Home > ASP.NET, IIS, c# > Creating an IIS Site through managed code (C#, .NET)

Creating an IIS Site through managed code (C#, .NET)

Another task I had in the past along with creating the DNS entries via managed code, was creating a new site in IIS. I had to nip various code from various places, but when I got done, it all worked nicely together. You will notice by the try catch block, that again, I was executing this chunk of code from a web based application. Needless to say, chances are you won’t have the permissions to do this unless you do. This code works on IIS 6.0 with Windows 2003 Server Std Edition . I’d imagine it’s more IIS specific than OS specific, but this is the only version of Windows I’ve tested it with.

public static string CreateWebSite(string NewSiteIP, string webSiteName, string pathToRoot, string DomainName)
{
int siteID = 1;
string sSiteID = “”;
try
{

CreatePhysicalDirectory(pathToRoot, webSiteName);

ManagementScope _scope = new ManagementScope(@”\\WINDOWS\root\MicrosoftIISV2″, null);
_scope.Connect();

ManagementObject oW3SVC = new ManagementObject(_scope, new ManagementPath(@”IIsWebService=’W3SVC’”), null);
DirectoryEntry root = new DirectoryEntry(”IIS://WINDOWS/W3SVC”);

#region get a good site id
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == “IIsWebServer”)
{
int ID = Convert.ToInt32(e.Name);
if (ID >= siteID)
siteID = ID + 1;
}
}
#endregion

ManagementScope mScope = null;
ManagementPath mPath = new ManagementPath();
mPath.ClassName = “ServerBinding”;
mPath.NamespacePath = “root\\MicrosoftIISv2″;
mScope = new ManagementScope(mPath);
mScope.Path.Server = “WINDOWS”;

#region Create the new Site
ManagementBaseObject[] serverBindings = new ManagementBaseObject[2];
serverBindings[0] = CreateServerBinding(DomainName, NewSiteIP, “80″);
serverBindings[1] = CreateServerBinding(”www.” + DomainName, NewSiteIP, “80″);

ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters(”CreateNewSite”);
inputParameters["ServerComment"] = ConfigurationManager.AppSettings["SitePrefix"] + webSiteName;
inputParameters["ServerBindings"] = serverBindings;
inputParameters["PathOfRootVirtualDir"] = pathToRoot + webSiteName;
inputParameters["ServerId"] = siteID;

ManagementBaseObject outParameter = null;
outParameter = oW3SVC.InvokeMethod(”CreateNewSite”, inputParameters, null);
// return is like IIsWebServer=’W3SVC/2145288186′

sSiteID = Convert.ToString(outParameter.Properties["ReturnValue"].Value).Replace(”IIsWebServer=’W3SVC/”,””).Replace(”‘”,””);

ManagementObject site = new ManagementObject(_scope,
new ManagementPath(Convert.ToString(outParameter.Properties["ReturnValue"].Value)),
null);
#endregion

#region Remap ScriptMaps
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@”root\MicrosoftIISv2″,
“SELECT * FROM IIsWebVirtualDirSetting WHERE Path = ‘” + pathToRoot.Replace(@”\”,@”\\”) + webSiteName + “‘”) ;

foreach(ManagementObject queryObj in searcher.Get())
{
if (queryObj.Properties["ScriptMaps"] != null)
{
Object[] arrScriptMaps = (Object[])(queryObj["ScriptMaps"]);
foreach (Object arrValue in arrScriptMaps)
{
foreach (PropertyData data in ((ManagementBaseObject)arrValue).Properties)
{
if(Convert.ToString(data.Value).ToLower()==@”c:\windows\microsoft.net\framework\v1.1.4322\aspnet_isapi.dll”)
if (data.Name == “ScriptProcessor”)
data.Value = @”c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll”;
}
}
queryObj.SetPropertyValue(”ScriptMaps”, arrScriptMaps);
queryObj.Put();
}
}
#endregion

ManagementPath myPath = new ManagementPath();
myPath.Path = @”IIsWebVirtualDirSetting.Name=’W3SVC/” + siteID.ToString() + “/root’”;
ManagementObject oWebVDir = new ManagementObject(_scope, myPath, null);

oWebVDir.Properties["AppFriendlyName"].Value = “mah new app”;
oWebVDir.Properties["AccessRead"].Value = true;
//oWebVDir.Properties["ServerAutoStart"].Value = true;
oWebVDir.Properties["AuthFlags"].Value = 5; // Integrated Windows Auth.
oWebVDir.Properties["AccessScript"].Value = true;
oWebVDir.Properties["AuthAnonymous"].Value = true;
oWebVDir.Properties["AppPoolId"].Value = “MyAppPoolName”;
oWebVDir.Put();

site.InvokeMethod(”Start”, null);
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message + “
”);
HttpContext.Current.Response.Write(ex.StackTrace);
HttpContext.Current.Response.Write(ex.ToString());
HttpContext.Current.Response.End();
}

return sSiteID;
}

private static void CreatePhysicalDirectory(string pathToRoot, string webSiteName)
{
if (Directory.Exists(pathToRoot + webSiteName))
throw new Exception(”Error creating new website: Customer root directory already exists at ” + pathToRoot + webSiteName);
else
{
Directory.CreateDirectory(pathToRoot + webSiteName);
//StreamWriter indexFile = new StreamWriter(pathToRoot + webSiteName + @”\index.htm”, false, System.Text.Encoding.ASCII);
//indexFile.Write(”


Welcome to  ” + webSiteName + “

”);
//indexFile.Close();
}
}

///


/// Adds a host header value to a specified website. WARNING: NO ERROR CHECKING IS PERFORMED IN THIS EXAMPLE.
/// YOU ARE RESPONSIBLE FOR THAT EVERY ENTRY IS UNIQUE
///

/// The host header. Must be in the form IP:Port:Hostname /// The ID of the website the host header should be added to private static void AddHostHeader(string hostHeader, string websiteID)
{
DirectoryEntry site = new DirectoryEntry(”IIS://localhost/w3svc/” + websiteID);
try
{
//Get everything currently in the serverbindings propery.
PropertyValueCollection serverBindings = site.Properties["ServerBindings"];

//Add the new binding
serverBindings.Add(hostHeader);

//Create an object array and copy the content to this array
Object[] newList = new Object[serverBindings.Count];

serverBindings.CopyTo(newList, 0);
//Write to metabase

site.Properties["ServerBindings"].Value = newList;

//Commit the changes
site.CommitChanges();
}

catch (Exception e)
{
Console.WriteLine(e);
}
}

public static ManagementObject CreateServerBinding(string HostName, string IP, string Port)
{
ManagementScope _scope = new ManagementScope(@”\\WINDOWS\root\MicrosoftIISV2″);
_scope.Connect();

ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath(”ServerBinding”), null);
ManagementObject serverBinding = classBinding.CreateInstance();
serverBinding.Properties["Hostname"].Value = HostName;
serverBinding.Properties["IP"].Value = IP;
serverBinding.Properties["Port"].Value = Port;
serverBinding.Put();
return serverBinding;
}

Categories: ASP.NET, IIS, c# Tags:
  1. a
    August 19th, 2009 at 15:29 | #1

    several using statements are needed for this code to compile. one for example: using System.DirectoryServices

  2. Michael Bell
    August 19th, 2009 at 15:39 | #2

    Indeed. I have the following using statements in that class:
    using System;
    using System.Data;
    using System.Configuration;
    using System.IO;
    using System.DirectoryServices;
    using System.Management;
    using System.Web;

    @a

  3. nojux
    November 13th, 2009 at 13:51 | #3

    we todd ed, man your double quotes are converted to fancy quotes, nice job

  1. No trackbacks yet.