[CodeGen/Roslyn] Turn a code compile unit to VB.Net code
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).
This snippet turns any code compile unit into its VB.Net code:
Code:
''' <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
For example if I assemble a code graph thus:-
Code:
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)
Using the interface code generation function as:-
Code:
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 code in the string will look like:
Code:
'------------------------------------------------------------------------------
' <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