次の方法で共有


Programmatic management of IIS

Creation of Application Pool on IIS

Note: Add Microsoft.Web.Management.dll as reference(This can be found Windows/system32/inetsrv folder)

 1)      Create a class structure to take input parameters for Creation of Application Pool

  /// <summary>
 /// This class just provides parameters for application pool creation.
 /// </summary>
 public class ApplicationPoolParams
 {
 public ApplicationPoolParams(string appPoolName,string metabasePath, uint queueLength,string managedRuntimeVersion,ManagedPipelineMode managedPipeLineMode,
 ProcessModelAppPool processModel, RecyclingAppPool recycleAppPool,CpuAppPool cpuAppPool)
 {
 Name = appPoolName;
 MetabasePath = metabasePath;
 QueueLength = queueLength;
 ManagedRuntimeVersion = managedRuntimeVersion;
 PipelineMode = managedPipeLineMode;
 ProcessModelData = processModel;
 RecycleAppPoolData = recycleAppPool;
 CpuData = cpuAppPool;
 }
 public string Name { get; set; }
 public string MetabasePath { get; set; }
 public uint QueueLength { get; set; }
 public string ManagedRuntimeVersion { get; set; }
 public ManagedPipelineMode PipelineMode { get; set; }
 public ProcessModelAppPool ProcessModelData { get; set;}
 public RecyclingAppPool RecycleAppPoolData { get; set; }
 public CpuAppPool CpuData { get; set; }
 
 }
 public class ProcessModelAppPool
 {
 public ProcessModelAppPool(TimeSpan idleTimeOut,uint maxProcesses)
 {
 IdleTimeout = idleTimeOut;
 MaxProcesses = maxProcesses;
 
 }
 public TimeSpan IdleTimeout { get; set; }
 public uint MaxProcesses { get; set; }
 }
 public class RecyclingAppPool
 {
 public RecyclingAppPool(bool isOverlappingRotation,bool isRotationOnConfigChange, PeriodicRestartAppPool periodic)
 {
 DisallowOverlappingRotation = isOverlappingRotation;
 DisallowRotationOnConfigChange = isRotationOnConfigChange;
 PeriodicRestartData = periodic;
 }
 
 public bool DisallowOverlappingRotation { get; set; }
 public bool DisallowRotationOnConfigChange { get; set; }
 public PeriodicRestartAppPool PeriodicRestartData { get; set; }
 
 }
 public class PeriodicRestartAppPool
 {
 public PeriodicRestartAppPool(int privatememory,int memory,int requests,TimeSpan timespan)
 {
 PrivateMemory = privatememory;
 Memory = memory;
 Requests = requests;
 Time = timespan;
 }
 public int PrivateMemory { get; set; }
 public int Memory { get; set; }
 public int Requests { get; set; }
 public TimeSpan Time { get; set; }
 
 }
 public class CpuAppPool
 {
 public CpuAppPool(int limit,CpuActions action)
 {
 Limit = limit;
 Action = action;
 }
 public int Limit { get; set; }
 public CpuActions Action { get; set; }
 }
 public enum CpuActions
 {
 NoAction,
 KillW3wp
 }
 public static class VersionName
 {
 public static string Version2 = "v2.0";
 public static string Version4 = "v4.0";
 public static string UnManaged = "No Managed Code";
 }

2)      Create Application Programmatically using the parameters set in the above class

 /// <summary>
 /// Function to create Application Pool.
 /// </summary>
 /// <param name="appPoolData">Class Object with Input application pool data</param>
 public static void CreateAppPool(ApplicationPoolParams appPoolData)
 {
 Console.WriteLine("\nCreating application pool named {0}/{1}:", appPoolData.MetabasePath, appPoolData.Name);
 try
 {
 if (appPoolData.MetabasePath.EndsWith("/W3SVC/AppPools"))
 {
 DirectoryEntry newpool;
 DirectoryEntry apppools = new DirectoryEntry(appPoolData.MetabasePath);
 using (var manager = new ServerManager())
 {
 ApplicationPool appPoolIIS = manager.ApplicationPools.FirstOrDefault<ApplicationPool>(pool => pool.Attributes["name"].Value.ToString().ToLower() == appPoolData.Name.ToLower());
 if (appPoolIIS == null)
 {
 newpool = apppools.Children.Add(appPoolData.Name, "IIsApplicationPool");
 newpool.CommitChanges();
 manager.CommitChanges();
 appPoolIIS = manager.ApplicationPools.FirstOrDefault<ApplicationPool>(pool => pool.Attributes["name"].Value.ToString().ToLower() == appPoolData.Name.ToLower());
 if(appPoolData.QueueLength > 0)
 appPoolIIS.SetAttributeValue("queueLength", appPoolData.QueueLength);
 if(!string.IsNullOrEmpty(appPoolData.ManagedRuntimeVersion))
 appPoolIIS.SetAttributeValue("managedRuntimeVersion", appPoolData.ManagedRuntimeVersion);
 if (!string.IsNullOrEmpty(appPoolData.PipelineMode.ToString()))
 appPoolIIS.SetAttributeValue("managedPipelineMode", appPoolData.PipelineMode);
 if (appPoolData.ProcessModelData != null)
 {
 appPoolIIS.ProcessModel.SetAttributeValue("idleTimeout", appPoolData.ProcessModelData.IdleTimeout);
 appPoolIIS.ProcessModel.SetAttributeValue("maxProcesses", appPoolData.ProcessModelData.MaxProcesses);
 }
 
 if (appPoolData.RecycleAppPoolData != null)
 {
 appPoolIIS.Recycling.SetAttributeValue("disallowOverlappingRotation", appPoolData.RecycleAppPoolData.DisallowOverlappingRotation);
 appPoolIIS.Recycling.SetAttributeValue("disallowRotationOnConfigChange", appPoolData.RecycleAppPoolData.DisallowRotationOnConfigChange);
 if (appPoolData.RecycleAppPoolData.PeriodicRestartData != null)
 {
 appPoolIIS.Recycling.PeriodicRestart.SetAttributeValue("memory", appPoolData.RecycleAppPoolData.PeriodicRestartData.Memory);
 appPoolIIS.Recycling.PeriodicRestart.SetAttributeValue("privateMemory", appPoolData.RecycleAppPoolData.PeriodicRestartData.PrivateMemory);
 appPoolIIS.Recycling.PeriodicRestart.SetAttributeValue("requests", appPoolData.RecycleAppPoolData.PeriodicRestartData.Requests);
 appPoolIIS.Recycling.PeriodicRestart.SetAttributeValue("time", appPoolData.RecycleAppPoolData.PeriodicRestartData.Time);
 }
 }
 if (appPoolData.CpuData != null)
 {
 appPoolIIS.Cpu.SetAttributeValue("limit", appPoolData.CpuData.Limit);
 appPoolIIS.Cpu.SetAttributeValue("action", appPoolData.CpuData.Action.ToString());
 }
 manager.CommitChanges();
 
 }
 
 }
 
 
 Console.WriteLine(" Done.");
 }
 else
 Console.WriteLine(" Failed in CreateAppPool; application pools can only be created in the */W3SVC/AppPools node.");
 }
 catch (Exception ex)
 {
 Console.WriteLine("Failed in CreateAppPool with the following exception: \n{0}", ex.Message);
 }
 }
 

 

Creation of Virtual Directory on IIS

1)      This function will take Website Url under which virtual directory/web application have to be created, Name of the virtual directory and physical path to which it must point to.

 /// <summary>
 /// Function to create web application if does not exists.
 /// </summary>
 /// <param name="websiteUrl">Root website url</param>
 /// <param name="vDirName">Name of the web application</param>
 /// <param name="physicalPath">Physical path to which the web application will point to</param>
 public static void CreateVDir(string websiteUrl, string vDirName, string physicalPath)
 {
 
 Console.WriteLine("\nCreating application {0}/{1}, mapping the Root application to {2}:",
 websiteUrl, vDirName, physicalPath);
 
 try
 {
 DirectoryEntry site = new DirectoryEntry(websiteUrl);
 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;
 newVDir.Properties["AppFriendlyName"][0] = vDirName;
 newVDir.Properties["AppIsolated"][0] = "1";
 newVDir.Properties["AppRoot"][0] = "/LM" + websiteUrl.Substring(websiteUrl.IndexOf("/", ("IIS://".Length)));
 newVDir.CommitChanges();
 
 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);
 }
 }

Assigning Application Pool to virtual directory

1)      This function will take web application/virtual Directory name and application pool name

 /// <summary>
 /// Function to assign application pool to web application created.
 /// </summary>
 /// <param name="webApplicationUrl">Web Application Url</param>
 /// <param name="appPoolName">Application pool name this web application to be assigned to</param>
 public static void AssignVDirToAppPool(string webApplicationUrl, string appPoolName)
 {
 Console.WriteLine("\nAssigning application {0} to the application pool named {1}:", webApplicationUrl, appPoolName);
 
 try
 {
 DirectoryEntry vDir = new DirectoryEntry(webApplicationUrl);
 string className = vDir.SchemaClassName.ToString();
 object[] param = { 0, appPoolName, true };
 vDir.Invoke("AppCreate3", param);
 vDir.Properties["AppIsolated"][0] = "2";
 Console.WriteLine(" Done.");
 
 }
 catch (Exception ex)
 {
 Console.WriteLine("Failed in AssignVDirToAppPool with the following exception: \n{0}", ex.Message);
 }
 }