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

Deploy SQL Server databases easily with an Installer class

, 6 Apr 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
Deploy MS SQL Server databases using System.Configuration.Install and a VS.NET Setup Project.

Sample Image - sqlscriptinstall.jpg


If you made an application that is using an SQL Server database that needs to be located on the client server, VS.NET Setup Project doesn't help too much, you could go for InstallShild or other product that will make things easy but the costs will get higher. So searching for a free solution I've found an article on MSDN about using the Installer class and custom actions to make this happen. The code is in VB.NET, so this article is porting it to c# with some new features that I've found useful. All you need to do is to make a class derived from System.Configuration.Install and add to the solution two Embedded Resources named install.txt & uninstall.txt. The install.txt will contain the SQL script for your database and uninstall.txt the drop script. For the database script, I am using the ASPstate script made by Microsoft team for the ASP.NET InSQL session state:

< sessionState
mode ="SQLServer"
stateConnectionString ="tcpip="
sqlConnectionString ="data source=aleph;User ID=ASPsession;Password=ASPsession;"
cookieless ="false"
timeout ="60"

For my web application to work on a client server, I need to make a MSI with my app and the SQL script. To run the script at install time I've made a .dll named ScriptInstall, the code for it will follow.

Installer Class Code

First we declare a string that will have a default value and can be overwrite by the Install method:

string conStr="packet size=4096;integrated security=SSPI;"+
        "data source=\"(local)\";persist security info=False;"+
        "initial catalog=master";

I use two functions that will return the connection string and the script content:

private static string GetScript(string name)
    Assembly asm = Assembly.GetExecutingAssembly();
    Stream str = asm.GetManifestResourceStream(
                    asm.GetName().Name+ "." + name);
    StreamReader reader = new StreamReader(str);
    return reader.ReadToEnd();
private static string GetLogin(string databaseServer,
                 string userName,string userPass,string database)
    return "server=" + databaseServer + 
     ";database="+database+";User ID=" + userName +
     ";Password=" + userPass;

Then I use two functions that will run the install.txt and uninstall.txt onto the SQL server. The ExecuteSQL has a regex that splits the script after GO so that I can execute one by one with SQLCommand, I am doing this because ADO.NET will throw an exception if the SQL script contains "GO".

private static void ExecuteSql(SqlConnection sqlCon)
    string[] SqlLine;
    Regex regex = new Regex("^GO",RegexOptions.IgnoreCase | RegexOptions.Multiline);
    string txtSQL = GetScript("install.txt");
    SqlLine = regex.Split(txtSQL);

    SqlCommand cmd = sqlCon.CreateCommand();
    cmd.Connection = sqlCon;

    foreach(string line in SqlLine)
            cmd.CommandText = line;
            cmd.CommandType = CommandType.Text;
private static void ExecuteDrop(SqlConnection sqlCon)
    SqlCommand cmd = sqlCon.CreateCommand();
    cmd.Connection = sqlCon;
    cmd.CommandText = GetScript("uninstall.txt");
    cmd.CommandType = CommandType.Text;

Having the functions now we can override the Install(IDictionary stateSaver) and Uninstall(IDictionary savedState). In the Install method besides running the SQL script on to the server I save the connection data submitted by the user. It's dangerous to save connection strings in clear, so I use RijndaelManaged to encrypt it. You can find the class in the source as well. I am saving the connection string because I need it at uninstall to drop the database ASPstate.

