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

Deploy your Application and Database

By , 3 Nov 2006
 

Introduction

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.

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 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)
{
    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 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;
    try            
    {                
        // 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_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 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.

History

  • 3rd November, 2006: Initial post

License

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

About the Author

Dima Statsenko
Retired
Israel Israel
Member
Name: Statsenko Dima
Fields of interest: software

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

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionDeploy your Application and Database?memberibrahimonat29 Jan '11 - 13:06 
I have a project with database application.
I want to make setup my project that C#,Winforms
 
I made your steps in this web pages
But I can not write CustomActionData true
 
How can I write CustomActinData?
 
when I wrote this "/AppPath=C:\DA\BIN\NMSServer\ /dbName=dbNakliye /BackUpFile=dbNakliye.bak /ConfigFile=dbConfig" in CustomActionData, i got below error.
 
Database name: dbNakliye
Backup file: dbNakliye.bak
Config file: dbConfig
AppPath: C:\DA\BIN\NMSServer\
DATFile:
Connection string to local database created
Conn string is: Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=master;Data Source=YUNUS-PC
Db directory name:
Following query will be runned on SQL server:
restore database dbNakliye from disk='dbNakliye.bak'
Data base creation failed:
The tail of the log for the database "dbNakliye" has not been backed up. Use BACKUP LOG WITH NORECOVERY to backup the log if it contains work you do not want to lose. Use the WITH REPLACE or WITH STOPAT clause of the RESTORE statement to just overwrite the contents of the log.
RESTORE DATABASE is terminating abnormally.
GeneralMy vote of 5memberANKHE8 Jul '10 - 3:53 
good explaination with screen shot it helped me a lot
GeneralRe: My vote of 5membergalam20097 Dec '10 - 17:46 
hi ,
 
i am getting some errors while creating setup like this. will u help me.
Generalattach sql backup file in msimembermbrawat17 Jun '10 - 4:17 
how to attach sql backup file in msi and restore the database from backup file which is the part of msi.
GeneralPlease send me the solutionmembervamajor8 Jun '10 - 6:42 
Hope it can help me, im doing all the steps but get some error at installation time, thanks a lot!!
GeneralRe: Please send me the solutionmembervamajor8 Jun '10 - 6:42 
my email is vamajor@hotmail.com
Generalsample applicationmembermbrawat7 Jun '10 - 3:04 
Hi ,
 
I want to deploy window form application and sql database so please mail me a sample application.
 
my mail id is
mahendra1981@gmail.com
 

Regards,
Mahendra Singh
GeneralRe: sample applicationmemberjackthomson22 Jul '12 - 8:13 
hi,
did you get any response or sample application.if yes then please forward to me.
GeneralSetupScripts project typemembermbrawat7 Jun '10 - 2:54 
what is the type for SetupScripts project.
Generalexplain the parametersmembermbrawat7 Jun '10 - 2:45 
/AppPath=
/dbName=
/BackUpFile=
/ConfigFile= where this cofig file would be.
/DATFile= - no idea what this is?
Generalhi Dimamemberdhilsen304 May '10 - 22:30 
I have one error in installation time of my application using your installer application.... that is database creation is failed because syntax error near '/' shall you give me ideas to resolve this error... also send me Ur screen shot to this mail id dhilsen.nov30@gmail.com
.....thank you
QuestionParameters...membervinghese23 Feb '10 - 0:47 
Can you enlighten me with the parameters used in the installation session of the database. ie parameters passed to the
NMS.SetupScripts.dll.
Generalcreated a windows application and attached a data base file with .sdf when deployed The database file cannot be found errormemberANKHE17 Jan '10 - 20:02 
hi,
 
i have created a .net windows application project with attached sqlserver database file with .sdf
when executed it runs successful.
But, when installed the application throws unhandled exception.
 
such as:
Unhandled exception has occured in your application.
the database file cannot be found. check the path to the database [Data Source = C:\Program files\Home\projectFolderName\databasefilename.sdf]
 
though the database file is attached..
 
how to set the path to the file in the project folder instead of the above path
 
natraj

QuestionCan we get a better explaination of the settings string?memberbamf7514 Sep '09 - 22:31 
/AppPath= - is this where the program is going to be installed on the client machine? What is this?
 
/dbName= - is this the server name? like SQLExpress or Local host, or the catalog inside of the database?
 
/BackUpFile= I gather this is the name only of the backup file? Not the software path
 
/ConfigFile= - I don't see any mention of a config file in your artical or in the example software. I'm supposed to build a config file with a connection string in it?
 
/DATFile= - no idea what this is? is this data you want to insert into your database?
 

Thanks
GeneralHi Dima , Plz send me test solutionmemberram saurabh13 Sep '09 - 1:35 
Hi Dima !!
 
Thanks for this great code.
 
i am unable to integrate this class library project in my application.
would you please send me the complete test application (Hello world which u mentioned in the application) at following id
ramsaurabh@gmail.com
 
Thanks a Lot in advance
Generaldeployment an Sqlserver And C#.net Applicationmembersai2598 Sep '09 - 21:29 
Hello Sir,
I developed one application in .Net with Sql Server2005 Database.I create a .EXE file to deploy in client sytem.Here to run application the CLR is necessary,in such a way sql Server have any limited files are necessary or complete sql server database installed. Can any One help please
 
Just send u r views

QuestionError: cannot be restored over the existing ...memberhodinhle7 Jan '09 - 7:31 
Hi Dima,
 
This artical is good. I tried it with visual studio 2005 and got the following error:
 
Database creation fault:
File "Library" cannot be restored over the existing ...\Library_log.ldf". Resissue the RESTORE statement using WITH REPLACE to overwrite pre-existing files, or WITH MOVE to identify an alternate location. Problems were identified while planning for the ...
 
Could you please send me the simple solution to my email?
 
bryanhdl@yahoo.com
 
Thanks
 
Bryan
GeneralSome more explanationmemberreubenxl5 Aug '08 - 4:30 
I have question about the CustomActionData row. What will happen If I don't put any parameters there. I have tried some different input already, but i don't what I really have to put there. Colud you give some more information about what to do with it.
 
It also would be helpful if you would sent me an example project where put your code into practice. Please send it to supersaiyangohan86@hotmail.com.
 
Thank you!!
GeneralInstaller problemmemberMiguel Mesa12 Jun '08 - 5:28 
Hi! I'm using your example... opened the code attached on .net, generating the DLL and then adding this dll to mi setup project. On its parameters I write:
 
/AppPath=C:\MOTUS\SCAT\ /dbName=S-CAT /BackUpFile=dbBackup /ConfigFile=S-CAT.exe.config /DATFile=C:\MOTUS\SCAT\
 
since I'm installing it on C:\MOTUS\SCAT folder, mi db is S-CAT, the backup has the same name as yours, my configfile is: CAT.exe.config and for this try the datfiles will be on the proyect folder...
 
It is not working! It copies the files and then appears this message:
 
"Object reference not set to an instance of an object"
 
And everything installed disappears...
 
Do you have any clue? I'm sorry but maybe I cannot understand your explanation... utmost at step 3.
 
Thanks in advance!
 
Miguel
GeneralMinor problem I havemembertrfcrich3 Oct '07 - 3:14 
Hi, I think your article may be related to what my problem is.
 
I have created an SQL database locally in Visual Studio 2005 and did all the testing on the local computer, all worked fine. However when I upload it to my web site nothing shows, it is just blank space where there should be a GridView of some table data. One of the pages in question is here:
 
http://www.the-stone-company.co.uk/sandstone.shtml[^]
 
The Gridview should display data beneath the pitctures of stone.
 
Also the Admin page I set up so that I can edit product details by logging in does not prompt me for a username/password even though I have set the Admin directory on the site up to do so.
 
My web space provider assures me the space is set up for SQL databases and ASP.NET applications. It is a very small and simple site so it is probably easy for you folks. Can someone advise on what my problem may be? Do I need to install something so the database shows and so logins are prompted?
 
Hope you can help.
Regards
Rich
GeneralJust a Problemmembermafpinedo3 Aug '07 - 1:07 

 
Hi,
i cannot make the program works.
Cand you send me the windows app sample?
The fault begins when the program try to get the backup _log.ldf
 

"Database creation fault:
Directory lookup for the file ...\PruPin_log.ldf. Use WITH MOVE to identify a valid location.
for the file.
Problems were identified while planning for the RESTORE statement. Previous message...."
 
I also tried to uncomment the WITH MOVE.... and nothing works.
 
Thanks a lot.
mafpinedo@gmail.com
GeneralThank you!memberAivar92122 May '07 - 9:24 
Horosho napisano, sekonomit kuchu vremeni! Smile | :)
GeneralDeploy app and databasememberruga77714 Nov '06 - 0:30 
Dear Dima_sta,
Thanks for the article about deploying your db app you wrote. It is very instructive. I have a concern however. In picture five, when selecting the file nms.setupScripts.dll, the line CustomActionData is not completely showing in the screeshot you posted in your article. Could you please email me a wider screenshot showing all the parameters for the above mentionned property?

GeneralRe: Deploy app and databasememberDima_sta14 Nov '06 - 22:10 
Hi,
the parameters are
/AppPath=C:\DA\BIN\NMSServer\ /dbName=NMS_MAIN /BackUpFile=nms_main /ConfigFile=MainService.exe.config /DATFile=C:\DA\DAT\NMSServer\
 
When
 
1) AppPath is for deployment target directory
2) dbName - name of database to create
3) BackUpFile - db backup file to restore from
4) ConfigFile - app config file, that contains db connection string
5) DatFile - folder that contains dat files
 
If you still need the screenshot, send me you e-mail address
because it is impossible to send mails with attached files via
code project site .
 
Have a good day, Smile | :)
 

 
Dima

GeneralRe: Deploy app and databasememberhiteshapatel16 Aug '07 - 1:05 
Hi,
I am getting object reference not set to an instance of the object
If possible then send me the working code
My email id is hiteshmaster151@yahoo.com
pls help me
Thanks
Hitesh

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 3 Nov 2006
Article Copyright 2006 by Dima Statsenko
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid