¿Alguien puede publicar una macro de Visual Studio que recorre todos los archivos fuente de C# en un proyecto y agrega un banner de archivo? Crédito adicional si funciona para cualquier tipo de archivo fuente (.cs, .xaml, etc.).Necesita macro de Visual Studio para agregar un banner a todos los archivos de C#
Respuesta
Aquí tiene, proporciono un ejemplo para .cs y .vb pero no debería ser difícil para que usted pueda ajustar a su otro tipo de archivo necesidades: Editado para agregar de forma recursiva cabecera de 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
Gracias, votaré por esta en lugar de la que tiene el enlace al blog, porque muestra cómo enumerar los proyectos. – DSO
¿Qué tan bien funciona esto para los archivos que tienen diseñadores, como WinForms? –
Debería agregarlo a cualquier archivo CS o VB en la solución. Lo que incluiría el archivo de diseñador; sin embargo, como con cualquier archivo 'generado', el archivo podría cambiar y su comentario podría no estar allí. –
Guau - gran respuesta. Lástima que OP no parezca asimilar a Google. –
Gracias por el enlace. Onorio, probé google pero usé la palabra "banner" en lugar de "encabezado" ... que arroja resultados completamente diferentes. No sé por qué, siempre los llamé pancartas. Por supuesto ahora, debido a esta publicación, el uso de la palabra "banner" devuelve esta misma publicación. – DSO
Aquí es el jist de ella. No, no lo he depurado, es un ejercicio para el lector. Y, esto está hecho fuera de mi cabeza. (Excepto el comentario del archivo ... Esa es una macro real que uso).
function CommentAllFiles
option explicit
Dim ActiveProjectFullName
Dim dte80 As EnvDTE80.Solution2
ActiveProjectFullName = dte80.Projects.Item(0).FullName
If ActiveProjectFullName = "" Then
MsgBox("No project loaded!")
Exit Sub
End If
Err.Number = 0
doc.Open(ActiveProjectFullName, "Text", True)
If Err.Number <> 0 Then
MsgBox("Open " + ActiveProjectFullName + " failed: " & Hex(Err.Number))
Exit Sub
End If
ActiveDocument.Goto(1, 1, vsMovementOptions.vsMovementOptionsMove)
' Build search string
Dim SearchString
Dim vsFindOptionsValue As Integer
SearchString = "^SOURCE=.*" + dn + "$"
while ActiveDocument.Selection.FindText(SearchString, vsFindOptions.vsFindOptionsFromStart + vsFindOptions.vsFindOptionsRegularExpression)
Dim TheFile
TheFile = ActiveDocument.Selection.Text
TheFile = Mid(TheFile, 8)
doc.Open(TheFile)
wend
ActiveDocument.Close()
end function
probado y verdadero sumador de "caja de la flor":
Function IsClassDef()
Dim ColNum
Dim LineNum
Dim sText
sText = ActiveDocument.Selection.ToString()
If sText = "" Then
'ActiveDocument.Selection.WordRight(dsExtend)
'sText = ActiveDocument.Selection
'sText = ucase(trim(sText))
End If
If (sText = "CLASS") Then
IsClassDef = True
Else
IsClassDef = False
End If
End Function
Sub AddCommentBlock()
'DESCRIPTION: Add Commecnt block to header, CPP files and Class Defs
AddCPPFileDesc()
End Sub
Sub AddCPPFileDesc()
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
Dim bOk, sExt, IsCpp, IsHdr, sHeader, IsCSharp
bOk = True
IsCpp = False
IsCSharp = False
If ActiveDocument.Selection.CurrentLine > 10 Then
If MsgBox("You are not at the top of the file. Are you sure you want to continue?", vbYesNo + vbDefaultButton2) = vbNo Then
bOk = False
End If
End If
If (bOk) Then
sExt = ucase(right(ActiveDocument.Name, 4))
IsCpp = sExt = ".CPP"
IsHdr = Right(sExt, 2) = ".H"
IsCSharp = sExt = ".CS"
If (IsCpp) Then
sHeader = left(ActiveDocument.Name, len(ActiveDocument.Name) - 3) + "h"
FileDescTopBlock(1)
editPoint.Insert("#include " + Chr(34) + "StdAfx.h" + Chr(34) + vbLf)
editPoint.Insert("#include " + Chr(34) + sHeader + Chr(34) + vbLf)
ElseIf (IsCSharp) Then
FileDescTopBlock(1)
Else
If IsHdr Then
'If IsCLassDef() Then
'AddClassDef()
'Else
AddHeaderFileDesc()
'End If
Else
FileDescTopBlock(1)
End If
End If
End If
End Sub
Sub AddHeaderFileDesc()
FileDescTopBlock(0)
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert("#pragma once" + vbLf)
End Sub
Sub FileDescTopBlock(ByVal HasRevHistory)
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
ActiveDocument.Selection.EndOfLine()
Dim sComment
sComment = ActiveDocument.Selection.ToString()
If Left(sComment, 2) = "//" Then
ActiveDocument.Selection.Delete()
sComment = LTrim(Mid(sComment, 3))
Else
sComment = ""
End If
Dim sLineBreak
Dim sFileName
Dim sBlock
sLineBreak = "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"
sFileName = ActiveDocument.Name
ActiveDocument.Selection.StartOfDocument()
sBlock = sLineBreak & vbLf & _
"// File : " & sFileName & vbLf & _
"// Author : Larry Frieson" & vbLf & _
"// Desc : " & sComment & vbLf & _
"// Date : " & CStr(Now.Date()) & vbLf & _
"//" & vbLf & _
"// Copyright © 20" + Right(CStr(Now.Year.ToString()), 2) + " MLinks Technologies. All rights reserved" + vbLf
If (HasRevHistory > 0) Then
sBlock = sBlock & _
"//" & vbLf & _
"// Revision History: " & vbLf & _
"// " & CStr(Now) & " created." & vbLf & _
"// " & vbLf
End If
sBlock = sBlock + sLineBreak + vbLf
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert(sBlock)
End Sub
Espero que esto ayude, o al menos le da algunas ideas. Una vez más, no probé/depuré el "looper del archivo fuente", me imagino que usted puede manejar eso.
Larry
- 1. Agregar archivo C a Visual Studio
- 2. macro Visual Studio con la trayectoria de un puntales archivo
- 3. ¿Para qué son todos estos archivos de Visual Studio 2005?
- 4. Agregar archivos existentes a diferentes proyectos de Visual Studio 2010
- 5. C# Visual Studio usando los archivos de recursos
- 6. Visual Studio Web Deploy no publica todos los archivos
- 7. Visual Studio Breakpoint Macro para modificar un valor?
- 8. ¿Necesita MSBuild instalar Visual Studio?
- 9. Visual Studio: ¿Imprimir todos los archivos fuente en una solución?
- 10. agregar recursivamente la extensión de archivo a todos los archivos
- 11. ¿Para qué se utilizan los archivos .rc2 en Visual Studio?
- 12. ¿Dónde busca Visual Studio los archivos de encabezado C++?
- 13. Formateo - de una vez - todos los archivos en un proyecto de Visual Studio
- 14. ¿Se necesita bscmake con Visual Studio 2010?
- 15. CMake - ¿Agregar automáticamente todos los archivos de una carpeta a un destino?
- 16. Visual Studio 2010 no publica todos los archivos en el sistema de archivos
- 17. Definición de compilación de Visual Studio: cómo agregar archivos adicionales (dll) para compilar?
- 18. C# Visual Studio ... agregar referencias mediante programación
- 19. ¿Cómo crear un complemento de Visual Studio para generar archivos?
- 20. Agregar biblioteca a Visual Studio 2008 Proyecto C++
- 21. Complemento de Visual Studio para agrupar archivos
- 22. Cómo exportar archivos exe en Visual Studio con todos los archivos usados
- 23. ¿Cómo agregar comandos a Visual Studio 2012?
- 24. Extensibilidad de Visual Studio: Agregar carpetas existentes a un proyecto
- 25. C# para escribir macros en Visual Studio?
- 26. auto formatear todos los archivos en solución en visual studio 2010
- 27. Cómo agregar REGION en Visual Studio en archivos aspx
- 28. Agregar F # a Visual Studio 2010 C# express - ¿es posible?
- 29. ¿Cómo agregar macros al proyecto de Visual Studio?
- 30. Visual Studio 2010 compilación de archivos .cpp como archivos .c
VS 2013 tiene un buen complemento desde [rubicon IT] (http://licensemanager.codeplex.com/) que le permite añadir, eliminar y actualizar un encabezado de cada archivo con el tipo de extensión declarada en su archivo de licencia. Instalar directamente yendo a Herramientas -> 'Extensiones y actualizaciones' -> 'En línea' -> buscar 'encabezados' y encontrar el resultado 'Administrador de encabezado de licencia'. Ahora simplemente haga clic con el botón derecho en su carpeta de proyecto y use el nuevo menú 'encabezados de licencia'. –