public override void Install(IDictionary stateSaver)
    base.Install (stateSaver);

    if(Context.Parameters["databaseServer"].Length>0 &&
        Context.Parameters["userName"].Length>0 &&
        conStr = GetLogin(

        RijndaelCryptography rijndael = new RijndaelCryptography();
        //save information in the state-saver IDictionary
        //to be used in the Uninstall method

    SqlConnection sqlCon = new SqlConnection(conStr);


public override void Uninstall(IDictionary savedState)
    base.Uninstall (savedState);

        RijndaelCryptography rijndael = new RijndaelCryptography();
        rijndael.Key = (byte[])savedState["key"];
        rijndael.IV = (byte[])savedState["IV"];
        conStr = rijndael.Decrypt((byte[])savedState["conStr"]);            

    SqlConnection sqlCon = new SqlConnection(conStr);


Setup Project

Now that the installer class is done I can make a Setup project and add the primary output. In the User Interface Editor, select the Start node under Install. On the Action menu, choose Add Dialog. In the Add Dialog dialog box, select the Textboxes (A) dialog, then click OK to close the dialog box. On the Action menu, choose Move Up. Repeat until the Textboxes(A) dialog is above the Installation Folder node. Edit the properties of the Textboxes(A) form like this:

Textboxes(A) propeties

Go to the Custom Actions Editor and add the Primary output to the install and uninstall nodes. Click on the Primary output at the Install node and edit the properties. In the CustomActionData, type this:

/databaseServer=[EDITA1] /userName=[EDITA2] /userPass=[EDITA3]

I am getting the values of the Text Boxes in the Installer class using the Context.Parameters.

conStr = GetLogin(

All is done now. Just build the two projects and you are ready to install the database. I hope you'll find this code useful, there are a lot of things that can be added to the code like storing safer the Key and IV of the Rijndael or using in the ExecuteSql transactions. Looking foreword to your comments.


  • Version 1.0


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Stefan Prodan
Romania Romania
Co-Founder at Passionate about software architecture, SOA, domain driven design, continuous integration, .NET and Javascript programming. I write on
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

QuestionSQL Express PinmemberMember 432365910-Sep-14 22:49 
QuestionValue cannot be null: steram PinmemberMember 930335018-Jul-13 8:42 
GeneralMy vote of 1 Pinmemberleelaprasad0092-Jan-13 20:48 
GeneralRe: My vote of 1 Pinmembersupernorb6-Apr-13 11:23 
GeneralMy vote of 5 PinmemberHernán Hegykozi29-Oct-12 14:02 
GeneralRe: My vote of 5 Pinmembersupernorb6-Apr-13 11:23 
Questiondatbase connection live - then try to un intall Pinmemberdacku_198724-Aug-11 4:04 
GeneralMy vote of 5 PinmemberKanasz Robert13-Nov-10 7:03 
QuestionHow to use SqlInstall.dll Pinmemberpavan_contractor6-Jul-09 2:14 
Generalexport database on to another machine Pinmemberwaquasalig16-Oct-08 1:23 
Generalvalue cannot be null parameter name: stream Pinmemberjothy_cse14-Jul-08 23:03 
AnswerRe: value cannot be null parameter name: stream PinmemberSivarajselvakumar17-May-11 1:01 
GeneralThanks Pinmembergirish_tinnu16-Apr-08 23:02 
GeneralAgain about GO PinmemberWin32nipuh13-Aug-07 20:54 
GeneralRe: Again about GO PinmemberStefan Prodan13-Aug-07 22:39 
GeneralRe: Again about GO PinmemberWin32nipuh14-Aug-07 20:36 
GeneralRegEx Change PinmemberThe Punisher28-Feb-07 12:56 
QuestionHow to stop installation if database is not validate? PinmemberYulaw13-Jul-06 3:24 
AnswerRe: How to stop installation if database is not validate? Pinmemberkovalov9-May-07 15:59 
GeneralRe: How to stop installation if database is not validate? Pinmembermikker_12331-May-07 8:07 
QuestionGO problem ;) Pinmemberbeatles169218-Feb-06 22:21 
QuestionReferences? PinmemberEduard Ralph8-Dec-05 22:59 
GeneralGreat article got my 5 + Customize the database name PinmemberCohen Shwartz Oren4-Dec-05 23:08 
GeneralMSI Repair Problem Pinmemberdjspirit7-Nov-05 1:45 
QuestionWeb Services PinmemberAsi BS11-Oct-05 1:39 
GeneralRegex &quot;^Go&quot; doesn't work Pinmembershakoosh1-Aug-05 6:28 
GeneralRe: Regex &quot;^Go&quot; doesn't work PinmemberMMaslyk22-Jun-06 3:03 
GeneralRe: Better Regex - Regex &quot;^Go&quot; doesn't work PinmemberAlrightyThen26-Sep-07 9:30 
GeneralPerformance PinsussNeil Mosafi24-Apr-05 23:43 
GeneralRe: Performance PinmemberStefan Prodan25-Apr-05 3:01 
GeneralRe: Performance PinsussNeil Mosafi25-Apr-05 3:50 
GeneralUnattended install PinmemberGuido_d12-Apr-05 5:18 
GeneralRe: Unattended install PinmemberGuido_d12-Apr-05 6:18 
GeneralRe: Unattended install PinmemberStefan Prodan12-Apr-05 10:34 
GeneralRe: Unattended install PinmemberGyi4-Mar-09 4:24 
GeneralTimely material PinsussDylan Thomas6-Apr-05 6:44 
GeneralCool PinmemberSergey Solozhentsev6-Apr-05 5:39 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150414.1 | Last Updated 6 Apr 2005
Article Copyright 2005 by Stefan Prodan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid