Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Visual Studio macro to add banner to all C# files

Can someone post a Visual Studio macro which goes through all C# source files in a project and adds a file banner? Extra credit if it works for any type of source file (.cs, .xaml, etc).

like image 240
DSO Avatar asked Jan 06 '09 01:01

DSO


2 Answers

Here you go, I provide an example for .cs and .vb but shouldn't be hard for you to adjust it to your other file type needs: Edited to recursively add header to sub-folders

Sub IterateFiles()
    Dim solution As Solution = DTE.Solution
    For Each prj As Project In solution.Projects
        IterateProjectFiles(prj.ProjectItems)
    Next
End Sub

Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
    For Each file As ProjectItem In prjItms
        If file.SubProject IsNot Nothing Then
            AddHeaderToItem(file)
            IterateProjectFiles(file.ProjectItems)
        ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
            AddHeaderToItem(file)
            IterateProjectFiles(file.ProjectItems)
        Else
            AddHeaderToItem(file)
        End If
    Next
End Sub

Private Sub AddHeaderToItem(ByVal file As ProjectItem)
    DTE.ExecuteCommand("View.SolutionExplorer")
    If file.Name.EndsWith(".cs") OrElse file.Name.EndsWith(".vb") Then
        file.Open()
        file.Document.Activate()

        AddHeader()

        file.Document.Save()
        file.Document.Close()
    End If
End Sub

Private Sub AddHeader()
    Dim cmtHeader As String = "{0} First Line"
    Dim cmtCopyright As String = "{0} Copyright 2008"
    Dim cmtFooter As String = "{0} Footer Line"

    Dim cmt As String

    Select Case DTE.ActiveDocument.Language
        Case "CSharp"
            cmt = "//"
        Case "Basic"
            cmt = "'"
    End Select
    DTE.UndoContext.Open("Header Comment")
    Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
    ts.StartOfDocument()
    ts.Text = String.Format(cmtHeader, cmt)
    ts.NewLine()
    ts.Text = String.Format(cmtCopyright, cmt)
    ts.NewLine()
    ts.Text = String.Format(cmtFooter, cmt)
    ts.NewLine()
    DTE.UndoContext.Close()
End Sub
like image 98
Brian Schmitt Avatar answered Sep 19 '22 02:09

Brian Schmitt


Visual Studio macro to add file headers

like image 30
Pop Catalin Avatar answered Sep 22 '22 02:09

Pop Catalin