.NET Framework Class Library  

CodeDomProvider Class

Provides a base class for CodeDomProvider implementations. This class is abstract.

For a list of all members of this type, see CodeDomProvider Members.

System.Object
   System.MarshalByRefObject
      System.ComponentModel.Component
         System.CodeDom.Compiler.CodeDomProvider
            Microsoft.CSharp.CSharpCodeProvider
            Microsoft.VisualBasic.VBCodeProvider

[Visual Basic]
MustInherit Public Class CodeDomProvider
   Inherits Component
[C#]
public abstract class CodeDomProvider : Component
[C++]
public __gc __abstract class CodeDomProvider : public Component
[JScript]
public abstract class CodeDomProvider extends Component

Thread Safety

Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe.

Remarks

A CodeDomProvider can be used to create and retrieve instances of code generators and code compilers. Code generators can be used to generate code in a particular language, and code compilers can be used to compile code into assemblies.

A CodeDomProvider implementation typically provides code generation and/or code compilation interfaces for generating code and managing compilation for a single programming language. Several languages are supported by CodeDomProvider implementations that ship with the .NET Framework SDK. These languages include C#, Visual Basic, Managed C++, J#.NET, and JScript. Developers or compiler vendors can implement the ICodeGenerator and ICodeCompiler interfaces and provide a CodeDomProvider that extends CodeDom support to other programming languages.

Example

[Visual Basic, C#, C++] The following example program can generate and compile source code based on a CodeDOM model of a program that prints "Hello World" using the System.Console class. A Windows Forms user interface is provided. The user can select the target programming langauge from several selections: C#, Visual Basic, and JScript.

[Visual Basic] 
Imports System
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Collections
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Imports Microsoft.CSharp
Imports Microsoft.VisualBasic
Imports Microsoft.JScript

' This example demonstrates building a Hello World program graph 
' using System.CodeDom elements. It calls code generator and
' code compiler methods to build the program using CSharp, VB, or
' JScript.  A Windows Forms interface is included. Note: Code 
' must be compiled and linked with the Microsoft.JScript assembly.
Namespace CodeDOMExample
    _
    Public Class CodeDomExample
        ' Builds a Hello World program graph using System.CodeDom types.
        Public Shared Function BuildHelloWorldGraph() As CodeCompileUnit
            ' Create a new CodeCompileUnit to contain the program graph
            Dim CompileUnit As New CodeCompileUnit()

            ' Declare a new namespace called Samples.
            Dim Samples As New CodeNamespace("Samples")
            ' Add the new namespace to the compile unit.
            CompileUnit.Namespaces.Add(Samples)

            ' Add a new namespace import for the System namespace.
            Samples.Imports.Add(New CodeNamespaceImport("System"))

            ' Declare a new type called Class1.
            Dim Class1 As New CodeTypeDeclaration("Class1")
            ' Add the new type to the namespace's type collection.
            Samples.Types.Add(Class1)

            ' Declare a new code entry point method.
            Dim Start As New CodeEntryPointMethod()
            ' Create a new method invocation expression.
            Dim cs1 As New CodeMethodInvokeExpression(New CodeTypeReferenceExpression("System.Console"), "WriteLine", New CodePrimitiveExpression("Hello World!"))
            ' Call the System.Console.WriteLine method.
            ' Pass a primitive string parameter to the WriteLine method.
            ' Add the new method code statement.
            Start.Statements.Add(New CodeExpressionStatement(cs1))

            ' Add the code entry point method to the type's members collection.
            Class1.Members.Add(Start)

            Return CompileUnit
        End Function 

        Public Shared Sub GenerateCode(ByVal provider As CodeDomProvider, ByVal compileunit As CodeCompileUnit)
            ' Obtain an ICodeGenerator from a CodeDomProvider class.
            Dim gen As ICodeGenerator = provider.CreateGenerator()
            ' Create a TextWriter to a StreamWriter to an output file.
            Dim tw As New IndentedTextWriter(New StreamWriter("TestGraph.cs", False), "    ")
            ' Generate source code using the code generator.
            gen.GenerateCodeFromCompileUnit(compileunit, tw, New CodeGeneratorOptions())
            ' Close the output file.
            tw.Close()
        End Sub 

        Public Shared Function CompileCode(ByVal provider As CodeDomProvider, ByVal filepath As String) As CompilerResults
            ' Obtain an ICodeCompiler from a CodeDomProvider class.        
            Dim compiler As ICodeCompiler = provider.CreateCompiler()
            ' Configure a CompilerParameters that links System.dll and 
            ' produces a file name based on the specified source file name.
            Dim cp As New CompilerParameters(New String() {"System.dll"}, filepath.Substring(0, filepath.LastIndexOf(".") + 1) + "exe", False)
            ' Indicate that an executable rather than a .dll should be generated.
            cp.GenerateExecutable = True
            ' Invoke compilation.
            Dim cr As CompilerResults = compiler.CompileAssemblyFromFile(cp, filepath)
            ' Return the results of compilation.
            Return cr
        End Function 
    End Class 
    _

    Public Class CodeDomExampleForm
        Inherits System.Windows.Forms.Form
        Private run_button As New System.Windows.Forms.Button()
        Private compile_button As New System.Windows.Forms.Button()
        Private generate_button As New System.Windows.Forms.Button()
        Private textBox1 As New System.Windows.Forms.TextBox()
        Private comboBox1 As New System.Windows.Forms.ComboBox()
        Private label1 As New System.Windows.Forms.Label()

        Private Sub generate_button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim provider As CodeDomProvider = GetCurrentProvider()
            CodeDomExample.GenerateCode(provider, CodeDomExample.BuildHelloWorldGraph())

            Dim sr As New StreamReader("TestGraph.cs")
            textBox1.Text = sr.ReadToEnd()
            sr.Close()
        End Sub 

        Private Sub compile_button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim provider As CodeDomProvider = GetCurrentProvider()
            Dim cr As CompilerResults = CodeDomExample.CompileCode(provider, "TestGraph.cs")

            If cr.Errors.Count > 0 Then
                textBox1.Text = "Errors encountered while building " + cr.PathToAssembly + ": " + ControlChars.CrLf
                Dim ce As CompilerError
                For Each ce In cr.Errors
                    textBox1.AppendText(ce.ToString() + ControlChars.CrLf)
                Next ce
                run_button.Enabled = False
            Else
                textBox1.Text = cr.PathToAssembly + " built with no errors."
                run_button.Enabled = True
            End If        
    End Sub 

        Private Sub run_button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Process.Start("TestGraph.exe")
        End Sub 

        Private Function GetCurrentProvider() As CodeDomProvider
            Dim provider As CodeDomProvider
            Select Case CStr(Me.comboBox1.SelectedItem)
                Case "CSharp"
                    provider = New CSharpCodeProvider()
                Case "Visual Basic"
                    provider = New VBCodeProvider()
                Case "JScript"
                    provider = New JScriptCodeProvider()
                Case Else
                    provider = New CSharpCodeProvider()
            End Select
            Return provider
        End Function

        Public Sub New()
            Me.SuspendLayout()
            ' label1
            Me.label1.Location = New System.Drawing.Point(395, 20)
            Me.label1.Size = New Size(180, 22)
            Me.label1.Text = "Select a programming language:"
            ' comboBox1
            Me.comboBox1.Location = New System.Drawing.Point(560, 16)
            Me.comboBox1.Size = New Size(190, 23)
            Me.comboBox1.Name = "comboBox1"
            Me.comboBox1.Items.AddRange(New String() {"CSharp", "Visual Basic", "JScript"})
            Me.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right Or System.Windows.Forms.AnchorStyles.Top
            Me.comboBox1.SelectedIndex = 0
            ' generate_button            
            Me.generate_button.Location = New System.Drawing.Point(8, 16)
            Me.generate_button.Name = "generate_button"
            Me.generate_button.Size = New System.Drawing.Size(120, 23)
            Me.generate_button.Text = "Generate Code"
            AddHandler generate_button.Click, AddressOf Me.generate_button_Click
            ' compile_button            
            Me.compile_button.Location = New System.Drawing.Point(136, 16)
            Me.compile_button.Name = "compile_button"
            Me.compile_button.Size = New System.Drawing.Size(120, 23)
            Me.compile_button.Text = "Compile"
            AddHandler compile_button.Click, AddressOf Me.compile_button_Click
            ' run_button            
            Me.run_button.Enabled = False
            Me.run_button.Location = New System.Drawing.Point(264, 16)
            Me.run_button.Name = "run_button"
            Me.run_button.Size = New System.Drawing.Size(120, 23)
            Me.run_button.Text = "Run"
            AddHandler run_button.Click, AddressOf Me.run_button_Click
            ' textBox1            
            Me.textBox1.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right
            Me.textBox1.Location = New System.Drawing.Point(8, 48)
            Me.textBox1.Multiline = True
            Me.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
            Me.textBox1.Name = "textBox1"
            Me.textBox1.Size = New System.Drawing.Size(744, 280)
            Me.textBox1.Text = ""
            ' CodeDomExampleForm            
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(768, 340)
            Me.MinimumSize = New System.Drawing.Size(750, 340)
            Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.textBox1, Me.run_button, Me.compile_button, Me.generate_button, Me.comboBox1, Me.label1})
            Me.Name = "CodeDomExampleForm"
            Me.Text = "CodeDom Hello World Example"
            Me.ResumeLayout(False)
        End Sub 'New

        Protected Overloads Sub Dispose(ByVal disposing As Boolean)
            MyBase.Dispose(disposing)
        End Sub 

        <STAThread()> _
        Shared Sub Main()
            Application.Run(New CodeDomExampleForm())
        End Sub 
    End Class 
End Namespace 

[C#] 
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using Microsoft.JScript;
    
// This example demonstrates building a Hello World program graph 
// using System.CodeDom elements. It calls code generator and
// code compiler methods to build the program using CSharp, VB, or
// JScript.  A Windows Forms interface is included. Note: Code
// must be compiled and linked with the Microsoft.JScript assembly. 
namespace CodeDOMExample
{    
    public class CodeDomExample
    {
        // Builds a Hello World program graph using System.CodeDom types
        public static CodeCompileUnit BuildHelloWorldGraph()
        {            
            // Create a new CodeCompileUnit to contain the program graph
            CodeCompileUnit CompileUnit = new CodeCompileUnit();

            // Declare a new namespace called Samples.
            CodeNamespace Samples = new CodeNamespace("Samples");
            // Add the new namespace to the compile unit.
            CompileUnit.Namespaces.Add( Samples );

            // Add the new namespace import for the System namespace.
            Samples.Imports.Add( new CodeNamespaceImport("System") );            

            // Declare a new type called Class1.
            CodeTypeDeclaration Class1 = new CodeTypeDeclaration("Class1");
            // Add the new type to the namespace's type collection.
            Samples.Types.Add(Class1);
            
            // Declare a new code entry point method
            CodeEntryPointMethod Start = new CodeEntryPointMethod();
            // Create a new method invocation expression.
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( 
                // Call the System.Console.WriteLine method.
                new CodeTypeReferenceExpression("System.Console"), "WriteLine", 
                // Pass a primitive string parameter to the WriteLine method
                new CodePrimitiveExpression("Hello World!") );
            // Add the new method code statement.
            Start.Statements.Add(new CodeExpressionStatement(cs1));

            // Add the code entry point method to the type's members collection
            Class1.Members.Add( Start );

            return CompileUnit;
        }

        public static void GenerateCode(CodeDomProvider provider, CodeCompileUnit compileunit)
        {
            // Obtain an ICodeGenerator from a CodeDomProvider class.
            ICodeGenerator gen = provider.CreateGenerator();
            // Create a TextWriter to a StreamWriter to an output file.
            IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter("TestGraph.cs", false), "    ");
            // Generate source code using the code generator.
            gen.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
            // Close the output file.
            tw.Close();            
        }

        public static CompilerResults CompileCode(CodeDomProvider provider, string filepath)
        {
            // Obtain an ICodeCompiler from a CodeDomProvider class.       
            ICodeCompiler compiler = provider.CreateCompiler();
            // Configure a CompilerParameters that links System.dll and 
            // produces a file name based on the specified source file name.
            CompilerParameters cp = new CompilerParameters(new string[] {"System.dll"}, filepath.Substring(0, filepath.LastIndexOf(".")+1)+"exe", false);
            // Indicate that an executable rather than a .dll should be generated.
            cp.GenerateExecutable = true;            
            // Invoke compilation.
            CompilerResults cr = compiler.CompileAssemblyFromFile(cp, filepath);
            // Return the results of compilation.
            return cr;
        }
    }

    public class CodeDomExampleForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button run_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.Button compile_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.Button generate_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox();
        private System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox();
        private System.Windows.Forms.Label label1 = new System.Windows.Forms.Label();
        
        private void generate_button_Click(object sender, System.EventArgs e)
        {
            CodeDomProvider provider = GetCurrentProvider();
            CodeDomExample.GenerateCode(provider, CodeDomExample.BuildHelloWorldGraph());
            
            StreamReader sr = new StreamReader("TestGraph.cs");
            textBox1.Text = sr.ReadToEnd();
            sr.Close();
        }

        private void compile_button_Click(object sender, System.EventArgs e)
        {
            CodeDomProvider provider = GetCurrentProvider();
            CompilerResults cr = CodeDomExample.CompileCode(provider, "TestGraph.cs");

            if(cr.Errors.Count > 0)
            {
                textBox1.Text = "Errors encountered while building "+cr.PathToAssembly+": \r\n";
                foreach(CompilerError ce in cr.Errors)                
                    textBox1.AppendText(ce.ToString()+"\r\n");                                
                run_button.Enabled = false;
            }
            else
            {
                textBox1.Text = cr.PathToAssembly+" built with no errors.";
                run_button.Enabled = true;
            }
        }

        private void run_button_Click(object sender, System.EventArgs e)
        {
            Process.Start("TestGraph.exe");            
        }
        
        private CodeDomProvider GetCurrentProvider()
        {
            CodeDomProvider provider;
            switch((string)this.comboBox1.SelectedItem)
            {
                case "CSharp":
                    provider = new CSharpCodeProvider();
                    break;
                case "Visual Basic":
                    provider = new VBCodeProvider();
                    break;
                case "JScript":
                    provider = new JScriptCodeProvider();
                    break;
                default:
                    provider = new CSharpCodeProvider();
                    break;
            }
            return provider;
        }

        public CodeDomExampleForm()
        {
            this.SuspendLayout();            
            // label1
            this.label1.Location = new System.Drawing.Point(395, 20);
            this.label1.Size = new Size(180, 22);
            this.label1.Text = "Select a programming language:";            
            // comboBox1
            this.comboBox1.Location = new System.Drawing.Point(560, 16);
            this.comboBox1.Size = new Size(190, 23);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Items.AddRange( new string[] { "CSharp", "Visual Basic", "JScript" } );
            this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Top;
            this.comboBox1.SelectedIndex = 0;
            // generate_button            
            this.generate_button.Location = new System.Drawing.Point(8, 16);
            this.generate_button.Name = "generate_button";
            this.generate_button.Size = new System.Drawing.Size(120, 23);            
            this.generate_button.Text = "Generate Code";
            this.generate_button.Click += new System.EventHandler(this.generate_button_Click);            
            // compile_button            
            this.compile_button.Location = new System.Drawing.Point(136, 16);
            this.compile_button.Name = "compile_button";
            this.compile_button.Size = new System.Drawing.Size(120, 23);            
            this.compile_button.Text = "Compile";
            this.compile_button.Click += new System.EventHandler(this.compile_button_Click);            
            // run_button            
            this.run_button.Enabled = false;
            this.run_button.Location = new System.Drawing.Point(264, 16);
            this.run_button.Name = "run_button";
            this.run_button.Size = new System.Drawing.Size(120, 23);            
            this.run_button.Text = "Run";
            this.run_button.Click += new System.EventHandler(this.run_button_Click);            
            // textBox1            
            this.textBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.textBox1.Location = new System.Drawing.Point(8, 48);
            this.textBox1.Multiline = true;
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(744, 280);            
            this.textBox1.Text = "";            
            // CodeDomExampleForm            
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(768, 340);
            this.MinimumSize = new System.Drawing.Size(750, 340);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {    this.textBox1, this.run_button, this.compile_button, this.generate_button, this.comboBox1, this.label1 });
            this.Name = "CodeDomExampleForm";
            this.Text = "CodeDom Hello World Example";
            this.ResumeLayout(false);
        }

        protected override void Dispose( bool disposing )
        {
            base.Dispose( disposing );
        }

        [STAThread]
        static void Main() 
        {
            Application.Run(new CodeDomExampleForm());
        }
    }
}

[C++] 
#using <mscorlib.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.dll>
#using <Microsoft.JScript.dll>
#using <Cscompmgd.dll>

using namespace System;
using namespace System::CodeDom;
using namespace System::CodeDom::Compiler;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Diagnostics;
using namespace System::Drawing;
using namespace System::IO;
using namespace System::Windows::Forms;
using namespace Microsoft::CSharp;
using namespace Microsoft::VisualBasic;
using namespace Microsoft::JScript;

// This example demonstrates building a Hello World program graph
// using namespace System::CodeDom elements. It calls code generator and
// code compiler methods to build the program using CSharp, VB, or
// JScript.  A Windows Forms interface is included. Note: Code
// must be compiled and linked with the Microsoft::JScript assembly.
namespace CodeDOMExample {
   public __gc class CodeDomExample {
      // Builds a Hello World program graph using namespace System::CodeDom types
   public:
      static CodeCompileUnit * BuildHelloWorldGraph() {
         // Create a new CodeCompileUnit to contain the program graph
         CodeCompileUnit* CompileUnit = new CodeCompileUnit();

         // Declare a new namespace called Samples.
         CodeNamespace* Samples = new CodeNamespace(S"Samples");
         // Add the new namespace to the compile unit.
         CompileUnit->Namespaces->Add(Samples);

         // Add the new namespace import for the System namespace.
         Samples->Imports->Add(new CodeNamespaceImport(S"System"));

         // Declare a new type called Class1.
         CodeTypeDeclaration* Class1 = new CodeTypeDeclaration(S"Class1");
         // Add the new type to the namespace's type collection.
         Samples->Types->Add(Class1);

         // Declare a new code entry point method
         CodeEntryPointMethod* Start = new CodeEntryPointMethod();
         // Create a new method invocation expression.
         CodePrimitiveExpression *cpe[] = new CodePrimitiveExpression*[1];
         cpe[0] = new CodePrimitiveExpression(S"Hello World!");
         CodeMethodInvokeExpression* cs1 = new CodeMethodInvokeExpression(
            // Call the System::Console::WriteLine method.
            new CodeTypeReferenceExpression(S"System.Console"), 
            S"WriteLine",
            static_cast<CodeExpression __gc * __gc[]>
            (// Pass a primitive String* parameter to the WriteLine method
            cpe
            )
            );
         // Add the new method code statement.
         Start->Statements->Add(new CodeExpressionStatement(cs1));

         // Add the code entry point method to the type's members collection
         Class1->Members->Add(Start);

         return CompileUnit;
      }

   public:
      static void GenerateCode(CodeDomProvider* provider, CodeCompileUnit* compileunit) {
         // Obtain an ICodeGenerator* from a CodeDomProvider class.
         ICodeGenerator* gen = provider->CreateGenerator();
         // Create a TextWriter to a StreamWriter to an output file.
         IndentedTextWriter* tw = new IndentedTextWriter(new StreamWriter(S"TestGraph.cs", false), S"    ");
         // Generate source code using the code generator.
         gen->GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
         // Close the output file.
         tw->Close();
      }

   public:
      static CompilerResults * CompileCode(CodeDomProvider* provider, String* filepath) {
         // Obtain an ICodeCompiler* from a CodeDomProvider class.
         ICodeCompiler* compiler = provider->CreateCompiler();
         // Configure a CompilerParameters that links System.dll and
         // produces a file name based on the specified source file name.
         String* temp0 [] = {S"System.dll"};
         CompilerParameters* cp = new CompilerParameters(temp0,String::Concat(filepath->Substring(0, filepath->LastIndexOf(S".") + 1), S"exe"), false);
         // Indicate that an executable rather than a .dll should be generated.
         cp->GenerateExecutable = true;
         // Invoke compilation.
         CompilerResults* cr = compiler->CompileAssemblyFromFile(cp, filepath);
         // Return the results of compilation.
         return cr;
      }
   };

public __gc class CodeDomExampleForm : public System::Windows::Forms::Form {
private:
   static System::Windows::Forms::Button* run_button = new System::Windows::Forms::Button();
private:
   static System::Windows::Forms::Button* compile_button = new System::Windows::Forms::Button();
private:
   static System::Windows::Forms::Button* generate_button = new System::Windows::Forms::Button();
private:
   static System::Windows::Forms::TextBox* textBox1 = new System::Windows::Forms::TextBox();
private:
   static System::Windows::Forms::ComboBox* comboBox1 = new System::Windows::Forms::ComboBox();
private:
   static System::Windows::Forms::Label* label1 = new System::Windows::Forms::Label();

private:
   void generate_button_Click(Object* sender, System::EventArgs* e) {
      CodeDomProvider* provider = GetCurrentProvider();
      CodeDomExample::GenerateCode(provider, CodeDomExample::BuildHelloWorldGraph());

      StreamReader* sr = new StreamReader(S"TestGraph.cs");
      textBox1->Text = sr->ReadToEnd();
      sr->Close();
   }

private:
   CodeDomProvider * GetCurrentProvider() {
      CodeDomProvider* provider;
      if ( String::Compare(dynamic_cast<String*>(this->comboBox1->SelectedItem), S"CSharp") == 0 )
         provider = new CSharpCodeProvider();
      else if ( String::Compare(dynamic_cast<String*>(this->comboBox1->SelectedItem), S"Visual Basic") == 0 )
         provider = new VBCodeProvider();
      else if ( String::Compare(dynamic_cast<String*>(this->comboBox1->SelectedItem), S"JScript") == 0 )
         provider = new JScriptCodeProvider();
      else
         provider = new CSharpCodeProvider();
      return provider;
   }

private:
   void compile_button_Click(Object* sender, System::EventArgs* e) {
      CodeDomProvider* provider = GetCurrentProvider();
      CompilerResults* cr = CodeDomExample::CompileCode(provider, S"TestGraph.cs");

      if (cr->Errors->Count > 0) {
         textBox1->Text = String::Concat(S"Errors encountered while building ", cr->PathToAssembly, ": \r\n");
         IEnumerator* myEnum = cr->Errors->GetEnumerator();
         while (myEnum->MoveNext()) {
            Microsoft::CSharp::CompilerError* ce = __try_cast<Microsoft::CSharp::CompilerError*>(myEnum->Current);

            textBox1->AppendText(String::Concat(ce->ToString(), S"\r\n"));
         }
         run_button->Enabled = false;

      } else {
         textBox1->Text = String::Concat(cr->PathToAssembly, S" built with no errors.");
         run_button->Enabled = true;
      }
   }

private:
   void run_button_Click(Object* sender, System::EventArgs* e) {
      Process::Start(S"TestGraph.exe");
   }

public:
   CodeDomExampleForm() {
      this->SuspendLayout();
      this->label1->Location = System::Drawing::Point(395, 20);
      this->label1->Size =  System::Drawing::Size(180, 22);
      this->label1->Text = S"Select a programming language:";
      // comboBox1
      this->comboBox1->Location = System::Drawing::Point(560, 16);
      this->comboBox1->Size = System::Drawing::Size(190, 23);
      this->comboBox1->Name = S"comboBox1";
      String* temp1 [] = {S"CSharp", S"Visual Basic", S"JScript" };
      this->comboBox1->Items->AddRange(temp1);
      this->comboBox1->Anchor = (System::Windows::Forms::AnchorStyles)(System::Windows::Forms::AnchorStyles::Left |
         System::Windows::Forms::AnchorStyles::Right | System::Windows::Forms::AnchorStyles::Top);
      this->comboBox1->SelectedIndex = 0;
      // generate_button
      this->generate_button->Location = System::Drawing::Point(8, 16);
      this->generate_button->Name = S"generate_button";
      this->generate_button->Size =  System::Drawing::Size(120, 23);
      this->generate_button->Text = S"Generate Code";
      this->generate_button->Click += new System::EventHandler(this, &CodeDomExampleForm::generate_button_Click);
      // compile_button
      this->compile_button->Location = System::Drawing::Point(136, 16);
      this->compile_button->Name = S"compile_button";
      this->compile_button->Size = System::Drawing::Size(120, 23);
      this->compile_button->Text = S"Compile";
      this->compile_button->Click += new System::EventHandler(this, compile_button_Click);
      // run_button
      this->run_button->Enabled = false;
      this->run_button->Location = System::Drawing::Point(264, 16);
      this->run_button->Name = S"run_button";
      this->run_button->Size = System::Drawing::Size(120, 23);
      this->run_button->Text = S"Run";
      this->run_button->Click += new System::EventHandler(this, run_button_Click);
      // textBox1
      this->textBox1->Anchor = (System::Windows::Forms::AnchorStyles)(System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom
         | System::Windows::Forms::AnchorStyles::Left
         | System::Windows::Forms::AnchorStyles::Right);
      this->textBox1->Location = System::Drawing::Point(8, 48);
      this->textBox1->Multiline = true;
      this->textBox1->ScrollBars = System::Windows::Forms::ScrollBars::Vertical;
      this->textBox1->Name = S"textBox1";
      this->textBox1->Size = System::Drawing::Size(744, 280);
      this->textBox1->Text = S"";
      // CodeDomExampleForm
      this->AutoScaleBaseSize = System::Drawing::Size(5, 13);
      this->ClientSize = System::Drawing::Size(768, 340);
      this->MinimumSize = System::Drawing::Size(750, 340);
      System::Windows::Forms::Control* myControl[] = {this->textBox1, this->run_button, this->compile_button,
         this->generate_button, this->comboBox1, this->label1};
      this->Controls->AddRange(myControl);
      this->Name = S"CodeDomExampleForm";
      this->Text = S"CodeDom Hello World Example";
      this->ResumeLayout(false);
   }

protected:
   void Dispose(bool disposing) {
      __super::Dispose(disposing);
   }
};
}
[STAThread]
int main() {
   Application::Run(new CodeDOMExample::CodeDomExampleForm());
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.CodeDom.Compiler

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: System (in System.dll)

See Also

CodeDomProvider Members | System.CodeDom.Compiler Namespace