Introduction
The CodeDOM allows for automatic generation and compilation of code - however, even when code is automatically generated, it is good practice to add comments. This tip / class makes for rapid addition of the XML comment sections.
Background
For background on code generation with CodeDOM, refer to the MSDN documentation.
Using the Code
To generate (for example) a VB "remarks" comment that has two lines:
Dim commentLines As New List(Of String)
commentLines.Add("Line 1")
commentLines.Add("Line 2")
Dim remarksComment = CommentGeneration.RemarksCommentSection(commentLines)
Source Code
Everything needs a reference to the Roslyn compilers:
Imports Microsoft.CodeDom.Providers.DotNetCompilerPlatform
Then we need two functions that create the start and end tag for the XML comment:
Public Shared Function OpenCommentSection(ByVal sectionName As String,
ByVal sectionAttributes As Dictionary(Of String, String)) As CodeCommentStatement
Dim commentInner As String = sectionName
If (sectionAttributes IsNot Nothing) Then
For Each sectionNameAttribute As String In sectionAttributes.Keys
commentInner &= " " & sectionNameAttribute & _
"=""" & sectionAttributes(sectionNameAttribute) & """"
Next
End If
Return New CodeCommentStatement("<" & commentInner.Trim & ">", True)
End Function
Public Shared Function CloseCommentSection(ByVal sectionName As String) _
As CodeCommentStatement
Return New CodeCommentStatement("</" & sectionName.Trim & ">", True)
End Function
Then we build on these to make a generic method that can put any number of comments in a named section.
Public Shared Function BaseCommentSection(ByVal sectionName As String,
ByVal sectionAttributes As Dictionary(Of String, String),
ByVal commentText As IEnumerable(Of String))
As CodeCommentStatementCollection
Dim ret As New CodeCommentStatementCollection()
ret.Add(OpenCommentSection(sectionName, sectionAttributes))
For Each commentLine As String In commentText
ret.Add(New CodeCommentStatement(commentLine, True))
Next
ret.Add(CloseCommentSection(sectionName))
Return ret
End Function
Then we wrap each comment section up in a function, depending on whether it does or does not expect named properties:
Public Shared Function RemarksCommentSection(ByVal commentText As IEnumerable(Of String)) _
As CodeCommentStatementCollection
Return BaseCommentSection("remarks", Nothing, commentText)
End Function
History
- 10th August, 2015: Initial version