Click here to Skip to main content
15,891,372 members
Articles / Programming Languages / Visual Basic
Tip/Trick

CodeGen - Turn a CodeCompileUnit to VB.Net (or C#) code

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
16 Aug 2015CPOL 7.7K   1  
A quick-and-dirty function to display the VB.NET code resultant from any given code compile unit

Introduction

When working with Roslyn and Code Gen it is useful to be able to visualise the code graph you have built as raw VB.Net code (since most of us are accustomed to thinking in code).

Utility function:

This snippet converts the compile unit to readable VB.Net code:

VB
''' <summary>
''' Turn whatever code compile unit is passed in to VB.Net code in a multi-line string
''' </summary>
''' <param name="codeUnitToShow">
''' The program graph (partial or complete) to turn into VB code
''' </param>
''' <returns></returns>
Public Shared Function ToVBCodeString(ByVal codeUnitToShow As CodeCompileUnit) As String

    Using provider As New VBCodeProvider
        'Visual Basic specific initialisation
        Dim vbNetOptions As New CodeDom.Compiler.CodeGeneratorOptions()
        vbNetOptions.BlankLinesBetweenMembers = True

        Dim sbRet As New System.Text.StringBuilder
        Using textWriter As New System.IO.StringWriter(sbRet)
            Using codeWriter As New IndentedTextWriter(textWriter)
                provider.GenerateCodeFromCompileUnit(codeUnitToShow, codeWriter, vbNetOptions)
            End Using
        End Using
        Return sbRet.ToString()
    End Using


End Function

Usage:

For example if I assemble a code graph thus:

VB
Imports System.CodeDom

'...

        Dim interfaceObj As CodeTypeDeclaration = CodeGeneration.InterfaceCodeGeneration.InterfaceDeclaration("Duncan's Interface")
        Dim interfaceHolder As New CodeCompileUnit
        Dim nsMain As New CodeNamespace("test")
        interfaceHolder.Namespaces.Add(nsMain)
        nsMain.Types.Add(interfaceObj)

And given the following utility function to create the interface:

VB
Public Shared Function InterfaceDeclaration(ByVal entityName As String) As CodeTypeDeclaration

    Dim interfaceDeclarationRet As CodeTypeDeclaration = New CodeTypeDeclaration(ModelCodeGenerator.MakeInterfaceName(entityName))
    interfaceDeclarationRet.IsPartial = True
    interfaceDeclarationRet.IsInterface = True

    Return interfaceDeclarationRet

End Function

The resulting output would be:

VB
'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'     Runtime Version:4.0.30319.42000
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict Off
Option Explicit On


Namespace test
    
    Partial Public Interface IDuncan_s_Interface
    End Interface
End Namespace

C# version

To convert a code snippet to C# code the equivalent utility function would be:

VB.NET
''' <summary>
''' Turn whatever code compile unit is passed in to C# code in a multi-line string
''' </summary>
''' <param name="codeUnitToShow">
''' The program graph (partial or complete) to turn into C# code
''' </param>
Public Shared Function ToCSharpCodeString(ByVal codeUnitToShow As CodeCompileUnit) As String

    Using provider As New CSharpCodeProvider
        Dim cSharpOptions As New CodeDom.Compiler.CodeGeneratorOptions()
        cSharpOptions.BlankLinesBetweenMembers = True
        cSharpOptions.BracingStyle = "C" ' Change this to "Block" to have the open brace on the current line (freak)

        Dim sbRet As New System.Text.StringBuilder
        Using textWriter As New System.IO.StringWriter(sbRet)
            Using codeWriter As New IndentedTextWriter(textWriter)
                provider.GenerateCodeFromCompileUnit(codeUnitToShow, codeWriter, cSharpOptions)
            End Using
        End Using
        Return sbRet.ToString()
    End Using

End Function

Remarks

This utility function can be useful if you want to make unit tests for your code generation application without having to persist the generated code to a file and check it that way.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Ireland Ireland
C# / SQL Server developer
Microsoft MVP (Azure) 2017
Microsoft MVP (Visual Basic) 2006, 2007

Comments and Discussions

 
-- There are no messages in this forum --