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

Deploy your Application and Database

, 3 Nov 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Describes how to add custom script to install project


This article describes a simple way to deploy your application and database. Once the development and testing of application are done, it is necessary to create some script that installs your application to the target computer. In VS2003/2005, it can be done by adding setup project to your solution and performing build on it. Get more information about setup projects on the MSDN site. But sometimes, the situation is more complicated.


Usually your application has some storage for saving its data. In my example, we are talking about SQL server database. My database is schema (table definitions), stored procedures and some predefined data (like ENUMs, application users and so on, that are stored in database). So as you can see, my Setup project is not only script that deploys application's binaries to target computer but also contains some logic for finding local SQL server (can be modified to find any SQL server in local network), creating database and inserting all predefined application data. The following steps will describe how it can be done.

Step 1

Perform backup operation on your database. It can be done in SQL EM. Choose your database, perform right click and choose backup database. See picture 1:

Sample screenshot

Picture 1

After choosing backup database, in SQL Server backup form, click add button and choose backup file name. (In my example, I called it dbBackup.) See picture 2.

Sample screenshot

Picture 2

Finally, click OK button and Backup will be executed. The created file will contain your database information.

Step 2

Now add your file to your Setup project. Perform Right click on setup project in (Visual Studio). See Picture 3:

Sample screenshot

Picture 3

In file dialog, choose dbBackUp file and perform build. Now your msi contains dbBackupFile, that will be copied to the target directory during setup process.

Step 3

Create a new project (SetupScripts) that will contain your deployment logic. Add a new class that inherits from System.Configuration.Install.Installer (Installer class in Add New Item dialog) and perform override on Install method. In Step 5, I'll give more explanation about the Install method. Compile your project.

Step 4

Now perform right mouse click on your setup project and click Custom actions. See picture 4.

Sample screenshot

Picture 4

In custom actions screen, click on install folder and add SetupScripts.dll from the previous step. Now during install, your SetupScript.dll will be used, so if it contains a class that inherits from Installer (as we've done in step 3), the Installer's class Install method will be invoked. You can pass parameters to your install method by performing the following steps: Right mouse click on SetupScripts.dll in Custom actions -> Install folder. Go to properties window and add parameters to CustomActionData row. See picture 5.

Sample screenshot

Picture 5

Step 5

Finally, we can add code that installs the database.

public override void Install(System.Collections.IDictionary stateSaver)
        base.Install( stateSaver );   
        SetupDataBase db = new SetupDataBase();
        // Database name to create
        db.DbName = Context.Parameters["dbName"]; 
        log.WriteLine( "Database name: " + db.DbName );
        // Backup file ( full name ) 
        db.BackUpFilePath = Context.Parameters["BackUpFile"]; 
        log.WriteLine( "Backup file: " + db.BackUpFilePath );
        // Application config file ( to update connection string )
        db.AppConfigFileName =    Context.Parameters["ConfigFile"];
        log.WriteLine( "Config file: " + db.AppConfigFileName );
        // Application file                
        db.AppPath = Context.Parameters["AppPath"];
        log.WriteLine( "AppPath: " + db.AppPath );
        db.m_datFilePath = Context.Parameters["DATFile"];   
        log.WriteLine( "DATFile: " + db.m_datFilePath );
    catch( Exception e ) 
        throw new ApplicationException("Database creation fault: \n" + e.Message );

Setup database is a class that performs database install. (You can find its full code in the attached ZIP file). Now I'll show only its execute and GetConnStringToLocalServer() methods.

public void Execute() 
    SqlCommand cmd = null;            
    SqlConnection conn = null;
        // Create connection string to database

        string connString = GetConnStringToLocalServer(); 
        conn = new SqlConnection( connString );    
        // Create query to perform on DB           
        string query = string.Format(               
            @"restore database {1} from disk='{2}{0}'",
            m_datFilePath            );        
        // Create SQL command             
        cmd = new SqlCommand( query, conn );     
        cmd.CommandType = CommandType.Text;
        // Get              
        string[] parts = connString.Split( new char[] { ';' } );
        foreach( string part in parts )             
            if( part.StartsWith( "Initial" ) )
                connString = connString.Replace(      
                    string.Format( "Initial Catalog={0}", m_dbName)
        // Update Connection string in application's config
        UpdateAttribute( connString );
        if( cmd != null ) cmd.Dispose(); 
        if( conn != null ) conn.Dispose(); 

private string GetConnStringToLocalServer()
    SqlDataSourceEnumerator sqlEnum = SqlDataSourceEnumerator.Instance;
    DataTable table = sqlEnum.GetDataSources();
    // Get local machine name 

    string machineName = Environment.MachineName;    
    foreach( DataRow row in table.Rows )   
        if( row[0].ToString() == machineName )
            string connString = string.Format(
                "Persist Security Info=False;Integrated Security=SSPI;" +
                "Initial Catalog=master;Data Source={0}",
                machineName );
            return connString;   
    throw new ApplicationException( "No local sql Server is installed" );

Ok folks, that’s all. May be one more tip, install code is extremely hard to debug, so use logging mechanism to log almost every step of install operation. In the attached code (in ZIP file), I've used regular Windows Form to see the installation progress status. Use this example to create something more elegant.


  • 3rd November, 2006: Initial post


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


About the Author

Dima Statz
Israel Israel
Name: Statz Dima
Fields of interest: software

Comments and Discussions

QuestionSQL Server 2008 Express Edition is configured as prerequisite PinmemberSyed Jahanzeb2-Mar-15 10:37 
GeneralThank you PinmemberMember 113448001-Jan-15 18:30 
Questiondeploy your application and database Pinmemberlouis Tunde10-Sep-14 12:32 
Questiondeploy your application and database Pinmemberlouis Tunde10-Sep-14 12:23 
GeneralNot working!!! PinmemberMember 982544227-Jan-14 0:04 
Questiongot stuck at step 3 Pinmemberdaviegy7-May-13 8:25 
GeneralMy vote of 4 PinmemberShubh Agrahari30-Jan-13 21:16 
Questionwhat if I am using mysql? PinmemberBsa0330-Jan-13 8:40 
GeneralMy vote of 5 Pinmemberrenjuvinod12-Aug-12 21:05 
Questioncustom action data property is not clear Pinmemberjackthomson22-Jul-12 9:08 
QuestionStuck with CustomActionData Pinmembersersheed16-Jul-12 3:15 
QuestionDeploy Database File to Client PC without to install SQL Server Pinmemberh0k3n91-Jun-12 19:41 
QuestionDeploy your Application and Database Pinmemberaloknetuser11-Apr-12 3:20 
GeneralMy vote of 5 PinmemberMember 830647410-Oct-11 17:21 
GeneralStuck at step 3. [modified] PinmemberJayEnAr26-May-11 0:45 
QuestionDeploy your Application and Database? Pinmemberibrahimonat29-Jan-11 14:06 
GeneralMy vote of 5 PinmemberANKHE8-Jul-10 4:53 
GeneralRe: My vote of 5 Pinmembergalam20097-Dec-10 18:46 
Generalattach sql backup file in msi Pinmembermbrawat17-Jun-10 5:17 
GeneralPlease send me the solution Pinmembervamajor8-Jun-10 7:42 
GeneralRe: Please send me the solution Pinmembervamajor8-Jun-10 7:42 
Generalsample application Pinmembermbrawat7-Jun-10 4:04 
GeneralRe: sample application Pinmemberjackthomson22-Jul-12 9:13 
GeneralSetupScripts project type Pinmembermbrawat7-Jun-10 3:54 
Generalexplain the parameters Pinmembermbrawat7-Jun-10 3:45 
Generalhi Dima Pinmemberdhilsen304-May-10 23:30 
QuestionParameters... Pinmembervinghese23-Feb-10 1:47 
Generalcreated a windows application and attached a data base file with .sdf when deployed The database file cannot be found error PinmemberANKHE17-Jan-10 21:02 
QuestionCan we get a better explaination of the settings string? Pinmemberbamf7514-Sep-09 23:31 
GeneralHi Dima , Plz send me test solution Pinmemberram saurabh13-Sep-09 2:35 
Generaldeployment an Sqlserver And Application Pinmembersai2598-Sep-09 22:29 
QuestionError: cannot be restored over the existing ... Pinmemberhodinhle7-Jan-09 8:31 
GeneralInstaller problem PinmemberMiguel Mesa12-Jun-08 6:28 
GeneralMinor problem I have Pinmembertrfcrich3-Oct-07 4:14 
GeneralJust a Problem Pinmembermafpinedo3-Aug-07 2:07 
GeneralThank you! PinmemberAivar92122-May-07 10:24 
GeneralDeploy app and database Pinmemberruga77714-Nov-06 1:30 
GeneralRe: Deploy app and database PinmemberDima_sta14-Nov-06 23:10 
GeneralRe: Deploy app and database Pinmemberhiteshapatel16-Aug-07 2:05 
GeneralRe: Deploy app and database PinmemberMD Sanata21-Sep-07 19:20 
GeneralRe: Deploy app and database PinmemberMember 92661676-Aug-12 1:43 
GeneralRe: Deploy app and database PinmemberR_B_10-Apr-13 21:54 
QuestionNot working Pinmemberdr4cul43-Nov-06 4:09 
AnswerRe: Not working PinmemberDima_sta4-Nov-06 21:19 
AnswerRe: Not working Pinmemberdr4cul47-Nov-06 1:31 
GeneralRe: Not working [modified] Pinmembersaeid201015-May-10 21:42 
GeneralRe: Not working Pinmemberdr4cul416-May-10 20:59 
GeneralRe: Not working Pinmemberheronbank24-Nov-06 0:07 
GeneralRe: Not working Pinmemberram saurabh13-Sep-09 2:57 
GeneralCode Deploy PinmemberAlex De Large17-Jan-07 6:30 

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
Web03 | 2.8.150414.1 | Last Updated 3 Nov 2006
Article Copyright 2006 by Dima Statz
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid