Export (0) Print
Expand All

CodeDomProvider Class

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

Namespace:  System.CodeDom.Compiler
Assembly:  System (in System.dll)

'Declaration
<ComVisibleAttribute(True)> _
<PermissionSetAttribute(SecurityAction.InheritanceDemand, Name := "FullTrust")> _
<PermissionSetAttribute(SecurityAction.LinkDemand, Name := "FullTrust")> _
Public MustInherit Class CodeDomProvider _
	Inherits Component

The CodeDomProvider type exposes the following members.

  NameDescription
Protected methodCodeDomProviderInitializes a new instance of the CodeDomProvider class.
Top

  NameDescription
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyFileExtensionGets the default file name extension to use for source code files in the current language.
Public propertyLanguageOptionsGets a language features identifier.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Top

  NameDescription
Public methodCompileAssemblyFromDomCompiles an assembly based on the System.CodeDom trees contained in the specified array of CodeCompileUnit objects, using the specified compiler settings.
Public methodCompileAssemblyFromFileCompiles an assembly from the source code contained in the specified files, using the specified compiler settings.
Public methodCompileAssemblyFromSourceCompiles an assembly from the specified array of strings containing source code, using the specified compiler settings.
Public methodCreateCompiler Obsolete. When overridden in a derived class, creates a new code compiler.
Public methodCreateEscapedIdentifierCreates an escaped identifier for the specified value.
Public methodCreateGenerator Obsolete. When overridden in a derived class, creates a new code generator.
Public methodCreateGenerator(String)When overridden in a derived class, creates a new code generator using the specified file name for output.
Public methodCreateGenerator(TextWriter)When overridden in a derived class, creates a new code generator using the specified TextWriter for output.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodCreateParser Obsolete. When overridden in a derived class, creates a new code parser.
Public methodStatic memberCreateProvider(String)Gets a CodeDomProvider instance for the specified language.
Public methodStatic memberCreateProvider(String, IDictionary(Of String, String))Gets a CodeDomProvider instance for the specified language and provider options.
Public methodCreateValidIdentifierCreates a valid identifier for the specified value.
Public methodDisposeReleases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGenerateCodeFromCompileUnitGenerates code for the specified Code Document Object Model (CodeDOM) compilation unit and sends it to the specified text writer, using the specified options.
Public methodGenerateCodeFromExpressionGenerates code for the specified Code Document Object Model (CodeDOM) expression and sends it to the specified text writer, using the specified options.
Public methodGenerateCodeFromMemberGenerates code for the specified Code Document Object Model (CodeDOM) member declaration and sends it to the specified text writer, using the specified options.
Public methodGenerateCodeFromNamespaceGenerates code for the specified Code Document Object Model (CodeDOM) namespace and sends it to the specified text writer, using the specified options.
Public methodGenerateCodeFromStatementGenerates code for the specified Code Document Object Model (CodeDOM) statement and sends it to the specified text writer, using the specified options.
Public methodGenerateCodeFromTypeGenerates code for the specified Code Document Object Model (CodeDOM) type declaration and sends it to the specified text writer, using the specified options.
Public methodStatic memberGetAllCompilerInfoReturns the language provider and compiler configuration settings for this computer.
Public methodStatic memberGetCompilerInfoReturns the language provider and compiler configuration settings for the specified language.
Public methodGetConverterGets a TypeConverter for the specified data type.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodStatic memberGetLanguageFromExtensionReturns a language name associated with the specified file name extension, as configured in the CodeDomProvider compiler configuration section.
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetTypeOutputGets the type indicated by the specified CodeTypeReference.
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodStatic memberIsDefinedExtensionTests whether a file name extension has an associated CodeDomProvider implementation configured on the computer.
Public methodStatic memberIsDefinedLanguageTests whether a language has a CodeDomProvider implementation configured on the computer.
Public methodIsValidIdentifierReturns a value that indicates whether the specified value is a valid identifier for the current language.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodParseCompiles the code read from the specified text stream into a CodeCompileUnit.
Public methodSupportsReturns a value indicating whether the specified code generation support is provided.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Top

  NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Top

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.

NoteNote

In the .NET Framework 2.0, the methods made available in the code generator and code compiler are available directly from the code provider. You do not need to call CreateGenerator or CreateCompiler to access the methods, and those methods are marked as obsolete. This applies to preexisting as well as new code provider implementations.

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 Windows Software Development Kit (SDK). These languages include C#, Visual Basic, C++, 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.

The <system.codedom> Element in the machine configuration file (Machine.config) provides a mechanism for developers and compiler vendors to add configuration settings for additional CodeDomProvider implementations.

The CodeDomProvider class provides static methods to discover and enumerate the CodeDomProvider implementations on a computer. The GetAllCompilerInfo method returns the settings for all CodeDomProvider implementations on a computer. The GetCompilerInfo method returns the settings for a specific CodeDomProvider implementation, based on the programming language name. The CreateProvider method returns an instance of a CodeDomProvider implementation for a specific language.

For more details on language provider settings in the configuration file, see Compiler and Language Provider Settings Schema.

NoteNote

This class makes a link demand and an inheritance demand at the class level. A SecurityException is thrown if either the immediate caller or the derived class does not have full trust permission. For details about security demands, see Link Demands and Inheritance Demands.

Notes to Inheritors

