C#部署数据库及IIS站点

2019-12-30 19:33:14于海丽

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:WindowsSystem32";
        startInfo.FileName = @"C:WindowsSystem32cmd.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));
    }
  }
}