1. 程式人生 > >如何用VS2005製作Web安裝程式

如何用VS2005製作Web安裝程式

選擇“使用者介面編輯器”,新增兩個文字框ABA將作為安裝新站點後的IIS設定,B將作為資料庫操作時的引數設定,調整位置後如下:

調整A的屬性,這裡只選擇了顯示兩個輸入框,屬性分別為IISSERVERPORT,值為localhost9998,其他的你可以自己調整。如圖:

文字框B的設定如下:

OK,文字框設定完畢。當然,你還可以選擇其他的多種文字框,如協議什麼的。

開啟自定義操作面板:

然後:

CustomActionData中輸入:

/dbname=[DBNAME] /server=[DBSERVERNAME] /user=[USERNAME] /pwd=[PASSWORD] /iis=[IISSERVER] /port=[PORT] /targetdir="[TARGETDIR]/"

這些引數就是文字框AB上的輸入框的值,在安裝過程中可以獲得,然後進行處理。

至此,基本的安裝檔案已經制作完畢。進行生成,然後點選安裝,可以看到檔案已經複製到了相應到目錄。接下來就要接收引數對IIS和資料庫進行處理。

開啟SetupClassLibrary專案下的MyInstaller.Designer.cs,修改此檔案。

申明幾個變數:

        private System.Data.SqlClient.SqlConnection sqlConn;

private System.Data.SqlClient.SqlCommand Command;

private string DBName;

private string ServerName;

private string AdminName;

private string AdminPwd;

private string iis;

private string port;

private string dir;

public static string VirDirSchemaName = "IIsWebVirtualDir";

private string _target;

private DirectoryEntry _iisServer;

private ManagementScope _scope;

private ConnectionOptions _connection;

連線資料庫伺服器到方法:

#region ConnectDatabase 連線資料庫

private bool ConnectDatabase()

{

if (Command.Connection.State != ConnectionState.Open)

{

try

{

Command.Connection.Open();

}

catch(Exception e)

{

return false;

}

}

return true;

}

#endregion

如果不能正確連線資料庫伺服器,請檢查你的連線字串,或者將連線字串寫入檔案檢視。不好意思,我不知道如何對這種安裝部署程式進行debugsorry咯!

讀取SQL檔案的方法:

#region GetSql 從檔案中讀取SQL,在讀取包含SQL指令碼的檔案時需要用到,參考自MSDN

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 getException)

{

throw new ApplicationException(getException.Message);

}

}

#endregion

可以將此需要執行的SQL指令碼放在此文字中

執行SQL語句的方法:

#region ExecuteSql 執行SQL語句,參考自MSDN

private void ExecuteSql(string DataBaseName, string sqlstring)

{

Command = new System.Data.SqlClient.SqlCommand(sqlstring, sqlConn);

if (ConnectDatabase())

{

try

{

Command.Connection.ChangeDatabase(DataBaseName);

Command.ExecuteNonQuery();

}

finally

{

Command.Connection.Close();

}

}

}

#endregion

建立資料庫及資料庫表:

#region CreateDBAndTable 建立資料庫及資料庫表,參考自MSDN

protected bool CreateDBAndTable(string DBName)

{

bool Restult = false;

try

{

ExecuteSql("master", "USE MASTER IF EXISTS (SELECT NAME FROM SYSDATABASES WHERE NAME='" + DBName + "') DROP DATABASE " + DBName);

ExecuteSql("master", "CREATE DATABASE " + DBName);

ExecuteSql(DBName, GetSql("DBSQL.txt"));

Restult = true;

}

Catch

{

}

return Restult;

}

#endregion

從備份檔案恢復資料庫及資料庫表

#region RestoreDB 從備份檔案恢復資料庫及資料庫表

///

/// 從備份檔案恢復資料庫及資料庫表

///

/// 資料庫名

/// 配件中資料庫指令碼資源的名稱

///

protected bool RestoreDB(string DBName)

