Click here to Skip to main content
Click here to Skip to main content

Visual Studio Backup Macro

By , 25 Sep 2010
 

Introduction

Have you ever screwed up the code of your project and needed to revert to a past version?

Unfortunately, Visual Studio doesn't have a backup option. If you need to do so, you have to manually copy your solution folder to another folder or media.

Tired of doing that, I decided to make a backup macro: my goal was to add a context menu option to Solution Explorer, to automatize the process of copying its files to the destination location.

Background

As described above, this adds an item to the solution context menu (named 'Make backup').
When this option is selected, it cleans the solution's temporary files, then copies its folder contents to a destination with the following format:

F:\BACKUP\Solution Name\month-day-year hour:minute:second

The F:\BACKUP folder name is hardcoded in the macro and must be changed to your backup destination folder.

Using the Code

First, you have to add the macro code to Visual Studio IDE. This is easily done from the Tools->Macros->Macro IDE menu.

Now, as stated above, you have to change the destination folder, which is hard coded in the macro as an optional parameter. I use F:\BACKUP, which is in an external USB Hard Drive.

Then, you need to create the context menu item that calls the macro:

  • Open Tools->Customize menu
  • Select Commands tab
  • Check "Context Menu" radio button, then select "Project and Solution Context Menu | Solution"
  • Click on Add Command button
  • Select Macros on the menu of the left
  • Select the created macro from the menu on the right (Macros.MyMacros.Backup.Make) and click OK
  • Now the option is added, but with the name of the macro. I changed it to "Make backup" from the Change Selection button

NOTE: In Visual Studio 2008, things are a little different. To add a macro to a context menu, you have to open the Context Menu toolbar and drag the macro from the list to the toolbar.

And you are done, now you can click in your solution and select the new item in the context menu to automatically make a backup of it.

Conclusion

I hope you find this code as useful as I do.

I've tested this macro in Visual Studio 2008 and 2010 and it works perfectly in both, I think that it should work in 2005 too.

Source Code

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.IO

Public Module Backup
    Public Sub Make(Optional ByVal backupdir As String = "F:\BACKUP")
        Dim SolutionExplorer As UIHierarchy
        Dim Item As UIHierarchyItem
        Dim Solution As EnvDTE.SolutionClass
        Dim SourceFolder As String, TargetFolder As String
        If Not Directory.Exists(backupdir) Then
            MsgBox("Cannot access destination folder(" + backupdir + ")", _
		MsgBoxStyle.Critical, "Backup copy")
            Exit Sub
        End If

        SolutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object()
        For Each Item In SolutionExplorer.SelectedItems
            Solution = CType(Item.Object, EnvDTE.SolutionClass)
            If Solution.SolutionBuild.BuildState = _
			vsBuildState.vsBuildStateInProgress Then
                MsgBox("Cannot make backup while building solution", _
			MsgBoxStyle.Critical, "Backup copy")
                Exit Sub
            End If
            Solution.SolutionBuild.Clean(True)
            SourceFolder = Path.GetDirectoryName(Solution.FullName)
            TargetFolder = Path.Combine(backupdir, Solution.Properties.Item("Name").Value)
            Directory.CreateDirectory(TargetFolder)
            TargetFolder = TargetFolder + "\" + Format(Now, "MM-dd-yy HH_MM_ss")
            If Not CopyDir(SourceFolder, TargetFolder) Then
                MsgBox("Destination folder already exists. Backup aborted", _
			MsgBoxStyle.Critical, "Backup copy")
                Exit Sub
            End If
            MsgBox("Backup done successfully", MsgBoxStyle.Information, "Backup copy")
        Next
    End Sub

    Private Function CopyDir(ByVal source As String, ByVal target As String) As Boolean
        Dim diSource As DirectoryInfo
        Dim diTarget As DirectoryInfo

        diSource = New DirectoryInfo(source)
        diTarget = New DirectoryInfo(target)
        Return CopyDir(diSource, diTarget)
    End Function
    Private Function CopyDir(ByVal source As DirectoryInfo, _
	ByVal target As DirectoryInfo, Optional ByVal AllowCreate As Boolean = False) _
		As Boolean
        Dim fi As FileInfo
        Dim di As DirectoryInfo, td As DirectoryInfo

        If AllowCreate Then
            If Not Directory.Exists(target.FullName) _
		Then Directory.CreateDirectory(target.FullName)
        Else
            If Directory.Exists(target.FullName) Then Return False
        End If

        Directory.CreateDirectory(target.FullName)
        For Each fi In source.GetFiles()
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), True)
        Next

        For Each di In source.GetDirectories()
            td = target.CreateSubdirectory(di.Name)
            CopyDir(di, td, True)
        Next
        Return True
    End Function
End Module

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

ja_benetti
Engineer
Argentina Argentina
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionError running on VS 2010 SP1 PinmemberGeorge Eckert19 Oct '12 - 11:39 
When running the macro, it errors out on line 23:
 
Solution = CType(Item.Object, EnvDTE.SolutionClass)
 
An exception of type 'System.InvalidCastException' occurred in VBAssembly but was not handled in user code
 
Additional information: Unable to cast COM object of type 'System.__ComObject' to class type 'EnvDTE.SolutionClass'. COM components that enter the CLR and do not support IProvideClassInfo or that do not have any interop assembly registered will be wrapped in the __ComObject type. Instances of this type cannot be cast to any other class; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

QuestionDoes not work in vs2008 Pinmembergallzzy29 Nov '11 - 10:03 
I have vs2008 sp1
Win xp sp3
The macro failed on this line
Solution = CType(Item.Object, EnvDTE.SolutionClass)
Unable to cast com object of type 'system.__combject' to class type 'EnvDTE.SolutionClass'.COM
 
Wonder how I can fix it,
Thanks!
 
Terry
AnswerRe: Does not work in vs2008 Pinmembergallzzy30 Nov '11 - 12:00 
GeneralBackup works great PinmemberRAPDev24 Jan '11 - 6:03 
Thank you for sharing!
GeneralMy vote of 4 Pinmembervbmike11 Oct '10 - 12:13 
I just added to vs2010 and changed directory and it works fine.
GeneralNice Tool PinmemberMember 459897928 Sep '10 - 18:21 
Thanks for sharing your tool and teaching how to add macros.
I changed the date format in the TargetFolder to "yyyyMMddHHmm". I think I will sort better. I think you should use lower case "m"s for minutes.
Best Regards.
GeneralRe: Nice Tool Pinmemberja_benetti29 Sep '10 - 4:02 
QuestionSource Control? PinmemberPete BSC28 Sep '10 - 7:57 
Have you ever screwed up the code of your project and needed to revert to a past version?
 
Isn't that what source control like SubVersion, GIT, etc. are for?
AnswerRe: Source Control? Pinmembermasmozzi1 Oct '10 - 1:20 
+1. What every developer must have is a version control tool. It's plenty of free versions out there. There are also commercial versions that are free for one or two users.
GeneralMy vote of 1 PinmemberJ.Discount28 Sep '10 - 1:32 
This macro does not work in 2005!
General5 for you PinmemberA Praveen Kumar26 Sep '10 - 23:55 
Very good code. Every VS developer needs this. Thanks
GeneralMy vote of 5 PinmemberA Praveen Kumar26 Sep '10 - 23:53 
Good Idea, It useful for every developer.
Thanks
GeneralMy vote of 4 PinmemberMadZookeeper25 Sep '10 - 15:27 
No real explation of the code. No option to create the backup directory.
GeneralRe: My vote of 4 Pinmemberja_benetti25 Sep '10 - 16:49 
GeneralGreat Option! however... PinmemberAshok Gowtham25 Sep '10 - 2:50 
It is really a great option to have in handy.
however it works only for VS 2010.
Keep it up, Thumbs Up | :thumbsup:
GeneralRe: Great Option! however... Pinmemberja_benetti25 Sep '10 - 8:51 
GeneralRe: Great Option! however... Pinmemberja_benetti25 Sep '10 - 11:46 
GeneralThe problem PinmemberAshok Gowtham8 Oct '10 - 13:55 
GeneralMy vote of 5 PinmemberAdem Gashi24 Sep '10 - 11:07 
Brilliant cause I think every developer suffered a lost solution during his career.
Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 25 Sep 2010
Article Copyright 2010 by ja_benetti
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid