A web project installation package, automatically configure databases, config files, and virtual directories. . (Original)

xiaoxiao2021-03-06  38

Recently a web project is to pack, find some information, found that the installation of the .NET comes with the Web installer is not very easy to use. It has been packaged. You can automatically configure the database and virtual directory and the config file. You are welcome to mention valuable advice. . using System; using System.Collections; using System.ComponentModel; using System.DirectoryServices; using System.Configuration.Install; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; using System.Text; using System.io; using system.xml;

namespace WebSetupConfig {///

/// Author: LXH Published: 2004-10-29 /// This class is used in .NET WEB application deployment platform, including /// publication database, web.config file Configure the creation of // virtual directory. And the reverse installation process of these installation steps. /// below is the context parameter of the installation process. /// / dbname = [dbname] / computername = [computername] / username = [username] / password = [password] / targetdir = "[targetdir] /" /// [RunInstaller (TRUE)] public Class setupconfig: system.configuration.install.installer {#region variable static stringbuilder sqltxt; private system.componentmodel.container components = NULL;

#ndregion public setupconfig () {initializationComponent ();

Protected Override Void Dispose (bool disposing) {if (disponents! = null) {components.dispose ();}} Base.Dispose (Disposing);

#REGION component designer generated code ///

/// designer supports the required method - Do not use the code editor to modify the // / this method. /// private () {components = new system.componentmodel.container (); // Add the old database name of the database backup file. This.context.Parameters.add ("olddbname", "ztwjmis1");} #ENDREGON / / Get database connection string private string getConnection () {string connectionString = string.format ("data source = {0}; user ID = {1}; password = {2}; PERSIST security info = false; packet size = 4096, context.parameters ["computername"], contert.Parameters ["username"], contert.Parameters ["password"]) ; return connectionstring;} // Sql code execution method private void SqlExec (string DataBaseName, string Sql) {SqlConnection conn = new SqlConnection ( "data source = localhost; database = master; persist security info = False; user id = sa; pwd = 123; packet size = 4096 "); sqlcommand com = new sqlcommand (sql, conn); com.connection.Open (); com.connection.changedatabase (DatabaseName); try {com.executenonquery ();} catch (Exception e) {throw e;} finally {com.connection.close ();

}

///

/// database deployment /// /// installation package backup database file path /// deployed to the local database name private void DataBaseDeploy (string DBFilePath, string DBDeployName) {try {string connection = GetConnection (); string sqlText = String.Format ( "restore filelistonly from disk = '{0}' restore Database {1} from disk = '{2}' with move {3} to '{4}', Move '{5}' to '{6}' ", this.context.Parameters [" Targetdir "] " Data.bin ", // 0 this.context.Parameters [" DBNAME "], // 1 this.context.Parameters [" targetdir "] " data.bin ", // 2 this.context.Parameters [" Olddbname "] " _ data ", // 3 this.context.Parameters [" dbname "] ". mdf ", // 4 this.context.Parameters [" olddbname "] " _ log ", // 5 this.context .Parameters ["DBNAME"] ". LDF"); // 6 SQLEXEC ("Master", Sqltext);} catch (exception ex) {messagebox.show ("Database installation exception, check the database configuration, and install ! " EX.MESSAGE);}}

///

/// WebConfig Settings Connection Strings /// /// Write the connection string in WebConfig Private void WebConfigDeploy (String CONNECTIONSTRING) {BOOL CHANGED = false; try {fileinfo xmlfile = new fileinfo (this.context.Parameters ["targetdir"] "// Web.config"); if (! Xmlfile.exists) {throw new installexception ("No Find the configuration file, please check the reinstall! ");} Xmldocument Xmldoc = new xmldocument (); xmldoc.Load (Xmlfile.FullName); foreach (system.xml.xmlnode XMLNode In Xmldoc [" configuration "] [" appsettings " ]) {IF (XMLNode.Name == "Add") {if (XMLNode.Attributes.getnamedItem ("key"). Value == "connection") {// write connection string XMLNode.attributes.getnamedItem (" Value "). Value = connection;}}}}}}}}}}} (!" "Web.config file does not contain the setting of the Connection connection string"); Else Xmldoc.save (Xmlfile.Fullname); } Catch (exception ex) {messagebox.show ("No WebConfig text Part, please reinstall " ex. measureage);}}

///

/// Set virtual directory /// /// virtual directory name /// virtual directory material path private void VirtualDirDeploy (string vdirName, string vdirPath) {IISManager iismanager = new IISManager (); iismanager.Connect (); VirtualDirectory newvdir = new VirtualDirectory (vdirName, vdirPath); VirtualDirectories vdics = iismanager.VirDirs; / / Virtual directory, // detect whether the created virtual directory is with the existing directory rename Foreach (VirtualDirectory vdir in vdics.values) {// has a rendering directory, give a prompt IF (vdir.name == VirtualName) {// Select override the virtual directory, // Delete an existing virtual directory, create a new virtual directory IF according to the new file path (MSSAGEBOX.SHOW (this, "you specified the virtual directory name already existing, you are to overwrite the existing virtual directory ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.OK) {iismanager.Delete (vdir.Path);! iismanager.Create (newvdir); break ;}} // There is no name, create a new virtual directory else {iiSManager.create (newvdir);}}}

/ / Install Configure Public Override Void Install (iDictionary Stateaver); // Database DatabaseDeploy (@ "d: /test.bak", "testdb"); // config file Configure connection string WebConfigDeploy ( @ "Data Source = localhost; database = ztwjmis1; user id = sa; pwd = 123"); // Virtual directory VirtualDirDirDeploy ("Virtualtest", @ "d: / vdir");}}

#REGION IIS Management Class ///

/// iismanager management class. /// public class IISManager {private string _server // need to use defined, _website, _AnonymousUserPass, _AnonymousUserName; private VirtualDirectories _virdirs; protected System.DirectoryServices.DirectoryEntry rootfolder; private bool _batchflag; public IISManager () {// By default, use localhost, that is, accessed the local machine_server = "localhost"; _Website = "1"; _batchflag = false;} public iismanager (String strserver) {_server = strserver; _Website = "1"; _BATCHFLAG = false;} / // /// Define public property ///

public void get_AnonymousUser () {_AnonymousUserPass = "IUSR_DEVE-SERVER"; _AnonymousUserName = "IUSR_DEVE-SERVER"; VirtualDirectory vDir; try {Hashtable myList = (Hashtable) _virdirs; IDictionaryEnumerator myEnumerator = myList.GetEnumerator (); while (myEnumerator.MoveNext ( )) {vDir = (VirtualDirectory) myEnumerator.Value; if (vDir.AnonymousUserName = "" && vDir.AnonymousUserPass =! "") {_AnonymousUserName = vDir.AnonymousUserName;! _AnonymousUserPass = vDir.AnonymousUserPass; break;}}} catch { _AnonymousUserPass = "IUSR_DEVE-SERVER"; _AnonymousUserName = "IUSR_DEVE-SERVER";}} public string AnonymousUserName {get {return _AnonymousUserName;} set {_AnonymousUserName = value;}} public string AnonymousUserPass {get {return _AnonymousUserPass;} set {_AnonymousUserPass = Value;}} // Server property defines the name of the access machine, which can be IP and calculation name public string server {get {returver;} set {_server = value;}} // Website property definition, for a number, For convenience, using string // Generally, the first host is 1, the second host is 2, and push the public string Website {get {return _Website;} set {_Website = value;}} // The name of the virtual directory Public VirtualDirectories virdirs {get {return_virdirs;} set {_virdirs = value;}} ///

/// definition public method ///