{

dir = this.Context.Parameters["targetdir"];

bool Restult = false;

string MSQL = "RESTORE DATABASE " + DBName +

" FROM DISK = '" + dir + @"data.bak' " +

" WITH MOVE 'Test' TO '" + @"c:/" + DBName + ".mdf', " +

" MOVE 'Test_log' TO '" + @"c:/" + DBName + ".ldf' ";

try

{

ExecuteSql("master", "USE MASTER IF EXISTS (SELECT NAME FROM SYSDATABASES WHERE NAME='" + DBName + "') DROP DATABASE " + DBName);

ExecuteSql("master", MSQL);

Restult = true;

}

finally

{

// 刪除備份檔案

try

{

File.Delete(dir + @"data.bak");

}

catch

{

}

}

return Restult;

}

#endregion

這裡可以到登錄檔讀取SQL Server的安裝路徑,把恢復後的資料庫檔案放到data目錄地下。在本例中,只是實現了恢復,並未進行標準的操作。其中TestTest_log時備份時資料庫的檔案資訊。如果想要從備份檔案中恢復,請把檔案包含到專案裡並且設定和DBSQL.txt一樣,嵌入到程式裡。最後執行刪除。不過我想應該有辦法不把檔案先安裝到目標機器上,而是有方法想讀取DBSQL.txt檔案一樣,直接恢復資料庫,不過確實沒想到辦法,失敗!

網站安裝好後,需要設定web.config檔案,這裡只涉及到連線字串到設定,其他的可以同理修改。

#region WriteWebConfig 修改web.config的連線資料庫的字串

private bool WriteWebConfig()

{

System.IO.FileInfo FileInfo = new System.IO.FileInfo(this.Context.Parameters["targetdir"] + "/web.config");

if (!FileInfo.Exists)

{

throw new InstallException("Missing config file :" + this.Context.Parameters["targetdir"] + "/web.config");

}

System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();

xmlDocument.Load(FileInfo.FullName);

bool FoundIt = false;

foreach (System.Xml.XmlNode Node in xmlDocument["configuration"]["appSettings"])

{

if (Node.Name == "add")

{

if (Node.Attributes.GetNamedItem("key").Value == "ConnectionString")

{

Node.Attributes.GetNamedItem("value").Value = String.Format("Persist Security Info=False;Data Source={0};database={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1", ServerName, DBName, AdminName, AdminPwd);

FoundIt = true;

}

}

}

if (!FoundIt)

{

throw new InstallException("Error when writing the config file: web.config");

}

xmlDocument.Save(FileInfo.FullName);

return FoundIt;

}

#endregion

#region WriteRegistryKey 寫登錄檔。安裝部署中,直接有一個登錄檔編輯器,可以在那裡面設定。

private void WriteRegistryKey()

{

// 寫登錄檔

RegistryKey hklm = Registry.LocalMachine;

RegistryKey cqfeng = hklm.OpenSubKey("SOFTWARE", true);

RegistryKey F = cqfeng.CreateSubKey("cqfeng");

F.SetValue("FilePath", "kkkk");

}

#endregion

操作IIS,建立網站等。可參考:

#region Connect 連線IIS伺服器

public bool Connect()

{

if (iis == null)

return false;

try

{

_iisServer = new DirectoryEntry("IIS://" + iis + "/W3SVC/1");

_target = iis;

_connection = new ConnectionOptions();

_scope = new ManagementScope(@"//" + iis + @"/root/MicrosoftIISV2", _connection);

_scope.Connect();

}

catch

{

return false;

}

return IsConnected();

}

public bool IsConnected()

{

if (_target == null || _connection == null || _scope == null) return false;

return _scope.IsConnected;

}

#endregion

#region IsWebSiteExists 判斷網站是否已經存在

public bool IsWebSiteExists(string serverID)

{

try

{

string siteName = "W3SVC/" + serverID;

ManagementObjectSearcher searcher = new ManagementObjectSearcher(_scope, new ObjectQuery("SELECT * FROM IIsWebServer"), null);

ManagementObjectCollection webSites = searcher.Get();

foreach (ManagementObject webSite in webSites)

{

if ((string)webSite.Properties["Name"].Value == siteName)

return true;

}

return false;

}

catch

{

return false;

}

}

