评论

收藏

[IIS] C#部署数据库及IIS站点

web服务器 web服务器 发布于:2022-04-29 10:42 | 阅读数:569 | 评论:0

这篇文章主要为大家详细介绍了C#部署数据库及IIS站点的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
一、前言
最近忙里偷闲,做了一个部署数据库及iis网站站点的wpf应用程序工具。
二、内容
此工具的目的是:

  • 根据.sql文件在本机上部署数据库
  • 在本机部署iis站点,包括新建站点,新建应用程序池。只新建而不会对本机上原有的程序池或站点做修改操作
最终样式:(check按钮的作用是防止与本机已有的站点或程序池有冲突)
DSC0000.jpg

view:
<window x:class="autowebtool.mainwindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
  xmlns:local="clr-namespace:autowebtool"
  title="web site automatic deployment" height="500" width="800" windowstartuplocation="centerscreen" resizemode="noresize">
  <grid>
  <grid.rowdefinitions>
    <rowdefinition height="0.5*"/>
    <rowdefinition height="0.5*"/>
    <rowdefinition height="auto"/>
  </grid.rowdefinitions>
  <groupbox header="database configuration" fontsize="15" borderthickness="3" margin="5,10" grid.row="0">
    <grid>
    <grid.rowdefinitions>
      <rowdefinition/>
      <rowdefinition/>
      <rowdefinition/>
      <rowdefinition/>
    </grid.rowdefinitions>
    <grid.columndefinitions>
      <columndefinition width="65*"/>
      <columndefinition width="133*"/>
      <columndefinition width="auto"/>
    </grid.columndefinitions>
 
    <textblock grid.row="0" grid.column="0" text="server address" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="1" grid.column="0" text="user" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="2" grid.column="0" text="password" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="3" grid.column="0" text="script path" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
 
    <textbox grid.row="0" grid.column="1" text="{binding serveraddress, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
    <textbox grid.row="1" grid.column="1" text="{binding user, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
    <passwordbox grid.row="2" grid.column="1" passwordchar="*" local:passwordboxhelper.password="{binding password, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32">
      <i:interaction.behaviors>
      <local:passwordboxbehavior />
      </i:interaction.behaviors>
    </passwordbox>
    <textbox grid.row="3" grid.column="1" text="{binding sqlpath, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
 
    <button grid.row="4" grid.column="2" width="70" height="25" margin="0,0,10,0"
      horizontalalignment="left" verticalalignment="center" content="browse" click="filepathbrowse_click"/>
    </grid> 
  </groupbox>
  <groupbox header="website and pool" fontsize="15" borderthickness="3" margin="5,10" grid.row="1">
    <grid>
    <grid.rowdefinitions>
      <rowdefinition/>
      <rowdefinition/>
      <rowdefinition/>
      <rowdefinition/>
      <rowdefinition/>
    </grid.rowdefinitions>
    <grid.columndefinitions>
      <columndefinition width="65*"/>
      <columndefinition width="133*"/>
      <columndefinition width="auto"/>
    </grid.columndefinitions>
 
    <textblock grid.row="0" grid.column="0" text="website name" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="1" grid.column="0" text="website id" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="2" grid.column="0" text="website physicalpath" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="3" grid.column="0" text="website port" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26" />
    <textblock grid.row="4" grid.column="0" text="application pool name" horizontalalignment="center" verticalalignment="center" fontsize="15" height="26"/>
 
    <textbox grid.row="0" grid.column="1" text="{binding websitename, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
    <textbox grid.row="1" grid.column="1" text="{binding websiteid, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
    <textbox grid.row="2" grid.column="1" text="{binding physicalpath, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
    <textbox grid.row="3" grid.column="1" text="{binding websiteport, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
    <textbox grid.row="4" grid.column="1" text="{binding poolname, mode=twoway, updatesourcetrigger=propertychanged}"
       horizontalalignment="left" verticalalignment="center" fontsize="15" width="450" height="32" />
 
    <button grid.row="0" grid.column="2" width="70" height="25" margin="0,0,10,0"
      horizontalalignment="left" verticalalignment="center" content="check" click="websitenamecheck_click"/>
    <button grid.row="1" grid.column="2" width="70" height="25" margin="0,0,10,0"
      horizontalalignment="left" verticalalignment="center" content="check" click="websiteidcheck_click"/>
    <button grid.row="2" grid.column="2" width="70" height="25" margin="0,0,10,0"
      horizontalalignment="left" verticalalignment="center" content="browse" click="pathbrowse_click"/>
    <button grid.row="3" grid.column="2" width="70" height="25" margin="0,0,10,0"
      horizontalalignment="left" verticalalignment="center" content="check" click="websiteportcheck_click"/>
    <button grid.row="4" grid.column="2" width="70" height="25" margin="0,0,10,0"
      horizontalalignment="left" verticalalignment="center" content="check" click="poolnamecheck_click"/>
    </grid>
  </groupbox>
  <stackpanel grid.row="2" orientation="horizontal" horizontalalignment="right" verticalalignment="center" margin="10">
    <button width="70" height="25" content="ok" click="deploy_click"/>
    <button width="70" height="25" content="cancel" margin="10,0,0,0" click="close_click"/>
  </stackpanel>
  </grid>
</window>
view的后台文件:
using system.windows;
using system.windows.controls;
using system.windows.interactivity;
 
namespace autowebtool
{
  /// <summary>
  /// mainwindow.xaml 的交互逻辑
  /// </summary>
  public partial class mainwindow : window
  {
  private autogenerationvm _vm;
 
  public mainwindow()
  {
    initializecomponent();
    datacontext = new autogenerationvm();
    _vm = datacontext as autogenerationvm;
  }
 
  private bool sqlpath;
  private void filepathbrowse_click(object sender, routedeventargs e)
  {
    sqlpath = _vm.getsqlfilepath();
  }
 
 
  private void websitenamecheck_click(object sender, routedeventargs e)
  {
    var isinuse = _vm.checknameandid();
    if (isinuse)
    {
    messagebox.show("1.this name is empty \r\n2.this name is in use,please change name!");
    }
    else
    {
    messagebox.show("no problem!");
    }
  }
 
  private void websiteidcheck_click(object sender, routedeventargs e)
  {
    var isinuse = _vm.checknameandid();
    if (isinuse)
    {
    messagebox.show("1.this id is empty \r\n2.this id is in use,please change id!");
    }
    else
    {
    messagebox.show("no problem!");
    }
  }
 
  private bool physicalpath;
  private void pathbrowse_click(object sender, routedeventargs e)
  {
    physicalpath = _vm.getfolderpath();
  }
  private void websiteportcheck_click(object sender, routedeventargs e)
  {
    var isinuse = _vm.checkwebport();
    if (isinuse)
    {
    messagebox.show("1.this port is empty \r\n2.this port is in use,please change port!");
    }
    else
    {
    messagebox.show("no problem!");
    }
  }
  private void poolnamecheck_click(object sender, routedeventargs e)
  {
    var isinuse = _vm.ckeckpoolname();
    if (isinuse)
    {
    messagebox.show("1.this pool name is empty \r\n2.this name is in use,please change name!");
    }
    else
    {
    messagebox.show("no problem!");
    }
  }
 
  private void deploy_click(object sender, routedeventargs e)
  {
    var databaseserveraddresschecked = string.isnullorempty(_vm.serveraddress);
    var databaseuserchecked = string.isnullorempty(_vm.user);
    var databasepasswordchecked = string.isnullorempty(_vm.password);
    var databasescriptchecked = sqlpath;
    var databasecondition = !databaseserveraddresschecked && !databaseuserchecked && !databasepasswordchecked && !databasescriptchecked;
 
    var websitenameandidchecked = _vm.checknameandid();
    var websiteportchecked = _vm.checkwebport();
    var applicationpoolnamechecked = _vm.ckeckpoolname();
    var websitecondition = !websitenameandidchecked && !physicalpath && !websiteportchecked && !applicationpoolnamechecked;
 
    if (databasecondition&& websitecondition)
    {
    _vm.execute();
    }
    else {
    messagebox.show("please check your input!");
    }
  }
 
  private void close_click(object sender, routedeventargs e)
  {
    close();
  }
  }
 
  public static class passwordboxhelper
  {
  public static readonly dependencyproperty passwordproperty =
    dependencyproperty.registerattached("password",
    typeof(string), typeof(passwordboxhelper),
    new frameworkpropertymetadata(string.empty, onpasswordpropertychanged));
 
  private static void onpasswordpropertychanged(dependencyobject sender, dependencypropertychangedeventargs e)
  {
    var passwordbox = sender as passwordbox;
 
    string password = (string)e.newvalue;
 
    if (passwordbox != null && passwordbox.password != password)
    {
    passwordbox.password = password;
    }
  }
 
