C#部署数据库及IIS站点

时间:2021-09-10 09:26:25

一、前言

最近忙里偷闲,做了一个部署数据库及iis网站站点的wpf应用程序工具。 

二、内容

此工具的目的是:

  • 根据.sql文件在本机上部署数据库
  • 在本机部署iis站点,包括新建站点,新建应用程序池。只新建而不会对本机上原有的程序池或站点做修改操作

最终样式:(check按钮的作用是防止与本机已有的站点或程序池有冲突)

C#部署数据库及IIS站点

view:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<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的后台文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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));
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/lovecsharp094/archive/2018/03/21/8618139.html