1. 程式人生 > >asp.net 開發的WEB專案和資料庫怎樣打包成exe安裝檔案

asp.net 開發的WEB專案和資料庫怎樣打包成exe安裝檔案

步驟:  
  1、新增一個新專案->選擇類庫模板->命名為DBCustomAction  
  2、單擊專案右鍵->新增新項->選擇安裝程式類(命名為DBCustomAction.cs)  
  3、在伺服器資源管理器中新增->連線到資料庫->指定使用者密碼(選擇允許儲存密碼)->資料庫選擇master  
  4、切換到DBCustomAction.cs的檢視狀態->將伺服器資源管理器資料庫連線中的master.dbo拖動到designer中  
  5、新增一個新項sql.txt(注意要使用小寫),輸入下列sql程式碼  
  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:也可以直接用SqlServer匯出)  
   
  6、在sql.txt的右鍵屬性中->生成操作->嵌入的資源  
  7、將DBCustomAction.cs切換到程式碼檢視,新增下列程式碼  
  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、再新增一個新專案,(選擇新增到解決方案中)->專案型別為安裝專案->命名為DBCustomAction Installer  
  9、選擇應用程式資料夾->新增->專案輸出->主輸出  
  10、在方案資源管理器中->右鍵安裝專案(DBCustomAction Installer)->檢視->使用者介面  
  11、選中啟動結點->新增對話方塊->文字A  
  12、選動文字框A->右鍵->上移一直到最頂端  
  13、選擇文字框A屬性->修改BannerText,(Specify Database Name)  
  14、修改BodyText(This dialog allows you to specify the name of the database to be created on the database server. )  
  15、修改EditLabel1(Name of DB),修改Edit1Porperty(CUSTOMTEXTA1),將其他Edit2,3,4的Edit(2,3,4)Visible屬性設為false;  
  16、在方案資源管理器中->右鍵安裝專案(DBCustomAction Installer)->檢視->自定義操作  
  17、選中安裝結點->新增->雙擊應用程式資料夾->主輸出來自DBCustomAction(活動)->右鍵屬性->CustomActiveData屬性修改為/dbname=[CUSTOMTEXTA1]  
  18、編譯生成,OK!  


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxwlkWalkthroughUsingCustomActionToCreateDatabaseDuringInstallation.asp