Key points to introduce how to automatically create databases for customers in the installation package
Steps: 1, add a new item-> Select Class Bank Template -> Named DBCustomAction 2, click Project Right-click -> Add New Item -> Select Installer class (named dbcustomaction.cs) 3, in Server Explorer Add-> Connect to Database -> Specify User Password (Select Allow Save Password) -> Database Select Master 4 to switch to DBCustomAction.cs -> Drag Master.dbo in Server Explorer Database Connections to DESIGNER 5, add a new item SQL.txt (Note To use lowercase), 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_GENER_CP1_CI_AS NULL) ON [PRIMARY];
Alter Table [DBO]. [Mk_employees] with nocheck address [pk_mk_employees] Primary Key Clustered ([Name]) on [primary]; (P.s: You can also export directly with SQLServer)
6, in SQL.txt's right-click Properties -> Generate Operation -> Embedded Resources 7, switch dbcustomaction.cs to code view, add the following code string getsql (string name) {try {ask {ask {ask {ask {ask gSEMBLY ASM = askEMBLY.GETEXECUTINAMBLY ); Stream strm = Asm.GetManifestResourceStream (Asm.GetName () Name Name). "."; StreamReader reader = new StreamReader (strm); return reader.ReadToEnd ();} catch (Exception ex) {Console.Write ("In getsql:" ex. amount); 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 a new project, (Select Add to Solution) -> Project Type to Installing Items -> Named DBCustomAction Installer 9, select Application Folder -> Add -> Project Output -> Main Output 10, Solution Explorer -> Right click on the item (DBCustomAction Installer) -> View -> User Interface 11, Select the Start Node -> Add Dialog -> Text A 12, Select Text Box A-> Right Key -> Top 13, select text box A properties -> Modify Bannertext, (Specify Database Name) 14, modify BodyText (this Dialog Allows You to Specify On The Database Server.) 15, modify Editlabel1 (Name of DB), modify edit1porperty (CustomTexta1), set other Edit 2, 3, 4 EDIT (2, 3, 4) Visible attribute to false; 16, in the program resource manager -> Right click Install item (DBCustomaction Installer ) -> View -> Custom operation 17, select the installation node -> Add -> Double-click Application Folder -> Main Output from DBCustomAction (Event) -> Right click Properties -> CustomactiveData property modified to / dbname = [CustomTexta1] 18, compile generation, OK!
Note: This article mainly comes from MSDN, this code uses VB.NET, I have rewritten with C #, please refer to http://msdn.microsoft.com/library/default.asp?url=/library/en- US / vsintro7 / html / vxwlkwalkthroughusingCustomActionTocreated.asp does not accept customer database services Server-name and password dialog, I want to accept DBNAME parameters, then receive server-name and password should be difficult. ------------ -------------------------------------------------- -------------------------------------------------- -------------------------------------------- Install the installation file how to pack SQL database? The SQL database is automatically built when installing, and the database name can be set. Password, Server? Project package summary implementation function: Default according to the user-defined database name and other files such as (IEWebControls) Steps: New Project: Visual C # item, select the class library template, such as named MyInstall, here Add a new item below: Select the installer class (Installer1.cs), here I adopt the default name. This installation class library will implement the installation of the database and the installation of other files. In Installer1.cs We will rewrite the installation class: See 1Install Commit Rollback Uninstall to implement custom installation in the Install method: First we have to get some user variables (the user does operation during installation, such as database Administrative account, etc.) We can get this.context.parameters ["DatabaseName"] for these variables. Install the server, the specified database name, database administrator account, password. And database backup files.
We look at the specific code is very simple:) private void InstallDateBase () {System.Reflection.Assembly Asm; // Asm = System.Reflection.Assembly.GetExecutingAssembly (); // System.IO.FileInfo FileInfo = new System .Io.fileinfo (ASM.LOCATION); // You can also get the currently installed directory, such as the wwwroot directory. MyWeb / Your installation engineering name .DLL // below is the database line and command 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 to SYSTEM32 String Curdir = Directory.getCurrentDirectory () @ "/ Testdata / database"; if (! Directory.exists (curdir)) // does not exist, create a new {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 ();} // mounting TreeView ProcessStartInfo psi = new ProcessStartInfo (); psi.WorkingDirectory = dir "// database"; psi.FileName = dir @ "/ database /iewebcontrols.msi "; psi.useshellexecute = true; // msi file, if EXE does not have to set up process.start (psi); // What brother helps look at it. The following code. It will be said to be run when executed, causing you to run when you install these controls. Be sure. It can be. However, the following code has a little better than the above code, the following process waits until the end of the end of the entire install method. And the above code is in actual operation, the entire installation is over. The work installed with TreeView has just begun. A bit disabled // system.diagnostics.process myproc = new system.diagnostics.process (); // myproc.enableraisingevents = true; /// String file = trans @ "/ database / ieWebControls.msi"; // / / / Myproc.startinfo.useshellexecute = true; // myproc.startinfo.FileName = file; // myproc.start (); // myproc.waitforeXIT (); // This method can be completed in the process of running until the process is completed, Code // if (MyProc.hasexited == True) // {// //}} 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/vbtskoverridingdefaultmethodsoninstallationcomponent.htmms-help: //MS.VSCC/MS.MSDNVS.2052/vsintro7/html/vxwlkWalkthroughUsingCustomActionToCreateDatabaseDuringInstallation.htm
Now let's add a new project installation and deployment item below this project, select the web project template, such as named WebSetup2.
Create a deployment item 1. On the File menu, select Add Project -> New Project. 2. In the Add Project dialog box, select Install and Deploy Projects in the Project Type pane, then select "Web Installation item" in the Template pane. In the Name box, type WebSetup2. (I am default, didn't change. These statements are too lazy to play, copy, :)) 3. In the Properties window, select the ProductName property and type myWebtest. 4. In the File System Editor, select Application Folder. On the "Operation" menu, select Add "-> Project Output. 5. In the Add Issue Output Group dialog, select the main output for the "MyInstall" project.
In the previous operation, add some files in your web project to the usual packaging. And some other package settings (product names, etc.), I will not say much. We just join a database backup file (MyDatabase.bak) first open the WebSetup2 file system window, select the web application folder, add a folder below this folder to store the database, such as Database, then MYDATABASE The .bak file is copied below this directory. Now we have to add a window to install, used to enable the user to enter the database account. We can do it as long as we open the user interface window.
Create a custom installation dialog 1. Select the "WebSetup2" item in the Solution Explorer. Point "Editor" on the View menu and select User Interface. 2. In the User Interface Editor, select the "Start" node under "Install". On the Actions menu, select Add Dialog. 3. Select the text box (a) dialog in the Add Dialog dialog box. 4. Select "Move" on the "Operation" menu. Repeat this step until the text box (a) dialog is on the "Install Folder" node. 5. In the Properties window, select the Bannertext property and type a custom database installation 6. Select the BodyText property and type the custom database installation 7. Select the Edit1Label property and type the server name:. 8. Select the Edit1Property property and type ServerName. 9. Select the Edit2Label property and type the Create Database Name:. 10. Select the Edit2Property property and type DatabaseName. 11. Select the Edit3Label property and type the database administrator account:. 12. Select the Edit3Property property and type InstallAdmin. 13. Select the Edit4Label property and type the administrator password:. InstallPassword14. Select the Edit4Property property and type ServerName.