Monday, April 27, 2009

修改 connection string during install process

public bool modifyConnectionString(string ServerName, string DBName, string AdminName, string AdminPwd, string targetSite)
{

string connectionString = string.Empty;

if (AdminName != string.Empty && AdminPwd != string.Empty)
connectionString = String.Format("Data Source={0};initial catalog={1};id={2};password={3}", ServerName, DBName, AdminName, AdminPwd);
else
connectionString = String.Format("Integrated Security=true;Data Source={0};initial catalog={1}", ServerName, DBName);
try
{
// Get the configuration object for a Web application
// running on the local server.
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("/" + targetSite)
as System.Configuration.Configuration;

// Get the appSettings.
ConnectionStringSettings settings = new ConnectionStringSettings();
settings.Name = "connectionString1";
settings.ConnectionString = connectionString;
MessageBox.Show(connectionString);
config.ConnectionStrings.ConnectionStrings.Clear();
config.ConnectionStrings.ConnectionStrings.Add(settings);
config.Save();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}

}

run Sql generate from sql 2005

need:
Microsoft.sqlServer.ConnectionInfo
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoEnum

c#
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

private void ExecuteSqlfile(string sqlstring)
{
if (ConnectDatabase())
{
try
{
Server server = new Server(new ServerConnection(sqlConn));
server.ConnectionContext.ExecuteNonQuery(sqlstring);

}
finally
{
Command.Connection.Close();
}
}
}

install/uninstall windows service and start it.

install.bat file (%1 --parameter 1, e.g. install.bat c:\Program Files\)
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i
cd %1
InstallUtil.exe winservice.exe
NET START "your win services display name"
Pause

uninstall.bat file
cd %1
InstallUtil.exe -u winservice.exe
Pause

c# to run the install.bat file
ProgramFilesx86() run the system program file folder path (e.g. "c:\Program File")
using System.Diagnostics;
System.Diagnostics.Process.Start("\"" + ProgramFilesx86() + "\\path\\install.bat\"", parameter1);

使用VS2005部署带有数据库的Web站点

1. 在“新建项目”对话框的左侧树状图中选择“Other Project Types”->“Setup and Deployment”节点,在右侧选择“Web Setup Project”。

2. 在Solution Explorer中在Solution上点右键,选择“Add”->“Existing Web Site”,将存放编译好的Web网站的文件夹加入Solution中。

如果添加使用aspnet_compiler编译好的网站,有可能会出现下面的提示框,点击“是”就行。


3. 再添加一个新的“Class Library”,名称“CreateDB”,用以创建数据库的操作。


删除默认生成的“class1.cs”,在这个项目上点右键,选择“Add”->“New Item”,在弹出的对话框中选择“Installer Class”,点击OK。

在类中添加如下代码:
private void ExecuteSql(string connectionString, string databaseName, string sql)
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
try
{
sqlCommand.Connection.Open();
sqlCommand.Connection.ChangeDatabase(databaseName);
sqlCommand.ExecuteNonQuery();
}
catch (Exception exception)
{
throw exception;
}
finally
{
sqlCommand.Connection.Close();
}
}

public override void Install(System.Collections.IDictionary stateSaver)
{
string server = this.Context.Parameters["server"];
string database = this.Context.Parameters["dbname"];
string user = this.Context.Parameters["user"];
string password = this.Context.Parameters["pwd"];
string targetDir = this.Context.Parameters["targetdir"];

try
{
string connectionString = String.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096",
server, user, password);

//create db
ExecuteSql(connectionString, "master", "CREATE DATABASE " + database);

//set user
string setUserString = "sp_addlogin 'PrinteryERP', 'PrinteryERP', 'PrinteryERP'";
string setAccessString = "sp_grantdbaccess 'PrinteryERP'";
string setRole = "sp_addrolemember 'db_owner', 'PrinteryERP'";

//create new user login
try
{
ExecuteSql(connectionString, "master", setUserString);
}
catch { }

//set default database
try
{
ExecuteSql(connectionString, "PrinteryERP", setAccessString);
}
catch { }

//set read role
try
{
ExecuteSql(connectionString, "PrinteryERP", setRole);
}
catch { }

//create table,store produce......
Process osqlProcess = new Process();
osqlProcess.StartInfo.FileName = targetDir + "osql.exe";
osqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {3} -i {4}createdb.sql",
user, password, server, database, targetDir);
osqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
osqlProcess.Start();
osqlProcess.WaitForExit();
osqlProcess.Close();

//add data
osqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {3} -i {4}insertdata.sql",
user, password, server, database, targetDir);
osqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
osqlProcess.Start();
osqlProcess.WaitForExit();
osqlProcess.Close();
}
catch (Exception exception)
{
throw exception;
}

try
{
string configFile = targetDir + "/Web.config";
if (!File.Exists(configFile))
{
throw new InstallException("没有找到配置文件。");
}

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(configFile);

GC.Collect();
File.Delete(configFile);
GC.Collect();

foreach (XmlNode xmlNode in xmlDoc["configuration"]["connectionStrings"].ChildNodes)
{
if (xmlNode.Name == "add")
{
if (xmlNode.Attributes["name"].Value == "DBConnection")
{
xmlNode.Attributes["connectionString"].Value = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=PrinteryERP;Password=PrinteryERP",
server, database);
}
if (xmlNode.Attributes["name"].Value == "UserManageServicesConnection")
{
xmlNode.Attributes["connectionString"].Value = String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=PrinteryERP;Password=PrinteryERP",
server, database);
}
}
}
xmlDoc.Save(configFile);
}
catch (Exception exception)
{
throw exception;
}
}
4. 在“Web Setup Project”项目上点右键,选择“Add”->“Project Output”,选择Project“CreateDB”,选择“Primary Output”,点击OK。重复上述动作,将选择刚才添加的Web Site,选择“Content Files”,点击OK。


5. 在“Web Setup Project”项目上点右键,选择“Add”->“File”,将创建数据库表、存储过程和视图的脚本createdb.sql加入。重复,将向 数据表中添加基础数据的脚本insertdata.sql加入。重复,将程序osql.exe加入。
6. 在“Web Setup Project”项目上点右键,选择“Add”->“Merge Module”,在弹出的对话框中选择“VC_User_CRT71_RTL_X86_---.msm”,点击OK。添加这个VC运行库是因为在一台干净 的机器上测试的时候发现osql.exe这个程序需要这个库。
7. 在“Web Setup Project”项目上点右键,选择“Properties”,在弹出的对话框中可以设置一些安装程序的属性。点击按钮“Prerequisites”, 在弹出的对话框中选中“.NET Framework 2.0”和“Windows Installer 3.1”,选中“Download prerequisites from the same location as my application”。这样就可以把这些组件和应用程序打包在一起,安装的时候自动检测并安装了。如果需要部署的计算机如果没有打过最新的补丁的话, 是没有“Windows Installer 3.1”的,如果没有这个组件,“.NET Framework 2.0”是不能安装的。

8.在“Web Setup Project”项目上点右键,选择“View”->“Custom Actions”,在出现的树状图的节点“Install”上点右键,选择“Add Custom Actions”。在弹出的对话框中“Look in”中选择“Web Application Folders”,在下面选择“Primary output from CreateDB (Active)”,点击OK。


9. 在“Web Setup Project”项目上点右键,选择“View”->“User Interface”,在出现的树状图节点“Install”的子节点“Start”上点击右键,选择“Add Dialog”,在弹出的对话框中选择“TextBoxes(A)”。

在新添加的节点“TextBoxes (A)”上点击右键,选择“Properites Window”,依次设置Edit*Property属性为“CUSTOMTEXTA1”,“CUSTOMTEXTA2”,“CUSTOMTEXTA3” 和“CUSTOMTEXTA4”。

10. 在刚刚建立的“Primary output from CreateDB (Active)”节点上点右键,选择“Properties Window”,设置“CustomActionData”属性为“/dbname=[CUSTOMTEXTA1] /server=[CUSTOMTEXTA2] /user=[CUSTOMTEXTA3] /pwd=[CUSTOMTEXTA4] /targetdir="[TARGETDIR]\"”。

接下来对整个解决方案进行编译,会在输出目录下生成两个文件夹和两个文件。
两个文件夹中分别包含了.NET Framework 2.0和Windows Installer3.1的安装包。另外的两个文件分别是(项目名称).msi和setup.exe。如果要进行安装,请执行setup.exe。

Bootstrap Manifest Generator - How To Setup Custom Pre-Requisites (VS 2005 Web setup project)

Bootstrap Manifest Generator - How To Setup Custom Pre-Requisites (VS 2005 Web setup project)

From: http://jcrawfor74.wordpress.com/2008/02/27/bootstrap-manifest-generator-how-to-custom-pre-requisites/

Recently I was attempting to create a deployment package that has customised pre-requisites i.e I wanted my installer to detect if AJAX Extensions 1.0 was installed and if not ask the user to install it.

I found this link talking about how to do it..

http://www.codeplex.com/MSAjax10SetupPrereq

Which lead me to download the Bootstapper Manifest generator from http://www.codeplex.com/bmg

http://www.davidguyer.us/BMG/publish.htm

I was a bit lost with what to do so hopefully this will save you the pain I went though.

(Note: the BMG is really buggy. Most of the system checks don’t work, and once you add a file system check and save your project you can no longer open your bootstrap project. But given it is free it’s better than attempting to write the XML by hand)

As an example to create a pre-requisite for AJAX follow these steps:
  1. Run the BMG tool.
  2. Create a new Package Manifest. Give it a name, AJAX
  3. Add a file, choose the AJAX Extension installer .msi.
  4. Give it a name, this will be the name that appears in your installer so make it something nice like “Microsoft ASP .Net 2.0 AJAX Extensions 1.0″
  5. Build it.
Now if it builds have a look at the location that it is written to, it is a visual studio directory, so I thought to myself it must integrate with VS2005.
So open your Setup Project in visual studio, (in my case, a Web Setup Project). Right Click — Properties on the solution. There in the bottom right is the pre-requisite button.
Click on it and you should now see AJAX as an option.
Traps for young players
1. Copy paste
Inside the BGM copy and paste does not appear to work. The trick, is right click in the field and choose paste.
2. Download from web Option
If you want to download from the web enter the url for the .exe. I setup my own publically available spot to allow downloading these pre-requesites (rather than relying on the microsoft download site), as they migth change things. So I have a known static location to go download the AJAX Extensions msi.
3. System Checks
You should include a check to see whether AJAX is already installed.
In your manifest click on the file you added, and go to the “System Checks” tab. I found that most of the system checks did not work properly.
I found the one that did work was a file check, so I added a file check for System.Web.Extensions.dll in the default location
  • Add a File check. Set the file name to System.Web.Extensions.dll, turn off the search, and enter the default path to the ASP Net folder.
  • Switch to the “Install Conditions” tab and add a line that says:
    • Type - By Pass If
    • Property - AJAX (or the name you gave your system check
    • Comparison - Exists

Cheers and goodluck