澳门新葡萄京官网首页[转]在打包的时候,创建应用程序池,并自动将程序assign到新创建的池中(MSI制作)

在 ASP.NET(2.0 及以上版本)中,我们可以使用 System.DirectoryServices
来管理 IIS。

 我在在部署ASP.net应用程序的时候,在IIS中都是创建在默认的应用池当中.我们能否在部署的时候创建自己的应用池呢?
本文就带你一起创建自己的应用池!

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.DirectoryServices;
using System.Reflection;
using System.Text.RegularExpressions;

System.DirectoryServices 可以获取和设置 IIS metabase 的 String and DWORD
属性,并且也能调用大多数方法。

  1 using System;
  2 using System.IO;
  3 using System.DirectoryServices;
  4 using System.Reflection;
  5 using System.Runtime.InteropServices;
  6 using System.Collections;
  7 
  8 namespace System_DirectoryServices_DirectoryEntry_ConfigIIS
  9 {
 10   class Program
 11   {
 12     static void Main(string[] args)
 13     {
 14 
 15 
 16 
 17 CreateAppPool(“IIS://Localhost/W3SVC/AppPools”, “MyAppPool”);
 18 
 19 
 20 
 21 CreateVDir(“IIS://Localhost/W3SVC/1/Root”, “MyVDir”, “D:\Inetpub\Wwwroot”);
 22 
 23 
 24 
 25 AssignVDirToAppPool(“IIS://Localhost/W3SVC/1/Root/MyVDir”, “MyAppPool”);
 26 
 27 
 28 
 29 }
 30 
 31 
 32 
 33 static void CreateAppPool(string metabasePath, string appPoolName)
 34 {
 35   //  metabasePath is of the form “IIS://<servername>/W3SVC/AppPools”
 36   //    for example “IIS://localhost/W3SVC/AppPools” 
 37   //  appPoolName is of the form “<name>”, for example, “MyAppPool”
 38   Console.WriteLine(“nCreating application pool named {0}/{1}:”, metabasePath, appPoolName);
 39 
 40   try
 41   {
 42     if (metabasePath.EndsWith(“/W3SVC/AppPools”))
 43     {
 44       DirectoryEntry newpool;
 45       DirectoryEntry apppools = new DirectoryEntry(metabasePath);
 46       newpool = apppools.Children.Add(appPoolName, “IIsApplicationPool”);
 47       newpool.CommitChanges();
 48       Console.WriteLine(” Done.”);
 49     }
 50     else
 51       Console.WriteLine(” Failed in CreateAppPool; application pools can only be created in the */W3SVC/AppPools node.”);
 52   }
 53   catch (Exception ex)
 54   {
 55     Console.WriteLine(“Failed in CreateAppPool with the following exception: n{0}”, ex.Message);
 56   }
 57 }
 58 
 59 
 60 
 61 static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
 62 {
 63   //  metabasePath is of the form “IIS://<servername>/<service>/<siteID>/Root[/<vdir>]”
 64   //    for example “IIS://localhost/W3SVC/1/Root” 
 65   //  vDirName is of the form “<name>”, for example, “MyNewVDir”
 66   //  physicalPath is of the form “<drive>:<path>”, for example, “C:InetpubWwwroot”
 67   Console.WriteLine(“nCreating virtual directory {0}/{1}, mapping the Root application to {2}:”,
 68       metabasePath, vDirName, physicalPath);
 69 
 70   try
 71   {
 72     DirectoryEntry site = new DirectoryEntry(metabasePath);
 73     string className = site.SchemaClassName.ToString();
 74     if ((className.EndsWith(“Server”)) || (className.EndsWith(“VirtualDir”)))
 75     {
 76       DirectoryEntries vdirs = site.Children;
 77       DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace(“Service”, “VirtualDir”)));
 78       newVDir.Properties[“Path”][0] = physicalPath;
 79       newVDir.Properties[“AccessScript”][0] = true;
 80       // These properties are necessary for an application to be created.
 81       newVDir.Properties[“AppFriendlyName”][0] = vDirName;
 82       newVDir.Properties[澳门新葡萄京官网首页 ,”AppIsolated”][0] = “1”;
 83       newVDir.Properties[“AppRoot”][0] = “/LM” + metabasePath.Substring(metabasePath.IndexOf(“/”, (“IIS://”.Length)));
 84 
 85       newVDir.CommitChanges();
 86 
 87       Console.WriteLine(” Done.”);
 88     }
 89     else
 90       Console.WriteLine(” Failed. A virtual directory can only be created in a site or virtual directory node.”);
 91   }
 92   catch (Exception ex)
 93   {
 94     Console.WriteLine(“Failed in CreateVDir with the following exception: n{0}”, ex.Message);
 95   }
 96 }
 97 
 98 
 99 
100 static void AssignVDirToAppPool(string metabasePath, string appPoolName)
101 {
102   //  metabasePath is of the form “IIS://<servername>/W3SVC/<siteID>/Root[/<vDir>]”
103   //    for example “IIS://localhost/W3SVC/1/Root/MyVDir” 
104   //  appPoolName is of the form “<name>”, for example, “MyAppPool”
105   Console.WriteLine(“nAssigning application {0} to the application pool named {1}:”, metabasePath, appPoolName);
106 
107   try
108   {
109     DirectoryEntry vDir = new DirectoryEntry(metabasePath);
110     string className = vDir.SchemaClassName.ToString();
111     if (className.EndsWith(“VirtualDir”))
112     {
113       object[] param = { 0, appPoolName, true };
114       vDir.Invoke(“AppCreate3”, param);
115       vDir.Properties[“AppIsolated”][0] = “2”;
116       Console.WriteLine(” Done.”);
117     }
118     else
119       Console.WriteLine(” Failed in AssignVDirToAppPool; only virtual directories can be assigned to application pools”);
120   }
121   catch (Exception ex)
122   {
123     Console.WriteLine(“Failed in AssignVDirToAppPool with the following exception: n{0}”, ex.Message);
124   }
125 }
126 
127 
128 
129   }
130 }
131   
132  
133 

//添加站点代码

前提是您的操作系统应该是 Windows XP Professional 带 SP2,或 Windows
Server 2003 带 SP1 或更新版本的操作系统。否则您可能会得到类似“The
directory cannot report the number of properties”的错误。

private void button2_Click(object sender, System.EventArgs e)
  {
   
   
   string newServerComment=textBox1.Text;   
   string newServerIP=textBox2.Text;
   string newServerPort=textBox3.Text;   
   string newServerPath=textBox4.Text;
   string newServerHeader=textBox5.Text;   
   //NewWebSiteInfo siteInfo=new
NewWebSiteInfo(hostIP,portNum,descOfWebSite,commentOfWebSite,webPath);
   NewWebSiteInfo siteInfo=new
NewWebSiteInfo(newServerIP,newServerPort,newServerHeader,newServerComment,newServerPath);
   string entPath = “IIS://localhost/w3svc”;
   DirectoryEntry rootEntry = new DirectoryEntry(entPath);

不过开始之前,您应该在网站解决方案的属性页上 References
中引入 System.DirectoryServices。添加后,web.config
中应该有类似如下的内容:

   string newSiteNum = GetNewWebSiteID();

<configuration>
  <system.web>
    <compilation debug=”false”>
      <assemblies>
        <add
assembly=”System.DirectoryServices, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=B03F5F7F11D50A3A”/>

   DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum,
“IIsWebServer”);

另外还请您注意一下,您运行 ASP.NET
的帐户要有足够的权限来操作 IIS。

   newSiteEntry.CommitChanges();

关于用 System.DirectoryServices 来管理 IIS
的所有内容请参见 MSDN 上的 http://msdn.microsoft.com/en-us/library/ms525791.aspx。

   newSiteEntry.Properties[“ServerBindings”].Value =
siteInfo.BindString;

另外我摘录了一点示例,是关于如何创建站点、设置端口、创建虚拟目录,虽然是
Console 环境中的,但只需要作些很简单的修改,就可以应用到 ASP.NET 中。

   newSiteEntry.Properties[“ServerComment”].Value =
siteInfo.CommentOfWebSite;

using System;
using System.IO;
using System.DirectoryServices;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;

   newSiteEntry.CommitChanges();

namespace
System_DirectoryServices_DirectoryEntry_ConfigIIS
{
  class Program
  {
    static void Main(string[] args)
    {

   DirectoryEntry vdEntry = newSiteEntry.Children.Add(“root”,
“IIsWebVirtualDir”);

   vdEntry.CommitChanges();

CreateSite(“IIS://Localhost/W3SVC”, “555”,
“MySite”, “D:\Inetpub\Wwwroot”);

   vdEntry.Properties[“Path”].Value = siteInfo.WebPath;

   vdEntry.CommitChanges();
   
    

SetSingleProperty(“IIS://Localhost/W3SVC/555”, “ServerBindings”, “:8080:”);

   MessageBox.Show(“站点”+siteInfo.CommentOfWebSite+”创建完成”);
   

  }

CreateVDir(“IIS://Localhost/W3SVC/1/Root”,
“MyVDir”, “D:\Inetpub\Wwwroot”);

//IIS站点查询代码
  ////
  /// Get and return a new website ID of specify host
  ///
  /// the smallest new website ID of the host
  public string GetNewWebSiteID()
  {
   ArrayList idList = new ArrayList();
   string tmpStr;

   string entryPath = “IIS://localhost/W3SVC”;
   DirectoryEntry entry = GetDirectoryEntry(entryPath);
  
   foreach (DirectoryEntry child in entry.Children)
   {
    if (child.SchemaClassName == “IIsWebServer”)
    {
     tmpStr = child.Name.ToString();
     idList.Add(Convert.ToInt32(tmpStr));
    }
   }

}

   idList.Sort();

   int i = 1;
   foreach (int id in idList)
   {
    if (i == id)
    {
     i++;
    }
   }

static void CreateSite(string metabasePath, string siteID, string siteName, string physicalPath)
{
  //  metabasePath is of the form
“IIS://<servername>/<service>”
  //    for example “IIS://localhost/W3SVC”

   return i.ToString();
  }

  //  siteID is of the form “<number>”,
for example “555”
  //  siteName is of the form “<name>”,
for example, “My New Site”
  //  physicalPath is of the form
“<drive>:<path>”, for example,
“C:InetpubWwwroot”
  Console.WriteLine(“nCreating site {0}/{1}, mapping the Root
application to {2}:”,
      metabasePath, siteID, physicalPath);

//删除站点代码

  try
  {
    DirectoryEntry service = new
DirectoryEntry(metabasePath);
    string className =
service.SchemaClassName.ToString();
    if (className.EndsWith(“Service”))
    {
      DirectoryEntries sites = service.Children;
      DirectoryEntry newSite = sites.Add(siteID,
(className.Replace(“Service”, “Server”)));
      newSite.Properties[“ServerComment”][0] = siteName;
      newSite.CommitChanges();

private void button3_Click(object sender, System.EventArgs e)
  {
   string newServerComment=textBox1.Text;   
   string newServerIP=textBox2.Text;
   string newServerPort=textBox3.Text;   
   string newServerPath=textBox4.Text;
   string newServerHeader=textBox5.Text;
   string newServerHost=textBox6.Text;

      DirectoryEntry newRoot;
      newRoot = newSite.Children.Add(“Root”, “IIsWebVirtualDir”);
      newRoot.Properties[“Path”][0] = physicalPath;
      newRoot.Properties[“AccessScript”][0] = true;
      newRoot.CommitChanges();

   string siteNum = GetWebSiteNum(newServerComment);
   string rootPath = “IIS://localhost/w3svc”;
   string siteEntPath =rootPath+”/”+siteNum; 
   DirectoryEntry rootEntry = GetDirectoryEntry(rootPath);
   DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
   rootEntry.Children.Remove(siteEntry);
   rootEntry.CommitChanges();
   MessageBox.Show(“站点 “+newServerComment+” 删除完毕”);
  }

      Console.WriteLine(” Done. Your site will not start until you set the
ServerBindings or SecureBindings property.”);
    }
    else
      Console.WriteLine(” Failed. A site can only be created in a service
node.”);
  }
  catch (Exception ex)
  {
    Console.WriteLine(“Failed in CreateSite with the following
exception: n{0}”, ex.Message);
  }
}

  //根据站点名称获取站点标识符
  #region 获取一个网站编号的方法
  public string GetWebSiteNum(string siteName)

  {

static void SetSingleProperty(string metabasePath, string propertyName, object newValue)
{
  //  metabasePath is of the form
“IIS://<servername>/<path>”
  //    for example “IIS://localhost/W3SVC/1”

   Regex regex = new Regex(siteName);
   string tmpStr;
   string entPath = “IIS://localhost/w3svc”;
   DirectoryEntry ent =new DirectoryEntry(entPath); 

  //  propertyName is of the form
“<propertyName>”, for example “ServerBindings”
  //  value is of the form
“<intStringOrBool>”, for example, “:80:”
  Console.WriteLine(“nSetting single property at {0}/{1} to {2}
({3}):”,
      metabasePath, propertyName, newValue,
newValue.GetType().ToString());

   foreach(DirectoryEntry child in ent.Children)

  try
  {
      DirectoryEntry path = new
DirectoryEntry(metabasePath);
      PropertyValueCollection propValues =
path.Properties[propertyName];
      string oldType =
propValues.Value.GetType().ToString();
      string newType =
newValue.GetType().ToString();
      Console.WriteLine(” Old value of {0} is {1} ({2})”,
propertyName, propValues.Value, oldType);
      if (newType == oldType)
      {
          path.Properties[propertyName][0] = newValue;
          path.CommitChanges();
          Console.WriteLine(“Done”);
      }
      else
          Console.WriteLine(” Failed in SetSingleProperty; type of new value
does not match property”);
  }
  catch (Exception ex)
  {
      if (“HRESULT
0x80005006” == ex.Message)
          Console.WriteLine(” Property {0} does not exist at
{1}”, propertyName, metabasePath);
      else
          Console.WriteLine(“Failed in SetSingleProperty with the following
exception: n{0}”, ex.Message);
  }
}

   {
    if(child.SchemaClassName == “IIsWebServer”)
    {
     if(child.Properties[“ServerBindings”].Value != null)
     {
      tmpStr = child.Properties[“ServerBindings”].Value.ToString();
      if(regex.Match(tmpStr).Success)
      {
       return child.Name;
      }
     }

     if(child.Properties[“ServerComment”].Value != null)

static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
  //  metabasePath is of the form
“IIS://<servername>/<service>/<siteID>/Root[/<vdir>]”
  //    for example
“IIS://localhost/W3SVC/1/Root”
  //  vDirName is of the form “<name>”,
for example, “MyNewVDir”
  //  physicalPath is of the form
“<drive>:<path>”, for example,
“C:InetpubWwwroot”
  Console.WriteLine(“nCreating virtual directory {0}/{1}, mapping
the Root application to {2}:”,
      metabasePath, vDirName, physicalPath);

     {
      tmpStr = child.Properties[“ServerComment”].Value.ToString();
      if(regex.Match(tmpStr).Success)
      {
       return child.Name;
      }
     }
    }
   }
   return “”;
   
  }
  #endregion

  try
  {
    DirectoryEntry site = new
DirectoryEntry(metabasePath);
    string className =
site.SchemaClassName.ToString();
    if ((className.EndsWith(“Server”)) ||
(className.EndsWith(“VirtualDir”)))
    {
      DirectoryEntries vdirs = site.Children;
      DirectoryEntry newVDir = vdirs.Add(vDirName,
(className.Replace(“Service”, “VirtualDir”)));
      newVDir.Properties[“Path”][0] = physicalPath;
      newVDir.Properties[“AccessScript”][0] = true;
      // These properties are necessary for
an application to be created.
      newVDir.Properties[“AppFriendlyName”][0] =
vDirName;
      newVDir.Properties[“AppIsolated”][0] = “1”;
      newVDir.Properties[“AppRoot”][0] = “/LM” +
metabasePath.Substring(metabasePath.IndexOf(“/”,
(“IIS://”.Length)));

 

      newVDir.CommitChanges();

#region 新IIS站点信息结构体

      Console.WriteLine(” Done.”);
    }
    else
      Console.WriteLine(” Failed. A virtual directory can only be created
in a site or virtual directory node.”);
  }
  catch (Exception ex)
  {
    Console.WriteLine(“Failed in CreateVDir with the following
exception: n{0}”, ex.Message);
  }
}

  public struct NewWebSiteInfo
  {
   private string hostIP;   // The Hosts IP Address

   private string portNum;   // The New Web Sites Port.generally is “80”

  }
}

   private string descOfWebSite; //
网站表示。一般为网站的网站名。例如”www.dns.com.cn”

 

   private string commentOfWebSite;// 网站注释。一般也为网站的网站名。

   private string webPath;   // 网站的主目录。例如”e:tmp”

   public NewWebSiteInfo(string hostIP, string portNum, string
descOfWebSite, string commentOfWebSite, string webPath)

   {

    this.hostIP = hostIP;

    this.portNum = portNum;

    this.descOfWebSite = descOfWebSite;

    this.commentOfWebSite = commentOfWebSite;

    this.webPath = webPath;

   }

   public string BindString

   {

    get
    {
     return String.Format(“{0}:{1}:{2}”, hostIP, portNum,
descOfWebSite);

    }

   }

   public string CommentOfWebSite  {get{return commentOfWebSite;}}

   public string WebPath  {get{return webPath;}}

  }

  #endregion

<> <>

发表评论

电子邮件地址不会被公开。 必填项已用*标注