How can I create a database automatically after the application is installed?

Source: Internet
Author: User

Focuses on how to automatically create a database for the customer in the installation package

Steps:
1. Add a new project, select a class library template, and name it dbcustomaction.
2. Right-click the project and choose add new project from the shortcut menu. Select the installer class (named dbcustomaction. CS)
3. In the server resource manager, add-> connect to the database-> specify the user password (select allow to save the password)-> select master for the database
4. Switch to the view status of dbcustomaction. CS-> drag master. DBO from the database connection of the server resource manager to the designer.
A new SQL .txt (use lower-case letters) in the 5th percentile, and enter the following SQL code:
Create Table [DBO]. [mk_employees] (
[Name] [char] (30) Collate SQL _latin1_general_cp1_ci_as not null,
[RSVP] [int] Null,
[Requests] [nvarchar] (4000) Collate SQL _latin1_general_cp1_ci_as null
) On [primary];

Alter table [DBO]. [mk_employees] With nocheck add
Constraint [pk_mk_employees] primary key clustered
(
[Name]
) On [primary];
(P.s: You can also use sqlserver to export data directly)

6 bytes right-click SQL .txt and choose "generate operation"> "embedded resource" from the context menu.
7. Switch dbcustomaction. CS to the Code view and add the following code:
Private string getsql (string name)
{
Try
{
Assembly ASM = assembly. getexecutingassembly ();
Stream STRM = ASM. getmanifestresourcestream (ASM. getname (). Name + "." + name );
Streamreader reader = new streamreader (STRM );
Return reader. readtoend ();
}
Catch (exception ex)
{
Console. Write ("in getsql:" + ex. Message );
Throw ex;
}
}

Private void executesql (string databasename, string SQL)
{
System. Data. sqlclient. sqlcommand command = new system. Data. sqlclient. sqlcommand (SQL, sqlconnection1 );

Command. Connection. open ();
Command. Connection. changedatabase (databasename );
Try
{
Command. executenonquery ();
}
Finally
{
Command. Connection. Close ();
}
}

Protected void adddbtable (string strdbname)
{
Try
{
Executesql ("master", "create database" + strdbname );
Executesql (strdbname, getsql ("SQL .txt "));
}
Catch (exception ex)
{
Console. Write ("in exception handler:" + ex. Message );
}
}

Public override void install (system. Collections. idictionary statesaver)
{
Base. Install (statesaver );
Adddbtable (this. Context. Parameters ["dbname"]);
}

8. Add another project (select "add to solution")-> project type: Installation Project-> name it "dbcustomaction installer"
9. Select the application folder-> Add-> project output-> master output
10. In Solution Explorer, right-click the installation project (dbcustomaction installer) and choose View> User Interface.
11. Select Start Node-> Add dialog box-> text
12. Select a-> right-click the text box and move it up to the top.
13. Select a property in the text box-> modify bannertext (specify database name)
14. Modify bodytext (this dialog allows you to specify the name of the database to be created on the database server .)
15. Modify editlabel1 (name of DB), edit1porperty (customtexta1), and set the visible attribute of edit2, 3, and 4 to false;
16. In Solution Explorer, right-click the installation project (dbcustomaction installer) and choose View> Custom operation.
17. Select the installation node-> Add-> double-click the application folder-> master output from dbcustomaction (activity)-> right-click Attribute-> customactivedata attribute to/dbname = [customtexta1]
18. compile and generate. OK!