In the .NET Framework versions 1.0 and 1.1, code providers consist of implementations of CodeDomProvider, ICodeGenerator, ICodeParser, and ICodeCompiler. In the .NET Framework 2.0, the CreateGenerator, CreateParser, and CreateCompiler methods are obsolete, and the methods of ICodeGenerator and ICodeCompiler are directly available in the CodeDomProvider class. You should override those methods in your code provider implementation and not call the base methods.

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

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

    Class CodeDomExample
        ' Build 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 the 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 type collection.
            samples.Types.Add(class1)

            ' Declare a new code entry point method. 
            Dim start As New CodeEntryPointMethod()

            ' Create a type reference for the System.Console class. 
            Dim csSystemConsoleType As New CodeTypeReferenceExpression( _
                "System.Console")

            ' Build a Console.WriteLine statement. 
            Dim cs1 As New CodeMethodInvokeExpression( _
                csSystemConsoleType, "WriteLine", _
                New CodePrimitiveExpression("Hello World!"))

            ' Add the WriteLine call to the statement collection.
            start.Statements.Add(cs1)

            ' Build another Console.WriteLine statement. 
            Dim cs2 As New CodeMethodInvokeExpression( _
                csSystemConsoleType, "WriteLine", _
                New CodePrimitiveExpression("Press the Enter key to continue."))

            ' Add the WriteLine call to the statement collection.
            start.Statements.Add(cs2)

            ' Build a call to System.Console.ReadLine. 
            Dim csReadLine As New CodeMethodInvokeExpression( _
                csSystemConsoleType, "ReadLine")

            ' Add the ReadLine statement.
            start.Statements.Add(csReadLine)

            ' Add the code entry point method to 
            ' the Members collection of the type.
            class1.Members.Add(start)

            Return compileUnit
        End Function 

        Public Shared Sub GenerateCode(ByVal provider As CodeDomProvider, ByVal compileunit As CodeCompileUnit)

            ' Build the source file name with the appropriate 
            ' language extension. 
            Dim sourceFile As String 
            If provider.FileExtension.StartsWith(".") Then
                sourceFile = "TestGraph" + provider.FileExtension
            Else
                sourceFile = "TestGraph." + provider.FileExtension
            End If 

            ' Create an IndentedTextWriter, constructed with 
            ' a StreamWriter to the source file. 
            Dim tw As New IndentedTextWriter(New StreamWriter(sourceFile, False), "    ")
            ' Generate source code using the code generator.
            provider.GenerateCodeFromCompileUnit(compileunit, tw, New CodeGeneratorOptions())
            ' Close the output file.
            tw.Close()
        End Sub 

        Public Shared Function CompileCode(ByVal provider As CodeDomProvider, _
                                           ByVal sourceFile As String, _
                                           ByVal exeFile As String) As CompilerResults

            ' Configure a CompilerParameters that links System.dll 
            ' and produces the specified executable file. 
            Dim referenceAssemblies As String() = {"System.dll"}
            Dim cp As New CompilerParameters(referenceAssemblies, exeFile, False)

            ' Generate an executable rather than a DLL file.
            cp.GenerateExecutable = True 

            ' Invoke compilation. 
            Dim cr As CompilerResults = provider.CompileAssemblyFromFile(cp, _
                sourceFile)
            ' 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())

            ' Build the source file name with the appropriate 
            ' language extension. 
            Dim sourceFile As String 
            If provider.FileExtension.StartsWith(".") Then
                sourceFile = "TestGraph" + provider.FileExtension
            Else
                sourceFile = "TestGraph." + provider.FileExtension
            End If 

            ' Read in the generated source file and 
            ' display the source text. 
            Dim sr As New StreamReader(sourceFile)
            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()

            ' Build the source file name with the appropriate 
            ' language extension. 
            Dim sourceFile As String 
            If provider.FileExtension.StartsWith(".") Then
                sourceFile = "TestGraph" + provider.FileExtension
            Else
                sourceFile = "TestGraph." + provider.FileExtension
            End If 

            Dim cr As CompilerResults = CodeDomExample.CompileCode(provider, _
                                                                   sourceFile, _
                                                                   "TestGraph.EXE")

            If cr.Errors.Count > 0 Then 
                ' Display compilation errors.
                textBox1.Text = "Errors encountered while building " + _
                                sourceFile + " into " + _
                                cr.PathToAssembly + ": " + ControlChars.CrLf

                Dim ce As System.CodeDom.Compiler.CompilerError
                For Each ce In cr.Errors
                    textBox1.AppendText(ce.ToString() + ControlChars.CrLf)
                Next ce
                run_button.Enabled = False 
            Else
                textBox1.Text = "Source " + sourceFile + " built into " + _
                                cr.PathToAssembly + " 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 = CodeDomProvider.CreateProvider("CSharp")
                Case "Visual Basic"
                    provider = CodeDomProvider.CreateProvider("VisualBasic")
                Case "JScript"
                    provider = CodeDomProvider.CreateProvider("JScript")
                Case Else
                    provider = CodeDomProvider.CreateProvider("CSharp")
            End Select 
            Return provider
        End Function 

        Public Sub New()
            Me.SuspendLayout()
            ' Set properties for label1. 
            Me.label1.Location = New System.Drawing.Point(395, 20)
            Me.label1.Size = New Size(180, 22)
            Me.label1.Text = "Select a programming language:" 
            ' Set properties for 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
            ' Set properties for 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
            ' Set properties for 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
            ' Set properties for 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
            ' Set properties for 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 = "" 
            ' Set properties for the 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 

        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

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft