Freigeben über


Organize Usings Across Your Entire Solution

One of the features I worked on for the Visual Studio 2008 release was the new "Organize Usings" feature.  This feature allows you to:

  1. Remove Unused Usings - Determines which using directives are not used in the current file and deletes them.   
  2. Sort Usings - Sorts the using directives in a file

We've received a great response from customers on the usefulness of this feature but one of the questions that I've received quite often is - "is there a way to make the feature work on an entire project or solution"?  The current answer to this is no.  Given the number of times I've heard the request though, I thought it would be worth posting a workaround that uses macros. 

So here's what you need to do - it's really quite simple:

Step 1: Create a new macro in Visual Studio through the Tools | Macros menu.

Step 2: Paste the code below into the Module and save it

Note that the code below is courtesy of Kevin Pilch-Bisson ( https://blogs.msdn.com/kevinpilchbisson/archive/2004/05/17/133371.aspx ) and Chris Eargle ( https://www.chriseargle.com/post/Format-Solution.aspx ), who have posted macros that allow you to format across an entire solution. I'm simply re-applying their approach to invoke the RemoveAndSort command rather than the FormatDocument command. Note that I haven't tested this macro extensively so please use at your own risk.  

 Public Module Module1
     Sub OrganizeSolution()
         Dim sol As Solution = DTE.Solution
         For i As Integer = 1 To sol.Projects.Count
             OrganizeProject(sol.Projects.Item(i))
         Next
     End Sub
  
     Private Sub OrganizeProject(ByVal proj As Project)
         For i As Integer = 1 To proj.ProjectItems.Count
             OrganizeProjectItem(proj.ProjectItems.Item(i))
         Next
     End Sub
  
     Private Sub OrganizeProjectItem(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.RemoveAndSort")
                 '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 apply RemoveAndSort on all of the ProjectItems. 
         If Not projectItem.ProjectItems Is Nothing Then
             For i As Integer = 1 To projectItem.ProjectItems.Count
                 OrganizeProjectItem(projectItem.ProjectItems.Item(i))
             Next
         End If
         'Apply RemoveAndSort on a SubProject if it exists. 
         If Not projectItem.SubProject Is Nothing Then
             OrganizeProject(projectItem.SubProject)
         End If
     End Sub
 End Module

Step 3: Run the macro on any solution that you'd like and there you have it!  Enjoy :)

Comments

  • Anonymous
    August 15, 2008
    PingBack from http://www.easycoded.com/organize-usings-across-your-entire-solution

  • Anonymous
    August 15, 2008
    You've been kicked (a good thing) - Trackback from DotNetKicks.com

  • Anonymous
    August 16, 2008
    This is also available in the VS 2008 Power Commands addin, http://code.msdn.microsoft.com/PowerCommands But that's cool to see how easy it is implement with the use of a macro.  Anyway, I didn't know you were the guy you worked on it.  Really awesome feature DJ!

  • Anonymous
    August 18, 2008
    This looks great! However, when I try to run it on one of my larger solutions, it works for a while and then eventually fails with the error: The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_SERVERCALL_RETRYLATER)) Any ideas how to get this to work with larger solutions?

  • Anonymous
    August 19, 2008
    Excellent, great for tidying up after I've tried 10 different ways to solve a problem ...

  • Anonymous
    August 19, 2008
    Works a charm in a test solution. Will test it on a large solution soon.

  • Anonymous
    August 19, 2008
    Applied for a large solution. Great work done. Thanks.

  • Anonymous
    August 20, 2008
    Also got an error when running it on a large project: System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))

  • Anonymous
    August 20, 2008
    I'm current doing a code review and cleanup so I will try this as part of that effort. To be honest, to this point I had completely ignored the "Organize Usings" menu item.  To bad for me; it's really handy!  I don't like unused code of any kind, so this is the kind of simple feature that gets me through a project with a lot less stress. -Neil

  • Anonymous
    August 20, 2008
    Is there a way in VS.NET to order the fields and properties and methods automatically? and put them into #region blocks? or have a macro of some tool? Know of any?

  • Anonymous
    August 21, 2008
    A short while ago I wrote an add-in for the same purpose that you can find here: http://nayyeri.net/blog/simpler-code-add-in-for-visual-studio-2008/

  • Anonymous
    August 24, 2008
    Links of the Week #50 (week 34/2008)

  • Anonymous
    August 24, 2008
    Development Clone Detective for Visual Studio - "Clone Detective is a Visual Studio integration

  • Anonymous
    August 25, 2008
    Organize Usings Across Your Entire Solution

  • Anonymous
    September 02, 2008
    My latest in a series of the weekly, or more often, summary of interesting links I come across related to Visual Studio. Sara Ford's Tip of the Day #303 covers the QuickWatch window . Carlos Quintero posted The diagram of the convoluted build configuration

  • Anonymous
    September 03, 2008
    It would be cool if there was an a capability of removing any unnecessary references too.

  • Anonymous
    September 08, 2008
    Cool! Probably not what you want to hear, but (third party)  tools like ReSharper can do this also, as wel as removing unused references. Maybe you can look at some of its features while developing a new version of VS?

  • Anonymous
    September 09, 2008
    Has anyone heard about a product named R#?

  • Anonymous
    September 09, 2008
    Why i can't read .aspx source code if it has .cs file? 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 please alert me by my email burcu_hamamcioglu@hotmail.com

  • Anonymous
    September 10, 2008
    The functionalitity to remove redundant usings in the entire solution is part of the ReSharper add on for a long time.

  • Anonymous
    January 17, 2009
    The comment has been removed

  • Anonymous
    February 03, 2009
    Awesome macro, but it halts when it encounters a C# source file with a "Build Action" set to None.  This is because the Intellisense > Organize Usings menu is not available for files with BuildAction=None.  I've Googled for a solution but couldn't find a way to poll the projectItem for BuildAction.  Any ideas?  Thanks.

  • Anonymous
    May 31, 2010
    I've been trying for a while make this work on VS2010. Have you tried it? It opens the document, closes but the actual DTE.ExecuteCommand doesn't work. Tried also with DTE.ExecuteCommand("Edit.RemoveUnusedUsings").