#endregion

#region GetNextOpenID 獲得一個新的ServerID

private int GetNextOpenID()

{

DirectoryEntry iisComputer = new DirectoryEntry("IIS://localhost/w3svc");

int nextID = 0;

foreach (DirectoryEntry iisWebServer in iisComputer.Children)

{

string sname = iisWebServer.Name;

try

{

int name = int.Parse(sname);

if (name > nextID)

{

nextID = name;

}

}

catch

{

}

}

return ++nextID;

}

#endregion

#region CreateWebsite 新增網站

public string CreateWebSite(string serverID, string serverComment, string defaultVrootPath, string HostName, string IP, string Port)

{

try

{

ManagementObject oW3SVC = new ManagementObject(_scope, new ManagementPath(@"IIsWebService='W3SVC'"), null);

if (IsWebSiteExists(serverID))

{

return "Site Already Exists...";

}

ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters("CreateNewSite");

ManagementBaseObject[] serverBinding = new ManagementBaseObject[1];

serverBinding[0] = CreateServerBinding(HostName, IP, Port);

inputParameters["ServerComment"] = serverComment;

inputParameters["ServerBindings"] = serverBinding;

inputParameters["PathOfRootVirtualDir"] = defaultVrootPath;

inputParameters["ServerId"] = serverID;

ManagementBaseObject outParameter = null;

outParameter = oW3SVC.InvokeMethod("CreateNewSite", inputParameters, null);

// 啟動網站

string serverName = "W3SVC/" + serverID;

ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);

webSite.InvokeMethod("Start", null);

return (string)outParameter.Properties["ReturnValue"].Value;

}

catch (Exception ex)

{

return ex.Message;

}

}

public ManagementObject CreateServerBinding(string HostName, string IP, string Port)

{

try

{

ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath("ServerBinding"), null);

ManagementObject serverBinding = classBinding.CreateInstance();

serverBinding.Properties["Hostname"].Value = HostName;

serverBinding.Properties["IP"].Value = IP;

serverBinding.Properties["Port"].Value = Port;

serverBinding.Put();

return serverBinding;

}

catch

{

return null;

}

}

#endregion

好了,準備工作已經做完,現在開始寫最重要的Install方法了

整個方法寫完後如下:

#region Install 安裝

///

/// 安裝資料庫

///

///

public override void Install(IDictionary stateSaver)

{

base.Install(stateSaver);

dir = this.Context.Parameters["dir"];

DBName = this.Context.Parameters["DBNAME"].ToString();

ServerName = this.Context.Parameters["server"].ToString();

AdminName = this.Context.Parameters["user"].ToString();

AdminPwd = this.Context.Parameters["pwd"].ToString();

iis = this.Context.Parameters["iis"].ToString(); ;

port = this.Context.Parameters["port"].ToString();

//寫入獲取的安裝程式中的變數,此段程式碼為除錯用可以不新增

this.sqlConn.ConnectionString = "Packet size=4096;User ID=" + AdminName + ";Data Source=" + ServerName + ";Password=" + AdminPwd + ";Persist Security Info=False;Integrated Security=false";

// 執行SQL 安裝資料庫 可選擇時恢復或者時直接建立

if(!CreateDBAndTable(DBName))

{

throw new ApplicationException("建立資料庫時出現嚴重錯誤!");

}

// 從備份資料庫檔案恢復資料庫

/*

if (!RestoreDB(DBName))

{

throw new ApplicationException("恢復資料庫時出現嚴重錯誤!");

}

*/

// 新增網站

Connect();

//string serverID = GetNextOpenID().ToString();

//string serverComment = websitenName;

// 下面的資訊為測試,可以自己編寫文字框來接收使用者輸入資訊

string serverID = "5555";

string serverComment = "cqfeng";

string defaultVrootPath = this.Context.Parameters["targetdir"];

if (defaultVrootPath.EndsWith(@"/"))

{

defaultVrootPath = defaultVrootPath.Substring(0, defaultVrootPath.Length-1);

}

string HostName = "";

string IP = "";

string Port = port;

string sReturn = CreateWebSite(serverID, serverComment, defaultVrootPath, HostName, IP, Port);

// 修改web.config

if (!WriteWebConfig())

{

throw new ApplicationException("設定資料庫連線字串時出現錯誤");

}

// 寫登錄檔

WriteRegistryKey();

}