  public static string getpassword(dependencyobject dp)
  {
    return (string)dp.getvalue(passwordproperty);
  }
 
  public static void setpassword(dependencyobject dp, string value)
  {
    dp.setvalue(passwordproperty, value);
  }
  }
 
  public class passwordboxbehavior : behavior<passwordbox>
  {
  protected override void onattached()
  {
    base.onattached();
 
    associatedobject.passwordchanged += onpasswordchanged;
  }
 
  private static void onpasswordchanged(object sender, routedeventargs e)
  {
    var passwordbox = sender as passwordbox;
 
    string password = passwordboxhelper.getpassword(passwordbox);
 
    if (passwordbox != null && passwordbox.password != password)
    {
    passwordboxhelper.setpassword(passwordbox, passwordbox.password);
    }
  }
 
  protected override void ondetaching()
  {
    base.ondetaching();
 
    associatedobject.passwordchanged -= onpasswordchanged;
  }
  }
}
viewmodel:
using system;
using system.directoryservices;
using system.componentmodel;
using system.linq;
using system.net;
using system.net.networkinformation;
using microsoft.web.administration;
using system.windows.forms;
using system.diagnostics;
using system.data.sqlclient;
using system.io;
 
namespace autowebtool
{
  public class autogenerationvm : inotifypropertychanged
  {
 
  public autogenerationvm()
  {
    _physicalpath = appdomain.currentdomain.basedirectory;
  }
 
  //database serveraddress
  private string _serveraddress = string.empty;
 
  public string serveraddress
  {
    get { return _serveraddress; }
    set
    {
    if (_serveraddress != value)
    {
      _serveraddress = value;
      notifypropertychanged("serveraddress");
    }
    }
  }
 
 
  //database user
  private string _user = string.empty;
 
  public string user
  {
    get { return _user; }
    set
    {
    if (_user != value)
    {
      _user = value;
      notifypropertychanged("user");
    }
    }
  }
 
 
  //database password
  private string _password = string.empty;
 
  public string password
  {
    get { return _password; }
    set
    {
    if (_password != value)
    {
      _password = value;
      notifypropertychanged("password");
    }
    }
  }
 
 
  //database sqlpath
  private string _sqlpath = string.empty;
 
  public string sqlpath
  {
    get { return _sqlpath; }
    set
    {
    if (_sqlpath != value)
    {
      _sqlpath = value;
      notifypropertychanged("sqlpath");
    }
    }
  }
 
 
  public bool getsqlfilepath() {
 
    var openfiledialog = new openfiledialog();
    openfiledialog.filter = "数据库脚本文件|*.sql";
    if (openfiledialog.showdialog() == dialogresult.ok)
    {
    sqlpath = openfiledialog.filename;
    }
    return false;
  }
 
 
  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  //website name
  private string _websitename = string.empty;
 
  public string websitename
  {
    get { return _websitename; }
    set
    {
    if (_websitename != value)
    {
      _websitename = value;
      notifypropertychanged("websitename");
    }
    }
  }
 
 
  //website id
  private string _websiteid = string.empty;
 
  public string websiteid
  {
    get { return _websiteid; }
    set
    {
    if (_websiteid != value)
    {
      _websiteid = value;
      notifypropertychanged("websiteid");
    }
    }
  }
 
 
  /// <summary>
  /// check website name and id
  /// </summary>
  /// <returns></returns>
  public bool checknameandid()
  {
    if (string.isnullorempty(websitename) || string.isnullorempty(websiteid)) return true;
 
    directoryentry rootentry = new directoryentry("iis://localhost/w3svc");
    foreach (directoryentry entry in rootentry.children)
    {
    if (entry.schemaclassname.equals("iiswebserver", stringcomparison.ordinalignorecase))
    {
      if (websiteid == entry.name) {
      return true;
      }
      if (entry.properties["servercomment"].value.tostring() == websitename)
      {
      return true;
      }
    }
    }
    return false;
  }
 
 
  //physical path
  private string _physicalpath = string.empty;
 
  public string physicalpath
  {
    get { return _physicalpath; }
    set
    {
    if (_physicalpath != value)
    {
      _physicalpath = value;
      notifypropertychanged("physicalpath");
    }
    }
  }
 
  /// <summary>
  /// get path for website
  /// </summary>
  public bool getfolderpath()
  {
    if (string.isnullorempty(physicalpath)) return true;
    var openfolderdialog = new folderbrowserdialog();
    if (openfolderdialog.showdialog() == dialogresult.ok)
    {
    physicalpath = openfolderdialog.selectedpath;
    }
    return false;
  }
 
  //website port
  private string _websiteport = string.empty;
 
  public string websiteport
  {
    get { return _websiteport; }
    set
    {
    if (_websiteport != value)
    {
      _websiteport = value;
      notifypropertychanged("websiteport");
    }
    }
  }
 
 
  /// <summary>
  /// check website port
  /// </summary>
  /// <returns></returns>
  public bool checkwebport()
  {
    try
    {
    ipglobalproperties ipproperties = ipglobalproperties.getipglobalproperties();
    ipendpoint[] ipendpoints = ipproperties.getactivetcplisteners();
 
    foreach (ipendpoint endpoint in ipendpoints)
    {
      if (endpoint.port == convert.toint32(websiteport))
      {
      return true;
      }
    }
    return false;
 
    }
    catch {
 
    return true;
    }    
  }
 
 
  //pool name
  private string _poolname = string.empty;
 
  public string poolname
  {
    get { return _poolname; }
    set
    {
    if (_poolname != value)
    {
      _poolname = value;
      notifypropertychanged("poolname");
    }
    }
  }
 
 
  /// <summary>
  /// check application pool name
  /// </summary>
  /// <returns></returns>
  public bool ckeckpoolname()
  {
    if (string.isnullorempty(poolname)) return true;
    var manager = new servermanager();
    var list = manager.applicationpools;
    var matcheditem = list.firstordefault(x => x.name == poolname);
    if (matcheditem != null)
    return true;
    return false;
  }
 
 
  /// <summary>
  /// execute script
  /// </summary>
  public void execute()
  {
    //deploy database
    var tmpconn = new sqlconnection();
    tmpconn.connectionstring = "server = " + serveraddress +"; database = master; user id = " + user+ "; pwd = " + password+ ";";
    var scriptfile = new fileinfo(sqlpath);
    var sqlcreatedbquery = scriptfile.opentext().readtoend();
    sqlcommand mycommand = new sqlcommand(sqlcreatedbquery, tmpconn);
    try
    {
    tmpconn.open();
    mycommand.executenonquery();
    messagebox.show("database has been created successfully!","create database", messageboxbuttons.ok,messageboxicon.information);
    }
    catch (exception ex)
    {
    messagebox.show(ex.tostring(), "create database", messageboxbuttons.ok, messageboxicon.information);
    return;
    }
    finally
    {
    tmpconn.close();
    
    }
 
 
    try
    {
    //deploy website and application pool
    var script = "net start w3svc " +
         "& cd c:/windows/system32/inetsrv " +
         "& appcmd add site /name:" + websitename + " /id:" + websiteid +
         " /physicalpath:" + physicalpath + " /bindings:http/*:" + websiteport + ":" + websitename +
         " & appcmd add apppool /name:" + poolname + " /managedruntimeversion:v4.0 /managedpipelinemode:integrated" +
         " & appcmd set site /site.name:" + websitename + " /[path='/'].applicationpool:" + poolname;
 
    processstartinfo startinfo = new processstartinfo();
    startinfo.workingdirectory = @"c:\windows\system32";
    startinfo.filename = @"c:\windows\system32\cmd.exe";
    startinfo.redirectstandardinput = true;
    startinfo.redirectstandardoutput = true;
    startinfo.redirectstandarderror = true;
    startinfo.useshellexecute = false;
    startinfo.verb = "runas";
 
    process process = new process();
    process.startinfo = startinfo;
    process.start();
    process.standardinput.writeline(script);
    process.standardinput.writeline("&exit");
    process.standardinput.flush();
    process.standardinput.close();
    process.waitforexit();
 
    messagebox.show("iis website and application pool deployed successfully!", "create website and application pool", messageboxbuttons.ok, messageboxicon.information);
    }
    catch (exception ex)
    {
    messagebox.show(ex.tostring(), "exception", messageboxbuttons.ok, messageboxicon.information);
    }
  }
 
  public event propertychangedeventhandler propertychanged;
  private void notifypropertychanged(string name)
  {
    propertychanged?.invoke(this, new propertychangedeventargs(name));
  }
  }
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家
原文链接:https://www.cnblogs.com/lovecsharp094/archive/2018/03/21/8618139.html

关注下面的标签,发现更多相似文章