// Connect the server public void connection () {ConnectTOSERVER ();} // For easy to overload public void connect (String strserver) {_server = strser ();} // for easy heavy duty PUBLIC VOID Connect (String STRSERVER , string strWebSite) {_server = strServer; _website = strWebSite; ConnectToServer ();} // determines whether the virtual storage directory public bool Exists (string strVirdir) {return _virdirs.Contains (strVirdir);} // add a virtual directory public Bool create (VirtualDirectory newdir) {string strpath = "IIS: //" _server "/ w3svc /" _Website "/ root /" newdir.name; if (! _ virdirs.contains (newdir.name) || _batchflag) {try {// added to the ROOT Children set to DirectoryEntry newVirDir = rootfolder.Children.Add (newdir.Name, "IIsWebVirtualDir"); newVirDir.Invoke ( "AppCreate", true); newVirDir.CommitChanges (); Rootfolder.commitchanges (); // then update the data UpdatedirInfo (newvirdir, newdir); return true;} catch (exception ee) {// throw new exception (EE.TOSTRING ()); Return False;}} else {return true; // throw new Exception ( "This virtual directory is already exist.");}} // get a virtual directory public VirtualDirectory GetVirDir (string strVirdir) {VirtualDirectory tmp = null; if (_virdirs.Contains (strVirdir )) {TMP = _virdirs.Find (strvirdir); ((VirtualDirectory) _virdirs [strvirdir]). Flag = 2;} else {// throw new Exception ("this Virtual Directory Is Not Exists);} Return TMP;}

/ / Update a virtual directory public void update (VirtualDirectory Dir) {// Judging whether the virtual directory that needs to be changed does IF (_VIRDIRDIRS.CONTAINS (Dir.Name)) {DirectoryEntry Ode = rootfolder.children.find (Dir.name, " IIsWebVirtualDir "); UpdateDirInfo (ode, dir);} else {// throw new Exception (" This virtual directory is not exists ");.}} // delete a virtual directory public void delete (string strVirdir) {if (_virdirs .Contains (STRVIRDIR)) {Object [] Paras = new object [2]; Paras [0] = "IisWebVirtualDir"; // Indicates the virtual directory Paras [1] = Strvird; Rootfolder.Invoke ("delete", PARAS); rootfolder.commitchanges ();} else {// throw new exception ("Can''t delete" strvirdir ", Because it isn''t exists.");}} // Batch update public void Updatebatch () {BatchUpdate;} // Reserved one :-) public void updatebatch (VirtualDirectories vds) {BatchUpdate (VDS);} ///

/// Private method /// public Void close () {_virdirs.clear (); _VIRDIRS = NULL; rootfolder.dispose ();

} // Connection Server Private Void ConnectTOSERVER () {string strpath = "IIS: //" _server "/ w3svc /" _Website "/ root"; try {this.rootfolder = new DirectoryEntry (strpath); _Virdirs = GetVirdirs (this.rootfolder.children;} catch (exception e) {// throw new exception ("Can''t connect to the server [" _server "] ...", e);}} // perform bulk updating private void BatchUpdate (VirtualDirectories vds) {_batchflag = true; foreach (object item in vds.Values) {VirtualDirectory vd = (VirtualDirectory) item; switch (vd.flag) {case 0: break; case 1: Create ( VD); Break; Case 2: Update (VD); Break;}} _batchflag = false;} // Update Stuff PRIVATE VOID UpdatedirInfo (DirectoryEntry DE, VirtualDirectory VD) {de.properties ["AnonymoususerName"] [0] = vd.anonymoususeusername; de.properties ["anonymoususerpass"] [0] = vd.anonymoususeuserpass; de.properties ["accessread"] [0] = vd.accessread; de.properties ["AccessExecute"] [0] = VD. AccessExecute; DE .Properties ["accesswrite"] [0] = vd.accessWrite; de.properties ["authbasic"] [0] = vd.authbasic; de.properties ["authnTlm"] [0] = vd.authntlm; de.properties [ "ContentIndexed"] [0] = vd.ContentIndexed; de.Properties [ "EnableDefaultDoc"] [0] = vd.EnableDefaultDoc; de.Properties [ "EnableDirBrowsing"] [0] = vd.EnableDirBrowsing; de.Properties [ " Accessssl "] [0] = vd.accessssssl; de.properties [" accessscript "] [0] = vd.accessscript; de.properties [" defaultdoc "] [0] = vd.defaultdoc; de.properties ["

