Click here to Skip to main content
6,630,901 members and growing! (19,838 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate License: The Code Project Open License (CPOL)

Deploy your application and database.

By Dima_sta

Describes how to add custom script to install project
C#, Windows, .NET, Visual Studio, DBA, Dev
Posted:3 Nov 2006
Updated:3 Nov 2006
Views:36,015
Bookmarked:66 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 4.26 Rating: 3.72 out of 5
1 vote, 7.1%
1
1 vote, 7.1%
2
3 votes, 21.4%
3
1 vote, 7.1%
4
8 votes, 57.1%
5

Introduction

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

Database

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 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. 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

At last click OK button and Backup will be executed. 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 target directory during setup process.

Step 3

Create new project (SetupScripts) that will contain your deployment logic. Add 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 Install method. Compile you 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 previous step. Now during install, your SetupScript.dll will be used, so if it contains class that inherits from Installer ( as we've done in step 3) , Installer's class Install method will be invoked. You can pass parameters to your install method by performing following step: 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

At last we can add code that installs database.

public override void Install(System.Collections.IDictionary stateSaver)
{
    try
    {                                  
        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 );               
        db.Execute();           
    }           
    catch( Exception e )         
    {                                
        throw new ApplicationException("Database creation fault: \n" + e.Message );      
    }                
}

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

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


        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_backUpFilePath,                  
            m_dbName,                    
            m_datFilePath            );        
        // Create SQL command             

        cmd = new SqlCommand( query, conn );     
        cmd.CommandType = CommandType.Text;           
        conn.Open();              
        cmd.ExecuteNonQuery();                         
        // Get              

        string[] parts = connString.Split( new char[] { ';' } );           
        foreach( string part in parts )             
        {                  
            if( part.StartsWith( "Initial" ) )        
            {                     
                connString = connString.Replace(      
                    part,                     
                    string.Format( "Initial Catalog={0}", m_dbName)
                    );
            }
        }                 
        // Update Connection string in application's config                

        UpdateAttribute( connString );             
    }            
    finally            
    {                
        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 attached code (in ZIP file) I've used regular windows form to see installation progress status. Use this example to create something more elegant J.

License

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

About the Author

Dima_sta


Member
Name: Statsenko Dmitry

Fields of interest: .NET, SQL server, GIS

Professional experience: 7 years of software development for software companies.
Occupation: Web Developer
Location: Israel Israel

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
GeneralCan we get a better explaination of the settings string? Pinmemberbamf7523:31 14 Sep '09  
GeneralHi Dima , Plz send me test solution Pinmemberram saurabh2:35 13 Sep '09  
Generaldeployment an Sqlserver And C#.net Application Pinmembersai25922:29 8 Sep '09  
QuestionError: cannot be restored over the existing ... Pinmemberhodinhle8:31 7 Jan '09  
GeneralSome more explanation Pinmemberreubenxl5:30 5 Aug '08  
GeneralInstaller problem PinmemberMiguel Mesa6:28 12 Jun '08  
GeneralMinor problem I have Pinmembertrfcrich4:14 3 Oct '07  
GeneralJust a Problem Pinmembermafpinedo2:07 3 Aug '07  
GeneralThank you! PinmemberAivar921210:24 2 May '07  
GeneralDeploy app and database Pinmemberruga7771:30 14 Nov '06  
GeneralRe: Deploy app and database PinmemberDima_sta23:10 14 Nov '06  
GeneralRe: Deploy app and database Pinmemberhiteshapatel2:05 16 Aug '07  
GeneralRe: Deploy app and database PinmemberMD Sanata19:20 21 Sep '07  
QuestionNot working Pinmemberdr4cul44:09 3 Nov '06  
AnswerRe: Not working PinmemberDima_sta21:19 4 Nov '06  
AnswerRe: Not working Pinmemberdr4cul41:31 7 Nov '06  
GeneralRe: Not working Pinmemberheronbank0:07 24 Nov '06  
GeneralRe: Not working Pinmemberram saurabh2:57 13 Sep '09  
GeneralCode Deploy PinmemberAlex De Large6:30 17 Jan '07  
GeneralRe: Not working PinmemberMD Sanata23:17 20 Sep '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 Nov 2006
Editor: Sean Ewington
Copyright 2006 by Dima_sta
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project