Note: This article is mainly from msdn. I used VB.net as the code and changed it with C #. For the complete URL, see
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/vsintro7/html/vxwlk?throughusingcustomactiontocreatedatabaseduringinstallation. asp
In addition, the dialog box does not accept the client database service server-name and password. Since the dbname parameter is acceptable, it is not difficult to receive the server-name and password.
------------------------------------------------------------------------------------------------------------------------------- ------------------------ How to package the SQL database in the installation file? The SQL database is automatically created during installation and the database name can be set. Password, server?
Project package Summary
Function: Install the specified database name and other files according to the user's custom settings, for example (iewebcontrols)
Steps:
Create a new project: Visual C # project, select the class library template, for example, the name is myinstall, add a new item under this project: select the installation program class (installer1.cs), here I use the default name. This installation class library will install databases and other files.
In installer1.cs, We will rewrite the installation class method: see reference 1.
Install commit rollback uninstall
To implement custom installation in the install method:
First, we need to get some user variables (user operations during installation, such as database management accounts)
For these variables, we can use the Context Environment to obtain this. Context. Parameters ["databasename"]; (this will be set in the installation project)
Here we get a total of five variables. The server where the database is installed, the specified database name, Database Administrator account, and password. And database backup files.
Let's take a look at the specific code, which is very simple :)
Private void installdatebase ()
{
System. reflection. Assembly ASM;
// ASM = system. reflection. Assembly. getexecutingassembly ();
// System. Io. fileinfo = new system. Io. fileinfo (ASM. Location );
// You can also get the currently installed directory, such as myweb/your installation project name. dll under the wwwroot directory
// The following are database connections and commands
Sqlconnection sqlconnection1 = new sqlconnection ();
String dbname = This. Context. Parameters ["databasename"];
String dbserver = This. Context. Parameters ["servername"];
String dbuser = This. Context. Parameters ["installadmin"];
String dbkey = This. Context. Parameters ["installpassword"];
String dir = This. Context. Parameters ["dir"];

Streamwriter Ss = new streamwriter (@ "C:/aaa.txt", true );
SS. writeline ("Data Source =" + dbname + "; database = Master; uid =" + dbuser + "; Password =" + dbkey );
SS. Close ();
String constr = "Data Source =" + dbserver + "; database = Master; uid =" + dbuser + "; Password =" + dbkey;
Sqlconnection1.connectionstring = constr;
// The database will be installed under system32
String curdir = directory. getcurrentdirectory () + @ "/testdata/Database ";
If (! Directory. exists (curdir) // creates
{
Directory. createdirectory (curdir );
}
String msql = "Restore database" + dbname +
"From disk = '" + dir + @ "/database/mydatabase. Bak'" +
"With move 'mydate _ dat 'to'" + curdir + @ "/" + dbname + ". MDF '," +
"Move 'mydate _ log' to '" + curdir + @ "/" + dbname + ". ldf '";

Sqlcommand cmd = new sqlcommand (msql, sqlconnection1 );
Cmd. Connection. open ();
Cmd. executenonquery ();
Cmd. Connection. Close ();
If (sqlconnection1.state = connectionstate. open)
{
Sqlconnection1.close ();
}
// Install Treeview
Processstartinfo psi = new processstartinfo ();
PSI. workingdirectory = dir + "// Database ";
PSI. filename = dir + @ "/database/iewebcontrols. MSI ";
PSI. useshellexecute = true; // MSI file, which is not required if EXE is used

Process. Start (PSI );

// Which of the following brothers can help you with this. The following code. During execution, a process is running, which causes the control to fail to run during installation. It must be closed. But the following code is a little better than the above Code. The following process waits until the end to continue other code of the entire install method. The above code, in actual running, the entire installation is complete. The installation of Treeview is just getting started. A little out of sync
// System. Diagnostics. Process myproc = new system. Diagnostics. Process ();
// Myproc. enableraisingevents = true;
//
// String file = dir + @ "/database/iewebcontrols. MSI ";
//
// Myproc. startinfo. useshellexecute = true;
// Myproc. startinfo. filename = file;
// Myproc. Start ();
// Myproc. waitforexit (); // This method can be executed indefinitely until the process is completed.
// If (myproc. hasexited = true)
//{
//// Myproc. Kill ();
//
//}
}
Public override void install (system. Collections. idictionary statesaver)
{
Try
{
Base. Install (statesaver );
This. installdatebase (); // call the above method
}
Catch
{
Throw;
}
}
Public override void uninstall (system. Collections. idictionary statesaver)
{

Base. Uninstall (statesaver );

// Uninstalldatabase ();


}

Public override void commit (system. Collections. idictionary statesaver)
{
Base. Commit (statesaver );
}

Public override void rollback (system. Collections. idictionary statesaver)
{
Base. rollback (statesaver );



}

Reference 1:
MS-help: // Ms. VSCC/ms. msdnvs.2052/vbcon/html/vbtskoverridingdefamethomethodsoninstallationcomponent.htm
MS-help: // Ms. VSCC/ms. msdnvs.2052/vsintro7/html/vxwlk1_throughusingcustomactiontocreatedatabaseduringinstallation.htm

Now let's add a new project under this project.
Install and deploy a project. Select a WEB Project template, for example, websetup2.

Create a deployment project
1. on the "Files" menu, choose "add project"> "new project ".
2. In the "add project" dialog box, select "Install and deploy Project" in the "project type" pane, and select "Web Installation Project" in the "template" pane ". In the "name" box, type websetup2. (I am the default one. I didn't change it. These statements are too lazy to be typed and copied ,:))
3. In the "properties" window, select the productname attribute and type mywebtest.
4. In the file system Editor, select "application folder ". On the "operations" menu, choose "add"> "project output ".
5. In the "add project output group" dialog box, select the primary output for the "myinstall" project.

The preceding operations are the same as general packaging. Add some files in your web project. And some other packaging settings (product name, etc.
Here we only need to add a database backup file (mydatabase. Bak)
First open the file system Window of websetup2, select the web application folder, and add a folder under this folder to store the database, such as database, and then copy the mydatabase. Bak file to this directory.
Now we need to add a installation window for users to enter database accounts. You only need to open the user interface window to perform operations.

Create custom installation dialog box
1. Select the "websetup2" project in Solution Explorer. On the "View" menu, point to "Editor" and select "User Interface ".
2. In the User Interface Editor, select the "Start" node under "installation. On the "operations" menu, select "add dialog box ".
3. In the Add dialog box, select the text box (.
4. Select "Move Up" from the "operations" menu ". Repeat this step until the "text box (a)" dialog box is located on the "Install Folder" node.
5. In the "properties" window, select the bannertext attribute and type custom database installation
6. Select the bodytext attribute and type custom database installation
7. Select the edit1label attribute and enter the server name :.
8. Select the edit1property property and type servername.
9. Select the edit2label attribute and type "Create Database Name :.
10. Select the edit2property property and type databasename.
11. Select the edit3label attribute and enter the database administrator account :.
12. Select the edit3property property and type installadmin.
13. Select the edit4label attribute and enter the administrator password :. Installpassword
14. Select the edit4property property and type servername.

Create a custom operation
1. Select the "websetup2" project in Solution Explorer. On the "View" menu, point to "Editor" and select "Custom operations ".
2. Select the "Install" node in the Custom operation editor. On the "operations" menu, select "add custom operation ".
3. In the "select project items" dialog box, double-click "application folder ".
4. Select "main output from dbcustomaction (activity.
In the "properties" window, select customactiondata and type/installpassword = [installpassword]/installadmin = [installadmin]/servername = [servername]/databasename = [databasename]/DIR = "[targetdir]/"
Note that there are spaces between user data. For example,/AAA = [fdfad]/bfff = [fdafdfd]
5. On the "generate" menu, select "generate websetup2 ".
The above customactiondata will be referenced in the installation class. Note that there must be spaces between each other.
/DIR = ["targetdir"], which is the final installed web directory
The package of this project has ended.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.