Asp.net打包部署全攻略(SQL Server2005数据库)
Asp.net打包部署全攻略(SQL Server2005数据库)
第一次用VS.NET2005打包,和VS.NET2003还是有些区别的。翻箱子倒柜,总算是搞定了。其实很简单,我尽量写的详细点,以后就可以贴过去改改直接用。
一、前期准备
发布网站。准备好要打包的已经发布了的网站。至于怎么发布网站我就不说了,2005中发布网站很方便。
准备好SQL脚步。包括table,view,stroe procedure等。我这里只需要创建一个表和三个存储过程。(注:创建存储过程和表的脚步写到一起会出错,具体原因偶也搞不懂 所以我分开写的)
添加一个项目DBInstall,在项目中添加一个新项,选择Installer class 取名DBInstaller.cs 具体实现如下:
(注:这一步是必须的)
一切搞定之后,将DBInstall编译一次。
三、Web Setup Project
添加安装项目:在解决方案中添加一个Web Setup Project。我这里取名LogPresent
添加主输出:右键点击LogPresent选择添加-主输出(Project Outpu...),然后选择DBInstall的主输出(Primary Output)
添加项目文件:右键点击LogPresent选择视图-文件系统(File System)把发布好的网站所有文件夹文件拖放到Web Application Folder中。具体怎么拖不讲了,多试几次就知道。
添加数据库连接信息录入框:右键点击LogPresent选择视图-用户界面(User Interface),在Start下面添加一个文本框A(Textboxs A)设置如下:
这里的几个EditProperty后面会用到,可以根据自己的需要来设置。它们分别对应DBInstall.cs 中的this.Context.Parameters["server"],this.Context.Parameters["user"],this.Context.Parameters["password"]。
添加Customer Actions:右键点击LogPresent选择view-Customer Actions, 在Install中添加一个DBInstall主输出
然后,设置这个主输出的CustomerActionData属性为:
/server=[EDITA1] /user=[EDITA2] /password=[EDITA3] /targetdir="[TARGETDIR]\"(注:这里用到了之前在Textboxs A 中设置的几个参数 /targetdir="[TARGETDIR]\"用来获取服务器应用程序地址,在配置web.config时会用到)。
四、卸载程序
卸载可以参加http://www.cnblogs.com/syringa-flz/archive/2006/10/28/542579.html 不多说了。
好,一切搞定,编译以后安装包可用。其实还是很简单的。
一、前期准备
发布网站。准备好要打包的已经发布了的网站。至于怎么发布网站我就不说了,2005中发布网站很方便。
准备好SQL脚步。包括table,view,stroe procedure等。我这里只需要创建一个表和三个存储过程。(注:创建存储过程和表的脚步写到一起会出错,具体原因偶也搞不懂 所以我分开写的)
SQL.txt
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log]') AND type in (N'U'))
drop table [dbo].[Log]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log_Pagination]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Log_Pagination]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log_NoPagination]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Log_NoPagination]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OneLogDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[OneLogDetail]
CREATE TABLE [dbo].[Log](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Level] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
[Exception] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
[OutputData] [text] COLLATE Chinese_PRC_CI_AS NULL,
[InputData] [text] COLLATE Chinese_PRC_CI_AS NULL,
[SuccessFlag] [bit] NULL,
[FailureReason] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
[CustomerName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log]') AND type in (N'U'))
drop table [dbo].[Log]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log_Pagination]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Log_Pagination]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Log_NoPagination]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Log_NoPagination]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OneLogDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[OneLogDetail]
CREATE TABLE [dbo].[Log](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Level] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
[Exception] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
[OutputData] [text] COLLATE Chinese_PRC_CI_AS NULL,
[InputData] [text] COLLATE Chinese_PRC_CI_AS NULL,
[SuccessFlag] [bit] NULL,
[FailureReason] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
[CustomerName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
Pagination.txt
CREATE PROCEDURE [dbo].[Log_Pagination]
@PageSize int = 20, --record numbers of each page
@PageIndex int = 1, --current page index
@SuccessFlag varchar(1), --successflag true/false
@CustomerName varchar (50), --customer name
@DateFrom varchar(50), --date range start time
@DateTo varchar(50), --date range end time
@TotalRows int OUTPUT --total rows of pagination table
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SqlCMDString nvarchar(2000)
Begin
select @SqlCMDString ='SELECT @TotalRows=COUNT(*) FROM Log where 1=1'
IF(Cast(@SuccessFlag as varchar(1))!='2')
select @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
select @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
Exec sp_executesql @SqlCMDString,N'@TotalRows int out',@TotalRows out
End
DECLARE @CurrentPageLowerBound int
SET @CurrentPageLowerBound = (@PageIndex-1)* @PageSize
SET @SqlCMDString = 'SELECT TOP ' + cast(@PageSize As varchar(8))+ ' * FROM Log where 1=1'
IF(@PageIndex =1)
BEGIN
IF(Cast(@SuccessFlag as varchar(1))!='2')
SET @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
SET @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
SET @SqlCMDString = @SqlCMDString + ' ORDER BY Id'
Exec sp_executesql @SqlCMDString
END
ELSE
BEGIN
SET @SqlCMDString = @SqlCMDString + ' AND Id > (SELECT max(Id)'
SET @SqlCMDString = @SqlCMDString + ' FROM ( SELECT TOP '+ N'' + cast(@CurrentPageLowerBound As varchar(12)) + ' Id'
SET @SqlCMDString = @SqlCMDString + ' FROM Log Where 1=1 '
IF(Cast(@SuccessFlag as varchar(1))!='2')
SET @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
SET @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
SET @SqlCMDString = @SqlCMDString+'ORDER BY Id ) as temS ) ORDER BY Id'
--SET @SqlCMDString = @SqlCMDString + ' ) ORDER BY Id'
--print @SqlCMDString
Exec sp_executesql @SqlCMDString
END
END
CREATE PROCEDURE [dbo].[Log_Pagination]
@PageSize int = 20, --record numbers of each page
@PageIndex int = 1, --current page index
@SuccessFlag varchar(1), --successflag true/false
@CustomerName varchar (50), --customer name
@DateFrom varchar(50), --date range start time
@DateTo varchar(50), --date range end time
@TotalRows int OUTPUT --total rows of pagination table
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SqlCMDString nvarchar(2000)
Begin
select @SqlCMDString ='SELECT @TotalRows=COUNT(*) FROM Log where 1=1'
IF(Cast(@SuccessFlag as varchar(1))!='2')
select @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
select @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
Exec sp_executesql @SqlCMDString,N'@TotalRows int out',@TotalRows out
End
DECLARE @CurrentPageLowerBound int
SET @CurrentPageLowerBound = (@PageIndex-1)* @PageSize
SET @SqlCMDString = 'SELECT TOP ' + cast(@PageSize As varchar(8))+ ' * FROM Log where 1=1'
IF(@PageIndex =1)
BEGIN
IF(Cast(@SuccessFlag as varchar(1))!='2')
SET @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
SET @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
SET @SqlCMDString = @SqlCMDString + ' ORDER BY Id'
Exec sp_executesql @SqlCMDString
END
ELSE
BEGIN
SET @SqlCMDString = @SqlCMDString + ' AND Id > (SELECT max(Id)'
SET @SqlCMDString = @SqlCMDString + ' FROM ( SELECT TOP '+ N'' + cast(@CurrentPageLowerBound As varchar(12)) + ' Id'
SET @SqlCMDString = @SqlCMDString + ' FROM Log Where 1=1 '
IF(Cast(@SuccessFlag as varchar(1))!='2')
SET @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
SET @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
SET @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
SET @SqlCMDString = @SqlCMDString+'ORDER BY Id ) as temS ) ORDER BY Id'
--SET @SqlCMDString = @SqlCMDString + ' ) ORDER BY Id'
--print @SqlCMDString
Exec sp_executesql @SqlCMDString
END
END
NoPagination.txt
CREATE PROCEDURE [dbo].[Log_NoPagination]
@SuccessFlag varchar(1), --successflag true/false
@CustomerName varchar (50), --customer name
@DateFrom varchar(50), --date range start time
@DateTo varchar(50) --date range end time
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SqlCMDString nvarchar(2000)
select @SqlCMDString ='SELECT* FROM Log where 1=1'
IF(Cast(@SuccessFlag as varchar(1))!='2')
select @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
select @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
SET @SqlCMDString = @SqlCMDString + ' ORDER BY Id'
Exec sp_executesql @SqlCMDString
END
CREATE PROCEDURE [dbo].[Log_NoPagination]
@SuccessFlag varchar(1), --successflag true/false
@CustomerName varchar (50), --customer name
@DateFrom varchar(50), --date range start time
@DateTo varchar(50) --date range end time
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SqlCMDString nvarchar(2000)
select @SqlCMDString ='SELECT* FROM Log where 1=1'
IF(Cast(@SuccessFlag as varchar(1))!='2')
select @SqlCMDString = @SqlCMDString + ' AND SuccessFlag='+cast(@SuccessFlag as varchar(1))
IF(@CustomerName!='')
select @SqlCMDString = @SqlCMDString + ' AND CustomerName='+''''+@CustomerName+''''+''
IF(@DateFrom!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)>='+''''+Convert(varchar(10),@DateFrom,120)+''''+''
IF(@DateTo!='')
select @SqlCMDString = @SqlCMDString + ' AND Convert(Varchar(10),Date,120)<='+''''+Convert(Varchar(10),@DateTo,120)+''''+''
SET @SqlCMDString = @SqlCMDString + ' ORDER BY Id'
Exec sp_executesql @SqlCMDString
END
OneLogDetail.txt
Create PROCEDURE [dbo].[OneLogDetail]
@Id int --Log Id
AS
BEGIN
SELECT OutputData,InputData from Log WHERE Id=@Id
END
二、Installer类Create PROCEDURE [dbo].[OneLogDetail]
@Id int --Log Id
AS
BEGIN
SELECT OutputData,InputData from Log WHERE Id=@Id
END
添加一个项目DBInstall,在项目中添加一个新项,选择Installer class 取名DBInstaller.cs 具体实现如下:
DBInstaller.cs
1using System;
2using System.IO;
3using System.Reflection;
4using System.Data.SqlClient;
5using System.Collections.Generic;
6using System.ComponentModel;
7using System.Configuration.Install;
8using System.Xml;
9using Microsoft.Win32;
10using System.Security.AccessControl;
11
12namespace DBInstall
13{
14 [RunInstaller(true)]
15 public partial class DBInstaller : Installer
16 {
17 //The const string used to fix the database connection(Windows Authentication)
18 //private const string connectionString = "Data Source= 127.0.0.1;Initial Catalog= master;Integrated Security = SSPI";
19 private string connectionString;
20
21 //An SqlConnection used to connect the SqlServer
22 private System.Data.SqlClient.SqlConnection masterConnection;
23 public DBInstaller()
24 {
25 InitializeComponent();
26 }
27 //private void GetSql(string name)
28 //{
29 // System.Diagnostics.Process sqlProcess = new System.Diagnostics.Process();
30
31 // sqlProcess.StartInfo.FileName = "osql.exe";
32
33 // sqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -d {2} -i {3}SQL.sql", this.Context.Parameters["user"], this.Context.Parameters["password"], "master", this.Context.Parameters["targetdir"]);
34
35 // sqlProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
36
37 // sqlProcess.Start();
38
39 // sqlProcess.WaitForExit();//等待执行
40
41 // sqlProcess.Close();
42 // ////Gets the current assembly.
43 // //Assembly Asm = Assembly.GetExecutingAssembly();
44
45 // ////Resources are named using a fully qualified name.
46 // //Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + name);
47
48 // ////Reads the contents of the embedded file.
49 // //StreamReader reader = new StreamReader(strm);
50 // //return reader.ReadToEnd();
51
52 //}
53 private string GetSql(string name)
54 {
55 try
56 {
57 //Gets the current assembly.
58 Assembly Asm = Assembly.GetExecutingAssembly();
59
60 //Resources are named using a fully qualified name.
61 Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + name);
62
63 //Reads the contents of the embedded file.
64 StreamReader reader = new StreamReader(strm);
65 return reader.ReadToEnd();
66 }
67 finally { }
68 }
69
70 private void ExecuteSql(string dbName, string sql)
71 {
72
73 //Initialize the connection, open it, and set it to the "master" database
74 masterConnection = new System.Data.SqlClient.SqlConnection(connectionString);
75
76 //An instance of SqlCommand to realize the StrCommand
77 System.Data.SqlClient.SqlCommand command = new SqlCommand(sql, masterConnection);
78
79 if (masterConnection.State == System.Data.ConnectionState.Closed)
80 {
81 masterConnection.Open();
82 }
83
84 command.Connection.ChangeDatabase(dbName);
85
86 try
87 {
88 command.ExecuteNonQuery();
89 }
90 finally
91 {
92 //Closing the connection should be done in a Finally block
93 command.Connection.Close();
94 }
95 }
96
97 private void WriteWebConfig()
98 {
99 try
100 {
101 FileInfo fileInfo = new FileInfo(this.Context.Parameters["targetdir"] + @"\web.config");
102 if (!fileInfo.Exists)
103 throw new InstallException("Did not find config file");
104
105 //Instantiate xml
106 XmlDocument xmlDoc = new XmlDocument();
107 xmlDoc.Load(fileInfo.FullName);
108
109 //Find appsettings node
110 bool foundIt = false;
111 foreach (XmlNode node in xmlDoc.DocumentElement.SelectNodes("//connectionStrings/add"))
112 {
113 if (node.Name == "add")
114 {
115 if (node.Attributes.GetNamedItem("name").Value == "ExperianConnectionString")
116 node.Attributes.GetNamedItem("connectionString").Value = String.Format("Persist Security Info=True;Data Source={0};Initial Catalog=ExperianServer;User ID={1};Password={2};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1",
117 this.Context.Parameters["server"], this.Context.Parameters["user"], this.Context.Parameters["password"]);
118 foundIt = true;
119 }
120 }
121 if (foundIt == false)
122 throw new InstallException("web.config does not contains configSections");
123 xmlDoc.Save(fileInfo.FullName);
124 }
125 catch (Exception ex)
126 {
127 throw ex;
128 }
129 }
130
131 private void SettingDirectoryPopedom()
132 {
133 // Create a new DirectoryInfo object.
134 DirectoryInfo dInfo = new DirectoryInfo(this.Context.Parameters["targetdir"] + @"\XmlFiles");
135
136 // Get a DirectorySecurity object that represents the
137 // current security settings.
138 DirectorySecurity dSecurity = dInfo.GetAccessControl();
139
140 // Add the FileSystemAccessRule to the security settings.
141 dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.Modify, AccessControlType.Allow));
142
143 // Set the new access settings.
144 dInfo.SetAccessControl(dSecurity);
145
146 }
147
148
149 protected void AddDBTable(string strDBName)
150 {
151 try
152 {
153 //Creates the database.
154 ExecuteSql("MASTER", "IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'"
155 + strDBName + "') CREATE DATABASE " + strDBName);
156
157 //Creates the tables.
158 ExecuteSql(strDBName, GetSql("SQL.txt"));
159 ExecuteSql(strDBName, GetSql("Pagination.txt"));
160 ExecuteSql(strDBName, GetSql("NoPagination.txt"));
161 ExecuteSql(strDBName, GetSql("OneLogDetail.txt"));
162
163 }
164 finally { }
165 }
166
167 public override void Install(System.Collections.IDictionary stateSaver)
168 {
169 base.Install(stateSaver);
170
171 string server, user, password;
172 server = this.Context.Parameters["server"];
173 user = this.Context.Parameters["user"];
174 password = this.Context.Parameters["password"];
175
176 connectionString = "Data Source= "+server+";Initial Catalog= master;User Id ="+user+"; Password = "+password;
177
178 //Create database "EXPERIANSERVER"
179 AddDBTable("EXPERIANSERVER");
180 //Config web.config.
181 WriteWebConfig();
182 //Setting directory's popedom
183 SettingDirectoryPopedom();
184 }
185
186 public override void Uninstall(System.Collections.IDictionary savedState)
187 {
188 base.Uninstall(savedState);
189
190 //Drop the database
191 //string strDelTable = "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'EXPERIANSERVER') DROP DATABASE EXPERIANSERVER";
192 //ExecuteSql("MASTER", strDelTable);
193 }
194 }
195}
然后把刚才写的几个SQL文本添加到该项目中,并且设置几个文本的Build Action属性为Embedded Resource1using System;
2using System.IO;
3using System.Reflection;
4using System.Data.SqlClient;
5using System.Collections.Generic;
6using System.ComponentModel;
7using System.Configuration.Install;
8using System.Xml;
9using Microsoft.Win32;
10using System.Security.AccessControl;
11
12namespace DBInstall
13{
14 [RunInstaller(true)]
15 public partial class DBInstaller : Installer
16 {
17 //The const string used to fix the database connection(Windows Authentication)
18 //private const string connectionString = "Data Source= 127.0.0.1;Initial Catalog= master;Integrated Security = SSPI";
19 private string connectionString;
20
21 //An SqlConnection used to connect the SqlServer
22 private System.Data.SqlClient.SqlConnection masterConnection;
23 public DBInstaller()
24 {
25 InitializeComponent();
26 }
27 //private void GetSql(string name)
28 //{
29 // System.Diagnostics.Process sqlProcess = new System.Diagnostics.Process();
30
31 // sqlProcess.StartInfo.FileName = "osql.exe";
32
33 // sqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -d {2} -i {3}SQL.sql", this.Context.Parameters["user"], this.Context.Parameters["password"], "master", this.Context.Parameters["targetdir"]);
34
35 // sqlProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
36
37 // sqlProcess.Start();
38
39 // sqlProcess.WaitForExit();//等待执行
40
41 // sqlProcess.Close();
42 // ////Gets the current assembly.
43 // //Assembly Asm = Assembly.GetExecutingAssembly();
44
45 // ////Resources are named using a fully qualified name.
46 // //Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + name);
47
48 // ////Reads the contents of the embedded file.
49 // //StreamReader reader = new StreamReader(strm);
50 // //return reader.ReadToEnd();
51
52 //}
53 private string GetSql(string name)
54 {
55 try
56 {
57 //Gets the current assembly.
58 Assembly Asm = Assembly.GetExecutingAssembly();
59
60 //Resources are named using a fully qualified name.
61 Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + name);
62
63 //Reads the contents of the embedded file.
64 StreamReader reader = new StreamReader(strm);
65 return reader.ReadToEnd();
66 }
67 finally { }
68 }
69
70 private void ExecuteSql(string dbName, string sql)
71 {
72
73 //Initialize the connection, open it, and set it to the "master" database
74 masterConnection = new System.Data.SqlClient.SqlConnection(connectionString);
75
76 //An instance of SqlCommand to realize the StrCommand
77 System.Data.SqlClient.SqlCommand command = new SqlCommand(sql, masterConnection);
78
79 if (masterConnection.State == System.Data.ConnectionState.Closed)
80 {
81 masterConnection.Open();
82 }
83
84 command.Connection.ChangeDatabase(dbName);
85
86 try
87 {
88 command.ExecuteNonQuery();
89 }
90 finally
91 {
92 //Closing the connection should be done in a Finally block
93 command.Connection.Close();
94 }
95 }
96
97 private void WriteWebConfig()
98 {
99 try
100 {
101 FileInfo fileInfo = new FileInfo(this.Context.Parameters["targetdir"] + @"\web.config");
102 if (!fileInfo.Exists)
103 throw new InstallException("Did not find config file");
104
105 //Instantiate xml
106 XmlDocument xmlDoc = new XmlDocument();
107 xmlDoc.Load(fileInfo.FullName);
108
109 //Find appsettings node
110 bool foundIt = false;
111 foreach (XmlNode node in xmlDoc.DocumentElement.SelectNodes("//connectionStrings/add"))
112 {
113 if (node.Name == "add")
114 {
115 if (node.Attributes.GetNamedItem("name").Value == "ExperianConnectionString")
116 node.Attributes.GetNamedItem("connectionString").Value = String.Format("Persist Security Info=True;Data Source={0};Initial Catalog=ExperianServer;User ID={1};Password={2};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1",
117 this.Context.Parameters["server"], this.Context.Parameters["user"], this.Context.Parameters["password"]);
118 foundIt = true;
119 }
120 }
121 if (foundIt == false)
122 throw new InstallException("web.config does not contains configSections");
123 xmlDoc.Save(fileInfo.FullName);
124 }
125 catch (Exception ex)
126 {
127 throw ex;
128 }
129 }
130
131 private void SettingDirectoryPopedom()
132 {
133 // Create a new DirectoryInfo object.
134 DirectoryInfo dInfo = new DirectoryInfo(this.Context.Parameters["targetdir"] + @"\XmlFiles");
135
136 // Get a DirectorySecurity object that represents the
137 // current security settings.
138 DirectorySecurity dSecurity = dInfo.GetAccessControl();
139
140 // Add the FileSystemAccessRule to the security settings.
141 dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.Modify, AccessControlType.Allow));
142
143 // Set the new access settings.
144 dInfo.SetAccessControl(dSecurity);
145
146 }
147
148
149 protected void AddDBTable(string strDBName)
150 {
151 try
152 {
153 //Creates the database.
154 ExecuteSql("MASTER", "IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'"
155 + strDBName + "') CREATE DATABASE " + strDBName);
156
157 //Creates the tables.
158 ExecuteSql(strDBName, GetSql("SQL.txt"));
159 ExecuteSql(strDBName, GetSql("Pagination.txt"));
160 ExecuteSql(strDBName, GetSql("NoPagination.txt"));
161 ExecuteSql(strDBName, GetSql("OneLogDetail.txt"));
162
163 }
164 finally { }
165 }
166
167 public override void Install(System.Collections.IDictionary stateSaver)
168 {
169 base.Install(stateSaver);
170
171 string server, user, password;
172 server = this.Context.Parameters["server"];
173 user = this.Context.Parameters["user"];
174 password = this.Context.Parameters["password"];
175
176 connectionString = "Data Source= "+server+";Initial Catalog= master;User Id ="+user+"; Password = "+password;
177
178 //Create database "EXPERIANSERVER"
179 AddDBTable("EXPERIANSERVER");
180 //Config web.config.
181 WriteWebConfig();
182 //Setting directory's popedom
183 SettingDirectoryPopedom();
184 }
185
186 public override void Uninstall(System.Collections.IDictionary savedState)
187 {
188 base.Uninstall(savedState);
189
190 //Drop the database
191 //string strDelTable = "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'EXPERIANSERVER') DROP DATABASE EXPERIANSERVER";
192 //ExecuteSql("MASTER", strDelTable);
193 }
194 }
195}
(注:这一步是必须的)
一切搞定之后,将DBInstall编译一次。
三、Web Setup Project
添加安装项目:在解决方案中添加一个Web Setup Project。我这里取名LogPresent
添加主输出:右键点击LogPresent选择添加-主输出(Project Outpu...),然后选择DBInstall的主输出(Primary Output)
添加项目文件:右键点击LogPresent选择视图-文件系统(File System)把发布好的网站所有文件夹文件拖放到Web Application Folder中。具体怎么拖不讲了,多试几次就知道。
添加数据库连接信息录入框:右键点击LogPresent选择视图-用户界面(User Interface),在Start下面添加一个文本框A(Textboxs A)设置如下:
这里的几个EditProperty后面会用到,可以根据自己的需要来设置。它们分别对应DBInstall.cs 中的this.Context.Parameters["server"],this.Context.Parameters["user"],this.Context.Parameters["password"]。
添加Customer Actions:右键点击LogPresent选择view-Customer Actions, 在Install中添加一个DBInstall主输出
然后,设置这个主输出的CustomerActionData属性为:
/server=[EDITA1] /user=[EDITA2] /password=[EDITA3] /targetdir="[TARGETDIR]\"(注:这里用到了之前在Textboxs A 中设置的几个参数 /targetdir="[TARGETDIR]\"用来获取服务器应用程序地址,在配置web.config时会用到)。
四、卸载程序
卸载可以参加http://www.cnblogs.com/syringa-flz/archive/2006/10/28/542579.html 不多说了。
好,一切搞定,编译以后安装包可用。其实还是很简单的。