重點介紹如何在安裝包中自動爲客戶創建數據庫
步驟:
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!