C#基礎-代碼部署資料庫及IIS站點

来源:https://www.cnblogs.com/lovecsharp094/archive/2018/03/21/8618139.html
-Advertisement-
Play Games

一、前言 最近忙裡偷閑,做了一個部署資料庫及IIS網站站點的WPF應用程式工具。 二、內容 此工具的目的是: 最終樣式:(Check按鈕的作用是防止與本機已有的站點或程式池有衝突) View: View的後臺文件: ViewModel: ...


一、前言

       最近忙裡偷閑,做了一個部署資料庫及IIS網站站點的WPF應用程式工具。

 

二、內容

       此工具的目的是:

  1. 根據.sql文件在本機上部署資料庫
  2. 在本機部署IIS站點,包括新建站點,新建應用程式池。只新建而不會對本機上原有的程式池或站點做修改操作

最終樣式:(Check按鈕的作用是防止與本機已有的站點或程式池有衝突)

 

 

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	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 簡歷篇 請自我介紹 請介紹項目 基礎篇 基本功 面向對象的特征 final, finally, finalize 的區別 int 和 Integer 有什麼區別 重載和重寫的區別 抽象類和介面有什麼區別 說說反射的用途及實現 說說自定義註解的場景及實現 HTTP 請求的 GET 與 POST 方式的 ...
  • ~~媽媽,我終於會寫LCT了!~~ LCT太神奇了,它和Splay能完美結合。在$O(nlogn)$的時間內解決動態樹問題。 BZOJ2049 [Sdoi2008]Cave 洞穴勘測 丟板子,懶得解釋。用維護一下聯通塊就行了,因為數據水,並查集也可以水過。 AC代碼: c++ include inc ...
  • 1 package java.util; 2 3 import sun.misc.SharedSecrets; 4 5 import java.util.function.Consumer; 6 import java.util.function.Predicate; 7 import java.u... ...
  • 搜onlyoffice document server的github上的issue,會得到這2個地址https://github.com/ONLYOFFICE/DocumentServer/issues/67https://github.com/ONLYOFFICE/DocumentServer/i ...
  • 為什麼我們可以在Startup這個 “孤零零的” 類中配置依賴註入和管道? 它是什麼時候被實例化並且調用的? 參數中的IServiceCollection services是怎麼來的? 處理管道是怎麼構建起來的? 啟動過程中,系統“默默的”做了哪些準備工作? 上一篇文章講了ASP.NET Core中 ...
  • 由於自身專業水平的欠佳,我對於XAML控制項的學習並不深刻,只在簡單瞭解過後產生了一二想法,也許十分荒謬,就減省地談談。以下五種控制項,是我在學習後,並不十分看好或有所疑慮的。 在瀏覽XAML Controls Gallery上各種控制項的簡單介紹時,這個控制項引起我註意,它通過坐標軸控制每個內容的分佈,是 ...
  • interface 學習 使用interface定義介面, 介面不儲存數據,所以沒有欄位,但是可以有屬性, 實現介面的類必須包括介面的所有方法和屬性,否則無法編譯。 公共介面中的所有方法都會自動成為公共方法,因為介面就是用來定義實現該介面的類應該具有的公共方法和屬性。 不能實例化介面,不過可以引用接 ...
  • 顧名思義,HTML輔助方法(HTML Helper)就是用來輔助產生HTML之用,在開發View的時候一定會面對許多HTML標簽,處理這些HTML的工作非常繁瑣,為了降低View的複雜度,可以使用HTML輔助方法幫助你產生一些HTML標簽或內容,因這些HTML標簽都有固定標準的寫法,所以將其包裝成H ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...