Chris Eargle

Life Student of the Kodefu Arts

Format Solution

by chris 14. August 2007 19:14

There's a cool option in Visual Studio 2005 to format the current document (ctrl-e,d). But what do you do when you have thousands of files in your C# solution? I'm much too lazy to open every file individually to make sure other developers on the project are formatting their code properly.

My first idea was to change the build script. Doing this would ensure the code is always formatted (unless someone has a lock). Unfortunately, I could find no task do this in MSBuild. Naturally, I endeavored to build my own, but after trying to figure out the VS SDK I decided I should review other options. I chose to look into a macro since the command is already present within Visual Studio.

A quick google search brought me to Kevin Pilch-Bisson's blog explaining why the VS team didn't give a "Format Solution" option: "we figured that if you were consistently using VS, there wouldn’t be much need, since the formatting should be right already." I guess they didn't calculate large projects with developers who may not format habitually.

Kevin goes on to explain how he ended up needing the functionality and coded a macro for it. I tried using his macro, but it didn't like the way the solution was structured. In the solution I'm working on, there are several projects in subfolders within the solution. When stepping through the code I discovered you had to drill down into the SubProject property of some projects.

Here's my fixed version:

Public Sub FormatSolution()

Dim sol As Solution = DTE.Solution

For i As Integer = 1 To sol.Projects.Count

FormatProject(sol.Projects.Item(i))

Next

End Sub

Private Sub FormatProject(ByVal proj as Project)For i As Integer = 1 To proj.ProjectItems.Count

FormatProjectItem(proj.ProjectItems.Item(i))

Next

End Sub

Private Sub FormatProjectItem(ByVal projectItem As ProjectItem)

If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then

If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then

Dim window As Window = projectItem.Open(Constants.vsViewKindCode)

window.Activate()

projectItem.Document.DTE.ExecuteCommand(
"Edit.FormatDocument")

window.Close(vsSaveChanges.vsSaveChangesYes)

End If

End If

'Be sure to format all of the ProjectItems.

If Not projectItem.ProjectItems Is Nothing Then

For i As Integer = 1 To projectItem.ProjectItems.Count

FormatProjectItem(projectItem.ProjectItems.Item(i))

Next

End If

 

'Format the SubProject if it exists.

If Not projectItem.SubProject Is Nothing Then

FormatProject(projectItem.SubProject)

End If

End Sub

The macro ended up modifying 600 files out of around 1600... not too shabby. I can only imagine what my poor wrists would have experienced had I done it manually.

Currently rated 5.0 by 4 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

visual studio, macro, vbscript

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (6) | Post RSSRSS comment feed

Related posts

WCF 3.5 Security GuidelinesThe patterns & practices WCF Security Guidance project has released the the WCF 3.5 Security Guideli...Environment Variables and MSBuildEverything worked fine the last time I gave my MSBuild presentation. There were no changes to my fil...Vista UX Guidelines in PDFMicrosoft has released the Vista UX Guidelines in the pdf format.

Comments

October 17. 2007 17:31

Tony Evans

Just what I was looking for. Thanks! :o)

Tony Evans us

March 3. 2008 23:46

pingback

Pingback from blogs.artinsoft.net

Pretty Printers for C# - Mauricio Rojas Blog

blogs.artinsoft.net

April 16. 2008 22:47

Joe

I added a couple of lines to FormatProjectItem() to avoid closing files that are initially open when the macro is run.

Private Sub FormatProjectItem(ByVal projectItem As ProjectItem)
Dim fileIsOpen As Boolean = False
If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
'If this is a c# file
If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
'Set flag to true if file is already open
fileIsOpen = projectItem.IsOpen
Dim window As Window = projectItem.Open(Constants.vsViewKindCode)
window.Activate()
projectItem.Document.DTE.ExecuteCommand("Edit.FormatDocument")
'Only close the file if it was not already open
If Not fileIsOpen Then
window.Close(vsSaveChanges.vsSaveChangesYes)
End If
End If
End If
'Be sure to format all of the ProjectItems.
If Not projectItem.ProjectItems Is Nothing Then
For i As Integer = 1 To projectItem.ProjectItems.Count
FormatProjectItem(projectItem.ProjectItems.Item(i))
Next
End If
'Format the SubProject if it exists.
If Not projectItem.SubProject Is Nothing Then
FormatProject(projectItem.SubProject)
End If
End Sub

Joe us

July 28. 2008 15:07

Safe Home Products

Chris,

Thank you!

This saved us hours and hours of work. It formatted about 1000 files, only stopping a few times due to some .aspx files we had with typos. (Those errors had probably been there for years!)

If we were going to run this frequently, it'd be nice to trap and log any popup warning messages. This would let the macro could run to completion, even if a few files have issues. For instance, the message we got was "Could not reformat the document due to line [X]. The original format was restored."

Safe Home Products us

August 15. 2008 07:55

pingback

Pingback from blogs.msdn.com

Park Place : Organize Usings Across Your Entire Solution

blogs.msdn.com

September 9. 2008 16:43

Tuuba

Hi, i have a problem about reading .aspx file. If projectItem ends with .aspx and it has .aspx.cs when my .aspx window is active it reads the .cs code that it has. But if my item hasn't a .cs file it has only .aspx file it reads the source code of aspx it works correctly.How Can I solve this problem? Here is my code :

Private Sub ReadCodeFile(ByVal projectItem As EnvDTE.ProjectItem)

' Read file Content
Dim codeWindow As Window = projectItem.Open(Constants.vsViewKindCode)

codeWindow.Activate()

'Load text into text buffer
Dim objTextDoc As EnvDTE.TextDocument = codeWindow.Document.Object()

'Manipulate text as data in text buffers
Dim objEditPt As EditPoint = objTextDoc.StartPoint.CreateEditPoint()

'Move the object to the beginning of the document
objEditPt.StartOfDocument()

'Returns the text between the current location and the specified location in the buffer
content = objEditPt.GetText(objTextDoc.EndPoint)

codeWindow.Close(vsSaveChanges.vsSaveChangesNo)


End Sub

Tuuba tr

Saving the comment

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 21. 2008 06:56

Powered by BlogEngine.NET 1.3.1.0
Theme by Mads Kristensen

About the author

Chris Eargle Chris Eargle
Enterprise .NET developer in Columbia, SC.

E-mail me Send mail

Pages

  • Presentations

Twitter Updates

    Recent comments

    • Dev InTENsity (3)
      Chris Eargle wrote: Thanks for attending my presentations, Seth! In… [More]
    • Set Operations in MSBuild (1)
      FreeToDev wrote: Very nice post. Makes me wonder why I wrote tasks … [More]
    • Dev InTENsity (3)
      Seth Richards wrote: I saw both your C# 3.0 (I came up with the 'why ex… [More]
    • Dev InTENsity (3)
      Scott Ames wrote: I went to your presentation in Walthan for Code Ca… [More]
    • Generics Don't Make Me Sad (1)
      Matt Sheppard wrote: Cheers, I can't remember if I was aware of either… [More]
    • C# 3.0 Presentation (1)
      vijay wrote: Good post Thanks, Vijay [More]
    • Format Solution (4)
      Joe wrote: I added a couple of lines to FormatProjectItem() t… [More]
    • Sessions Galore (1)
      Lou wrote: I'll have to get you down here soon - I'll e-mail … [More]
    • Redeemed (3)
      Fred Beiderbecke wrote: It wasn't you, it was some of the others in the ro… [More]
    • South Florida Code Camp (1)
      Jason Meridth wrote: You've mentioned the only latest difference betwee… [More]

    Archive

    • 2008
      • January (4)

    Tags

    • activex
    • addin
    • ado.net data services
    • ajax
    • architecture
    • astoria
    • azure
    • beta
    • bug
    • c#
    • code camp
    • com
    • consolas
    • continuous integration
    • conversion
    • ctp
    • database
    • deployment
    • design
    • design principles
    • download
    • ebook
    • entity
    • entlib
    • environment variables
    • expression blend
    • fail
    • font
    • framework
    • gadget
    • generics
    • grid
    • guidelines
    • icon
    • interfaces
    • jacksonville
    • lamdba
    • linq
    • linqtosql
    • list
    • live mesh
    • macro
    • mobile
    • msbuild
    • msdn
    • msi
    • mvc
    • powertoy
    • preview
    • properties
    • ray ozzie
    • refactoring
    • regasm
    • russ fustino
    • security
    • serialization
    • silverlight
    • snippet
    • source code
    • sql server
    • sqlmetal
    • starter kit
    • stream
    • string
    • trial
    • usability
    • ux
    • vbscript
    • vista
    • visual studio
    • vs2008
    • wcf
    • web
    • winforms
    • wpf
    • xml

    Categories

    • RSS feed for Bleeding EdgeBleeding Edge (5)
    • RSS feed for CEDGCEDG (2)
    • RSS feed for GeneralGeneral (1)
    • RSS feed for KodefuKodefu (19)
    • RSS feed for Path NotesPath Notes (7)
    • RSS feed for PresentationPresentation (5)
    • RSS feed for TechniquesTechniques (2)
    • RSS feed for TrainingTraining (5)
    • RSS feed for WeaponsWeapons (4)
    • RSS feed for ZenZen (5)

    Archive

    Blogroll

    • RSS feed for Structure Too BigStructure Too Big
      • Should you buy an exten...
      • WorldMaps Update
      • MSDN Roadshow -- coming...
    • RSS feed for Chris CraftChris Craft
      • Pimp My Phone – D...
      • Pimp My Phone – D...
      • Pimp My Phone – D...
    Download OPML file OPML

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008

    Sign in