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:
Public Shared Function ToVBCodeString(ByVal codeUnitToShow As CodeCompileUnit) As String
Using provider As New VBCodeProvider
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:
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:
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:
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:
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"
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.