#endregion

刪除時的方法。在本文中未詳細操作,比如刪除站點,刪除資料庫等。如果需要,請你自己補足

#region Uninstall 刪除

public override void Uninstall(IDictionary savedState)

{

if (savedState == null)

{

throw new ApplicationException("未能解除安裝!");

}

else

{

base.Uninstall(savedState);

}

}

#endregion

編譯,然後選擇安裝,如圖:

第一圖:

第二圖:

第三圖:

抱歉,我不知道在這裡怎麼使登入密碼框輸入時顯示為*

第四圖:

第五圖:

安裝:

相關推薦

如何用VS2005製作Web安裝程式

選擇“使用者介面編輯器”,新增兩個文字框A和B,A將作為安裝新站點後的IIS設定,B將作為資料庫操作時的引數設定,調整位置後如下: 調整A的屬性,這裡只選擇了顯示兩個輸入框,屬性分別為IISSERVER和PORT,值為localhost和9998,其他的你可以自己調整。如圖:

.Net Framework 4.0 製作安裝程式安裝 .Net Framework 4.0 編寫的程式

文章題目看起來有點繞,解釋一下,假如你基於框架寫了一個程式,想裝到客戶機上,但是客戶機上可能並沒有安裝框架,因此你的程式需要預先將框架安裝在目標機上,然後再執行一些安裝程式的標準功能,如建立快捷方式、建立程式組、寫入解除安裝資訊以便讓Windows能夠對程式進行解除安裝管理

advanced installer 製作exe安裝程式

其他的和製作msi工程一樣.而後在媒介項中的載入程式欄中選中"建立exe安裝程式",並選中"程式包"->exe檔案中包含安裝檔案->msi包含在載入程式中.並把安裝選項的提取位置全部刪除.(555,以前就是這裡沒刪除,導致安裝檔案失敗)並在媒介欄->檔案中選擇使用lzma

利用AutoIt製作自動安裝程式

初次使用AutoIT感覺很方便,參照網路上的資料做了一個例子,總結如下: 1.利用window Spy 獲得窗體和控制元件資訊 CLTR+ALT+F:可以暫停獲取操作,方便檢視獲取的資訊 2.利用WinWaitActive 等待指定窗體的出現 WinWaitActive("窗體標題","窗體出現的文字")  

[原創*精華]一鍵釋出ASP.NET Web安裝程式,搞WebForm的童鞋看過來...

    重要更新:鑑於很多小夥伴們說看不到圖,我這邊換了幾個瀏覽器看了下,都看得到的,估計是網速問題,請耐心等待,另外,為了更好的方便大家學習,特此提供原始碼以及一個word文件,word文件就是本文內容,包括圖片,下載連結在最底下,謝謝.   前言:最近公司有個W

visual studio 2017 installer 安裝製作過程出現的問題---此安裝程式需要.NET Framework 版本 3.5,請安裝該版本,然後重新執行此安裝程式,可以從Web獲得

visual studio 2017 installer 安裝包製作過程出現的問題---此安裝程式需要.NET Framework 版本 3.5,請安裝該版本,然後重新執行此安裝程式,可以從Web獲得.NET Framework 。要立即做此事嗎?     &nbs

Inno Setup編譯器製作web系統安裝

一、工具準備 Inno Setup編譯器:一個免費的安裝製作軟體。 二、執行環境準備 1、新建打包用的資料夾,如在d盤新建webexe資料夾(D:/webexe)。 2、Jdk,把安裝好的jdk直接拷貝到webexe資料夾下 (或者綠色版)。 3、應用程式及tomcat

NSIS建立自己的windows安裝程式製作程式

