设为首页 收藏本站
查看: 1130|回复: 0

[经验分享] C#ASP.NET打包安装部署文件一键安装网站,包括IIS站点创建、数据库附加。

[复制链接]

尚未签到

发表于 2017-12-27 19:39:06 | 显示全部楼层 |阅读模式
//iis服务器地址下面方法会用到所以定义公共  string iis = "";
  //重写Install
  public override void Install(IDictionary stateSaver)
  {
  base.Install(stateSaver);
  //接收参数
  

  //数据库服务器地址
  string databaseServer = Context.Parameters["server"].ToString();
  //账号
  string user = Context.Parameters["user"].ToString();
  //密码
  string pwd = Context.Parameters["pwd"].ToString();
  //安装路径
  string targetdir = Context.Parameters["targetdir"].ToString().Replace(@"\\", @"\");
  //IIS地址
  iis = this.Context.Parameters["iis"].ToString();
  //ip
  string ip = this.Context.Parameters["ip"].ToString();
  //端口
  string port = this.Context.Parameters["port"].ToString();
  //网站名
  string isname = this.Context.Parameters["isname"].ToString();
  

  //File.WriteAllText(Path.Combine(targetdir, "log11.txt"), "databaseServer:" + databaseServer + "/n/r" + "user:" + user + "/n/r" + "pwd:" + pwd + "/n/r" + "targetdir:" + targetdir + "/n/r" + "iis:" + iis + "/n/r" + "port:" + port + "/n/r" + "isname" + isname + "/n/r" + "serverID:" + serverID);
  

  try
  {
  //实例化IIS站点配置信息
  NewWebSiteInfo nwsif = new NewWebSiteInfo(ip, port, isname.Trim(), (isname.Trim().Length > 0 ? isname : "anjiesigudingzichan"), targetdir);
  //创建IIS站点
  
                CreateNewWebSite(nwsif);
  

  #region 附加数据库
  

  //给文件添加"Authenticated Users,Everyone,Users"用户组的完全控制权限 ,要附加的数据库文件必须加权限否则无法附加
  if (File.Exists(Context.Parameters["targetdir"].ToString() + "App_Data\\ceshi.mdf"))
  {
  FileInfo fi = new FileInfo(Context.Parameters["targetdir"].ToString() + "App_Data\\ceshi.mdf");
  System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();
  fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
  fileSecurity.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.FullControl, AccessControlType.Allow));
  fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
  fi.SetAccessControl(fileSecurity);
  FileInfo fi1 = new FileInfo(Context.Parameters["targetdir"].ToString() + "App_Data\\ceshi.ldf");
  System.Security.AccessControl.FileSecurity fileSecurity1 = fi1.GetAccessControl();
  fileSecurity1.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
  fileSecurity1.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.FullControl, AccessControlType.Allow));
  fileSecurity1.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
  fi1.SetAccessControl(fileSecurity1);
  }
  

  string connectionString = GetConnectionString(null);
  

  //保存数据连接词,为卸载做准备
  File.WriteAllText(Path.Combine(targetdir + "\\" + "App_Data\\", "log.txt"), connectionString);
  

  try
  {
  using (SqlConnection connection = new SqlConnection(connectionString))
  {
  connection.Open();
  //使用数据库文件创建数据库,所以添加的网站项目中需要有App_Data文件夹和数据库文件(ceshi.mdf)和日志文件(ceshi.ldf)
  string sql = "sp_attach_db 'ceshi','" + Context.Parameters["targetdir"].ToString() + "App_Data\\ceshi.mdf','" + Context.Parameters["targetdir"].ToString() + "App_Data\\ceshi.ldf'";
  ExecuteSQL(connection, sql);
  connection.Close();
  

  //修改config文件连接词
  string webconfigpath = Path.Combine(this.Context.Parameters["targetdir"].ToString(), "web.config");
  string webcofnigstring = File.ReadAllText(webconfigpath).Replace("#constring#", GetConnectionString("ceshi"));
  File.WriteAllText(webconfigpath, webcofnigstring);
  }
  }
  catch (Exception ex)
  {
  MessageBox.Show("安装出错了1!\n" + ex.ToString(), "出错啦!");
  }
  

  #endregion
  }
  catch (Exception exx)
  {
  MessageBox.Show("安装出错了!2\n" + exx.ToString(), "出错啦!");
  }
  }
  

  /// <summary>
  /// 执行SQL语句
  /// </summary>
  /// <param name="connection"></param>
  /// <param name="sql"></param>
  void ExecuteSQL(SqlConnection connection, string sql)
  {
  SqlCommand cmd = new SqlCommand(sql, connection);
  cmd.ExecuteNonQuery();
  }
  

  /// <summary>
  /// 获取数据库登陆连接字符串
  /// </summary>
  /// <param name="databasename"></param>
  /// <returns></returns>
  private string GetConnectionString(string databasename)
  {
  return "server=" + Context.Parameters["server"].ToString() + ";database=" + (string.IsNullOrEmpty(databasename) ? "master" : databasename) + ";Useruser"].ToString() + ";Password=" + Context.Parameters["pwd"].ToString();
  }
  

  /// <summary>
  /// 创建IIS站点
  /// </summary>
  /// <param name="siteInfo">新站点配置信息</param>
  public void CreateNewWebSite(NewWebSiteInfo siteInfo)
  {
  string entPath = String.Format("IIS://{0}/W3SVC", iis);
  

  //SetFileRole();
  

  if (!EnsureNewSiteEnavaible(siteInfo.BindString, entPath))
  {
  throw new Exception("该网站已存在" + Environment.NewLine + siteInfo.BindString);
  }
  

  DirectoryEntry rootEntry = new DirectoryEntry(entPath);
  

  string newSiteNum = GetNewWebSiteID(entPath);
  

  DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, "IIsWebServer");
  newSiteEntry.CommitChanges();
  

  newSiteEntry.Properties["ServerBindings"].Value = siteInfo.BindString;
  newSiteEntry.Properties["ServerComment"].Value = siteInfo.CommentOfWebSite;
  newSiteEntry.Properties["ServerAutoStart"].Value = true;//网站是否启动
  
            newSiteEntry.CommitChanges();
  

  DirectoryEntry vdEntry = newSiteEntry.Children.Add("root", "IIsWebVirtualDir");
  vdEntry.CommitChanges();
  string ChangWebPath = siteInfo.WebPath.Trim().Remove(siteInfo.WebPath.Trim().LastIndexOf('\\'), 1);
  vdEntry.Properties["Path"].Value = ChangWebPath;
  

  

  vdEntry.Invoke("AppCreate", true);//创建应用程序
  //vdEntry.Properties["ServerAutoStart"].Value = true;//网站是否启动
  vdEntry.Properties["AccessRead"][0] = true; //设置读取权限
  vdEntry.Properties["AccessWrite"][0] = true;
  vdEntry.Properties["AccessScript"][0] = true;//执行权限
  vdEntry.Properties["AccessExecute"][0] = false;
  vdEntry.Properties["DefaultDoc"][0] = "Login_gdzc.aspx";//设置默认文档
  vdEntry.Properties["AppFriendlyName"][0] = "LabManager"; //应用程序名称
  vdEntry.Properties["AuthFlags"][0] = 1;//0表示不允许匿名访问,1表示就可以3为基本身份验证,7为windows继承身份验证
  
            vdEntry.CommitChanges();
  

  //操作增加MIME
  //IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
  //NewMime.Extension = ".xaml"; NewMime.MimeType = "application/xaml+xml";
  //IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
  //TwoMime.Extension = ".xap"; TwoMime.MimeType = "application/x-silverlight-app";
  //rootEntry.Properties["MimeMap"].Add(NewMime);
  //rootEntry.Properties["MimeMap"].Add(TwoMime);
  //rootEntry.CommitChanges();
  

  #region 针对IIS7
  DirectoryEntry getEntity = new DirectoryEntry("IIS://" + iis + "/W3SVC/INFO");
  int Version = int.Parse(getEntity.Properties["MajorIISVersionNumber"].Value.ToString());
  if (Version > 6)
  {
  #region 创建应用程序池
  string AppPoolName = "LabManager";
  if (!IsAppPoolName(AppPoolName))
  {
  DirectoryEntry newpool;
  DirectoryEntry appPools = new DirectoryEntry("IIS://" + iis + "/W3SVC/AppPools");
  newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
  newpool.CommitChanges();
  }
  #endregion
  

  #region 修改应用程序的配置(包含托管模式及其NET运行版本)
  ServerManager sm = new ServerManager();
  sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";

  sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成>  
                sm.CommitChanges();
  #endregion
  

  vdEntry.Properties["AppPoolId"].Value = AppPoolName;
  vdEntry.CommitChanges();
  }
  

  #endregion
  

  

  //启动aspnet_regiis.exe程序
  string fileName = Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
  ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
  //处理目录路径
  string path = vdEntry.Path.ToUpper();
  int index = path.IndexOf("W3SVC");
  path = path.Remove(0, index);
  //启动ASPnet_iis.exe程序,刷新脚本映射
  startInfo.Arguments = "-s " + path;
  startInfo.WindowStyle = ProcessWindowStyle.Hidden;
  startInfo.UseShellExecute = false;
  startInfo.CreateNoWindow = true;
  startInfo.RedirectStandardOutput = true;
  startInfo.RedirectStandardError = true;
  Process process = new Process();
  process.StartInfo = startInfo;
  process.Start();
  process.WaitForExit();
  string errors = process.StandardError.ReadToEnd();
  

  if (errors != string.Empty)
  {
  throw new Exception(errors);
  }
  

  }
  #region 判定网站是否存在
  

  /// <summary>
  /// 确定一个新的网站与现有的网站没有相同的。
  /// 这样防止将非法的数据存放到IIS里面去
  /// </summary>
  /// <param name="bindStr">网站邦定信息</param>
  /// <returns>真为可以创建,假为不可以创建</returns>
  public bool EnsureNewSiteEnavaible(string bindStr, string entPath)
  {
  DirectoryEntry ent = new DirectoryEntry(entPath);
  

  foreach (DirectoryEntry child in ent.Children)
  {
  if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerBindings"].Value != null && child.Properties["ServerBindings"].Value.ToString() == bindStr)
  {
  return false;
  }
  }
  return true;
  }
  

  /// <summary>
  /// 设置文件夹权限 处理给EVERONE赋予所有权限
  /// </summary>
  /// <param name="FileAdd">文件夹路径</param>
  public void SetFileRole()
  {
  string FileAdd = this.Context.Parameters["targetdir"].ToString();
  FileAdd = FileAdd.Remove(FileAdd.LastIndexOf('\\'), 1);
  DirectorySecurity fSec = new DirectorySecurity();
  fSec.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
  System.IO.Directory.SetAccessControl(FileAdd, fSec);
  }
  

  #endregion

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-428730-1-1.html 上篇帖子: 小轩窗,正梳妆 下篇帖子: SQLITE在IIS中使用问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表