Path "] [0] = vd.Path; de.CommitChanges ();} // set the virtual directory acquired private VirtualDirectories GetVirDirs (DirectoryEntries des) {VirtualDirectories tmpdirs = new VirtualDirectories (); foreach (DirectoryEntry de in des) {if ( de.SchemaClassName == "IIsWebVirtualDir") {VirtualDirectory vd = new VirtualDirectory (); vd.Name = de.Name; vd.AccessRead = (bool) de.Properties [ "AccessRead"] [0]; vd.AccessExecute = ( Bool) de.properties ["AccessExecute"] [0]; vd.accessWrite = (bool) de.properties ["accesswrite] [0]; vd.anonymoususeusername = (string) de.properties [" anonymoususername "] [0 ]; Vd.anonymoususeuserpass = (string) de.properties ["anonymoususername"] [0]; vd.authbasic = (bool) de.properties ["authbasic"] [0]; vd.authnTlm = (bool) de.properties ["AuthnTLM"] [0]; vd.contentIndexed = (bool) de.properties ["contentindexed"] [0]; vd.enabledeDefaultdoc = (bool) de.properties ["enabledefaultdoc"] [0]; vd.enableDirbrowsingsing = (BOOL) de.properties ["enabledirbrowsing"] [0]; vd.ac Cessssl = (bool) de.properties ["accessssl"] [0]; vd.accessscript = (bool) de.properties ["accessscript"] [0]; vd.path = (string) de.properties ["path" ] [0]; vd.flag = 0; vd.defaultdoc = (string) de.properties ["defaultdoc"] [0]; tmpdirs.add (vd.name, VD);}} returnitirs;}

}

#endregion #region virtual catalog class ///

/// VirtualDirectory type /// public class VirtualDirectory {private bool _read, _execute, _script, _ssl, _write, _authbasic, _authntlm, _indexed, _endirbrow, _endefaultdoc ; private string _ausername, _auserpass, _name, _path; private int _flag; private string _defaultdoc; /// /// constructor /// public VirtualDirectory () {SetValue ();} public VirtualDirectory ( string sVirDirName) {SetValue (); _name = sVirDirName;} // sVirDirName: virtual path; // strPhyPath: physical path (physics path) public VirtualDirectory (string sVirDirName, string strPhyPath, string [] AnonymousUser) {SetValue (); _name = sVirDirName; _path = strPhyPath; _ausername = AnonymousUser [0]; _auserpass = AnonymousUser [1];} private void SetValue () {_read = true; _execute = false; _script = true; _ssl = false; _write = false; _authbasic = False; _AUTHNTLM = true; _ndexed = true; _ndefaultdoc = true; _flag = 1; _defaultdoc = "default.htm, default.htm, Def AULT.ASPX, Default.asp, Index.htm "; _path =" c: // "; _AUSERNAME =" IUSR_DEVE-Server "; _ auserpass =" IUSR_DEVE-Server "; _ name =" ";} /// /// Define attributes, iisvirtualdir too many attributes /// I only have more important, other big guys need to add it. ///

public int flag {get {return _flag;} set {_flag = value;}} public bool AccessRead {get {return _read;} ​​set {_read = value;}} public bool AccessWrite {get {return _write;} set {_write = value;}} public bool AccessExecute {get {return _execute;} set {_execute = value;}} public bool AccessSSL {get {return _ssl;} set {_ssl = value;}} public bool AccessScript {get {return _script;} set {_script = value;}} public bool AuthBasic {get {return _authbasic;} set {_authbasic = value;}} public bool AuthNTLM {get {return _authntlm;} set {_authntlm = value;}} public bool ContentIndexed {get { return _indexed;} set {_indexed = value;}} public bool EnableDirBrowsing {get {return _endirbrow;} set {_endirbrow = value;}} public bool EnableDefaultDoc {get {return _endefaultdoc;} set {_endefaultdoc = value;}} public string Name {get {return _name;} set {_name = value;}} public string path {get {RET urn _path;} set {_path = value;}} public string DefaultDoc {get {return _defaultdoc;} set {_defaultdoc = value;}} public string AnonymousUserName {get {return _ausername;} set {_ausername = value;}} public string AnonymousUserPass {get {return _auserpass;} set {_auserpass = value;}}} #endregion #region virtual directory collections ///

/// set VirtualDirectories /// public class VirtualDirectories: System.Collections .Hashtable {public virtualdirectories () {} // Add new method PUBLIC VirtualDirectory Find (String Strname) {Return (VirtualDirectory) this [strname];}} #ENDREGON}

转载请注明原文地址:https://www.9cbs.com/read-68282.html

New Post(0)