NSIS簡介:    NSIS 是“Nullsoft 指令碼安裝系統”(Nullsoft Scriptable Installation System)的縮寫,它是一個免費的 Win32 安裝、解除安裝系統,它的特點:指令碼簡潔高效;系統開銷小;當然進行安裝、解除安裝、

Setup Factory 7.0製作安裝程式 基礎篇

我們在用VB等語言編寫並編譯成程式後,往往會希望製作一個精美的安裝程式來發布自己的軟體。在這裡推薦使用Setup Factory 7.0,這是一款強大的安裝程式製作工具。該軟體提供了安裝製作嚮導介面,即使你對安裝製作不瞭解,也可以生成專業性質的安裝程式。可建立快捷方式,也可直接在系統的登錄檔加入內容,還能在

Ubuntu下安裝程式的三種方法 ubuntu製作本地源

在ubuntu當中,安裝應用程式我所知道的有三種方法,分別是apt-get,dpkg安裝deb和make install安裝原始碼包三種。下面針對每一種方法各舉例來說明。 apt-get方法 使用apt-get install來安裝應用程式算是最常見的一種安裝方法了,比如我要安裝build-essenti

VS2005 建立Windows服務程式,打包成安裝檔案

一、建立服務程式1. 選單欄“檔案”--->“新建”--->“專案”,在專案型別中選擇“windows”,模板中--->“windows 服務”。專案名稱任意起。   新專案中會建立 Program.cs , Service1.cs及其他的檔案或資料夾 2.

P2P網路被谷歌來共享離線安裝應用程式

考慮到部分發展中國家網路覆蓋差和流量資費昂貴問題,谷歌正在通過P2P 共享技術幫助使用者離線安裝應用。 通過區域網的P2P 共享使用者可以快速獲得應用程式的安裝包,這樣可以降低使用者下載時間和耗費的流量費用。 當然基於安全考慮只有具有有效數字簽名的應用才可以P2P 共享,並且谷歌也會通過聯網

WebStorm + BootStrap 安裝 Tomcat 部署Web專案(圖文詳解 + 例項 )

                                 WebStorm安裝和破解 1.官網下載 2.安裝

Eclipse 安裝+ Tomcat 部署Web專案(圖文詳解 + 例項 )

                                          Ecl

UltraISO製作CentOS U盤安裝

準備 下載UltraISO 連結:https://pan.baidu.com/s/1DkauTgDAs7FqlUj4s7SawA 提取碼:5ibc 下載centos ios 製作過程 在Ultra ISO上方選單欄依次選擇檔案 -> 開啟 -&g

EclipseTomcat執行web程式出現HTTP Status 404的一種情況

情況分析: 1、Eclipse中Tomcat正常執行。 2、頁面URL地址,埠都是沒問題的。 3、Tomcat獨立執行專案,正常顯示。 問題解決: 雙擊Tomcat例項,在配置頁面中的Server Locations,修改為Use Tomcat installation,並選擇正確的To

windows下VS code除錯C程式之MinGW安裝(參考自官網)

準備工作 1.1 VScode 不累贅了, 官網自行下載. 1.2 C的編譯環境 一般使用MinGW, 先說一種騷操作通過安裝Codeblocks的mingw版會自動安裝需要的MinGW

docker 安裝 建立支援ssh服務的映象 建立nginx服務的映象 dockerfile製作nginx映象

環境centos7.2  docker安裝核心版本必須在3.10及其以上uname -r  檢視核心版本首先去docker官網downloaddocker-ce-17.03.2.ce-1.el7.centos.x86_64.rpm docker-ce-selinux-17.0

Lucene加速Web站點搜尋應用程式的開發

在本篇文章中,你會學習到如何利用 Lucene 實現高階搜尋功能以及如何利用 Lucene 來建立 Web 搜尋應用程式。通過這些學習,你就可以利用 Lucene 來建立自己的搜尋應用程式。 架構概覽 通常一個 Web 搜尋引擎的架構分為前端和後端兩部分,就像圖一中所示。

MFC製作一個倒計時小程式

void CCdTimerDlg::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default UpdateData(TRUE); BOOL bIsDecreased = FALSE;