简体   繁体   中英

programatically create iis 6.0 website and application pool with specified .net version

I need to create a new website in iis 6.0 (Windows server 2003 r2 sp2) and create a new virtual directory with .net framework 4.0 and assign it to created website .

here is my code :

public static int CreateWebSite(string webSiteName, string PhysicalPath, string PortNumber, string HostHeader, string DefaultDoc, string appPoolName, out string errorMessage)
    {
        errorMessage = string.Empty;
        try
        {
            DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
            // Find unused ID value for new web site
            int siteID = 1;
            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {
                    int ID = Convert.ToInt32(e.Name);
                    if (ID >= siteID)
                    {
                        siteID = ID + 1;
                    }
                }
            }

            DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
            site.Invoke("Put", "ServerComment", webSiteName);
            site.Invoke("Put", "KeyType", "IIsWebServer");

            site.Invoke("Put", "ServerBindings", ":" + PortNumber + ":" + HostHeader);

            site.Invoke("Put", "ServerState", 2);
            site.Invoke("Put", "FrontPageWeb", 1);
            site.Invoke("Put", "DefaultDoc", DefaultDoc);

            site.Invoke("Put", "ServerAutoStart", 1);
            site.Invoke("Put", "ServerSize", 1);
            site.Invoke("SetInfo");

            DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");

            if (appPoolName != "")
            {
                object[] param = { 0, appPoolName, true };
                siteVDir.Invoke("AppCreate3", param);
            }

            siteVDir.Properties["AppIsolated"][0] = 2;

            siteVDir.Properties["Path"][0] = PhysicalPath;

            siteVDir.Properties["AccessFlags"][0] = 513;
            siteVDir.Properties["AspEnableParentPaths"][0] = true;
            siteVDir.Properties["AppFriendlyName"][0] = webSiteName;
            siteVDir.Properties["FrontPageWeb"][0] = 1;
            siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";
            siteVDir.Properties["AppFriendlyName"][0] = "Root";
            siteVDir.Properties["AspSessionTimeout"][0] = "60";
            siteVDir.Properties["AuthFlags"].Value = 4;//integrity windows Authentication checked
            siteVDir.Properties["AuthAnonymous"][0] = true;//Anonymouse uncheck
            siteVDir.Properties["HttpErrors"].Add("401,1,FILE," + PhysicalPath + "/Lib/CustomError/SSOLoginError.htm");
            siteVDir.Properties["HttpErrors"].Add("401,2,FILE," + PhysicalPath + "/Lib/CustomError/SSOLoginError.htm");
            siteVDir.Properties["HttpErrors"].Add("401,3,FILE," + PhysicalPath + "/Lib/CustomError/SSOLoginError.htm");
            siteVDir.Properties["HttpErrors"].Add("401,4,FILE," + PhysicalPath + "/Lib/CustomError/SSOLoginError.htm");
            siteVDir.Properties["HttpErrors"].Add("401,5,FILE," + PhysicalPath + "/Lib/CustomError/SSOLoginError.htm");
            siteVDir.Properties["HttpErrors"].Add("401,7,FILE," + PhysicalPath + "/Lib/CustomError/SSOLoginError.htm");

            //For SSO, Set special settings for  WinLogin.aspx page -- This has beed added after version 8.1.1001
            DirectoryEntry deLoginDir;
            deLoginDir = siteVDir.Children.Add("WinLogin.aspx", siteVDir.SchemaClassName);
            deLoginDir.Properties["AuthAnonymous"][0] = false;//Anonymouse uncheck
            deLoginDir.Properties["AuthFlags"].Value = 4;//integrity windows Authentication checked
            deLoginDir.CommitChanges();
            ////////////////////////////////////////////

            siteVDir.CommitChanges();

            siteVDir.Invoke("AppDelete");
            siteVDir.Invoke("AppCreate", true);
            siteVDir.Invoke("AppEnable");

            site.CommitChanges();

            #region AssignApplicationPool

            DirectoryEntry vDir = new DirectoryEntry("IIS://localhost/W3SVC/" + siteID.ToString() + "/Root");
            string className = vDir.SchemaClassName.ToString();
            if (className.EndsWith("VirtualDir"))
            {
                object[] param = { 0, appPoolName, true };
                vDir.Invoke("AppCreate3", param);
                vDir.Properties["AppIsolated"][0] = "2";
                vDir.CommitChanges();
            }
            else
            {
                return -1;
            }

            if (Environment.OSVersion.Version.Major < 6)
            {
                try
                {
                    const string aspNetV1 = "1.0.3705";
                    const string aspNetV11 = "1.1.4322";
                    const string aspNetV2 = "2.0.50727";
                    const string aspNetV4 = "4.0.30319";
                    const string targetAspNetVersion = aspNetV4;

                    //loop through the script maps
                    for (var i = 0; i < siteVDir.Properties["ScriptMaps"].Count; i++)
                    {
                        //replace the versions if they exists
                        siteVDir.Properties["ScriptMaps"][i] =
                            siteVDir.Properties["ScriptMaps"][i].ToString().Replace(aspNetV1, targetAspNetVersion);
                        siteVDir.Properties["ScriptMaps"][i] =
                            siteVDir.Properties["ScriptMaps"][i].ToString().Replace(aspNetV11, targetAspNetVersion);
                        siteVDir.Properties["ScriptMaps"][i] =
                            siteVDir.Properties["ScriptMaps"][i].ToString().Replace(aspNetV2, targetAspNetVersion);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    errorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
                }
            }
            else
            {
                string appPoolPath = @"IIS://localhost/W3SVC/AppPools/" + appPoolName;
                try
                {
                    var appPoolEntry = new DirectoryEntry(appPoolPath);
                    appPoolEntry.Properties["managedRuntimeVersion"].Value = "v4.0";
                    appPoolEntry.Invoke("SetInfo", null);
                    appPoolEntry.CommitChanges();
                    appPoolEntry.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    errorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
                }

                siteVDir.CommitChanges();
                siteVDir.Close();
            }

            #endregion


            return siteID;
        }
        catch
        {
            return -1;
        }
    }

This code should work fine in IIS 6.0 (Windows 2003) and IIS 7.5+ (Windows 7 and Windows 2008). in windows 7 and 2008 every thing looks fine! but in windows 2003 I have some problems:

  1. Asp.net version of website does not change to v4
  2. Application Pool does not seems correct and its node in inetmgr only have one node with name Root not the name of website
  3. in the properties window of website -> home directory tab, application name is empty !

what is wrong with my code?

thanks in advance

DirectoryEntry sited = new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/Root", websiteID.ToString()));
sited.Properties["AccessRead"].Add(true);
PropertyValueCollection testScriptMap = sited.Properties["ScriptMaps"];

object[] allValues = (object[])testScriptMap.Value;
object[] newValues = new object[allValues.Length];
string oldVersion = "v1.1.4322";
string newVersion = "v2.0.50727";
//... etc to 4.0.30319 .....
for (int i = 0; i < allValues.Length; i++)
{
    if (allValues[i] is string)
    {
        string temp = allValues[i] as string;
        if (temp.Contains(oldVersion))
        {
            newValues[i] = temp.Replace(oldVersion, newVersion);
        }
        else
        {
            newValues[i] = allValues[i];
        }

    }
    else
    {
        newValues[i] = allValues[i];
    }
}
testScriptMap.Value = newValues;

sited.CommitChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM