Tuesday, September 20, 2011

How to Add Custom Action to Visual Studio Setup Project

Creating simple setup project in visual studio is very easy. Sometimes we need to perform some custom action at the time of install/uninstall such as start a web page. Today i will show you how you can add custom action in your Winform application. I will use C# as language.



First create a WindowsFormApplication. Then create a Setup Project from File->Add->New Project. Follow Other Project Types -> Setup and Deployment -> Visual Studion Installer -> Setup Project. Name it Setup1.


Now go to your Winform Project and add a installer class. Name it Installer1.cs. Open it as Code View. Here you can override four important functions, Install, Commit, Rollback and Uninstall. You can guess their functionality from name.


Suppose we want to open a web page before stating uninstallation. Add the following code:



[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Uninstall(IDictionary savedState)
{
    System.Diagnostics.Process.Start("http://www.microsoft.com");
    base.Uninstall(savedState);
}


base.Uninstall will start actuall uninstalltion. If you want the same functionality before starting installation you can add the following code:





[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Install(IDictionary savedState)
{
     System.Diagnostics.Process.Start("http://www.microsoft.com");
     base.Install(savedState);
}


Commit will fire after completing install transaction and Rollback when installer restores the pre-installation state of the computer.


Right click on Setup1 and go View->Add-> Project Output. Select WindowsFormApplication from project dropdown, select Primary Output and click OK.


Now we have to add the Installer1.cs to the Setup Project. Write click on Setup1 and go View->Custom Actions. We override only the Uninstall function. So, right click on Uninstall and click Add Custom Action. Go Application Folder -> Primary Output From... then click OK. Build Setup1, install it and uninstall to check the functionality.

No comments:

Post a Comment