Example #1
0
        /// <summary>
        /// Sitename == _FTP
        /// Appname = brugernavnet (navnet på virt directory)
        /// </summary>
        /// <param name="siteName"></param>
        public void CreateVirtualDirectory(string siteName, string appName, string physicalPath)
        {
            try
            {
                if (!Directory.Exists(physicalPath))
                {
                    Directory.CreateDirectory(physicalPath);
                }
                /*Create Authoorization rule */
                Configuration                  config = ServerMngr.GetApplicationHostConfiguration();
                ConfigurationSection           authorizationSection    = config.GetSection("system.ftpServer/security/authorization", siteName + "/" + appName);
                ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection();


                authorizationCollection.Clear();
                ConfigurationElement addElement = authorizationCollection.CreateElement("add");
                addElement["accessType"]  = @"Allow";
                addElement["users"]       = appName;
                addElement["permissions"] = @"Read, Write";
                authorizationCollection.Add(addElement);

                var vd = ServerMngr.Sites[siteName].Applications["/"].VirtualDirectories;
                vd.Add("/" + appName, physicalPath);
                ServerMngr.CommitChanges();
                BatchState.State = UserProcessState.VIRTUAL_DIRECTORY_OK;
            }
            catch (Exception)
            {
                BatchState.State = UserProcessState.VIRTUAL_DIRECTORY_ERROR;
                throw;
            }
        }
Example #2
0
        public void Revert()
        {
            var dialog = (IManagementUIService)this.GetService(typeof(IManagementUIService));
            var result =
                dialog.ShowMessage(
                    "Reverting to the parent configuration will result in the loss of all settings in the local configuration file for this feature. Are you sure you want to continue?",
                    this.Name, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button1);

            if (result != DialogResult.Yes)
            {
                return;
            }

            var service = (IConfigurationService)this.GetService(typeof(IConfigurationService));
            var section = service.GetSection("system.webServer/rewrite/allowedServerVariables");
            ConfigurationElementCollection collection = section.GetCollection();

            collection.Clear();
            collection.Delete();
            collection = section.GetCollection();

            this.SelectedItem = null;
            this.Items.Clear();
            foreach (ConfigurationElement ruleElement in collection)
            {
                var node = new AllowedVariableItem(ruleElement, this);
                this.Items.Add(node);
            }

            service.ServerManager.CommitChanges();
            this.OnRewriteSettingsSaved();
        }
Example #3
0
        public void SetEngines(HeliconZooEngine[] userEngines)
        {
            // Write to applicationHost.config

            using (var srvman = new ServerManager())
            {
                Configuration appConfig = srvman.GetApplicationHostConfiguration();


                ConfigurationSection           heliconZooServer  = appConfig.GetSection("system.webServer/heliconZooServer");
                ConfigurationElement           engines           = heliconZooServer.GetChildElement("userEngines");
                ConfigurationElementCollection enginesCollection = engines.GetCollection();
                enginesCollection.Clear();


                ConfigurationElement           switchboard           = heliconZooServer.GetChildElement("switchboard");
                ConfigurationElementCollection switchboardCollection = switchboard.GetCollection();
                switchboardCollection.Clear();



                foreach (HeliconZooEngine item in userEngines)
                {
                    if (item.isUserEngine)
                    {
                        ConfigurationElement engine = enginesCollection.CreateElement();
                        ConvertHeliconZooEngineToElement(item, engine);
                        enginesCollection.Add(engine);
                    }
                }

                srvman.CommitChanges();
            }
        }
Example #4
0
        /// <summary>
        /// Updates the ARR server farm based on instances of the current role.
        /// </summary>
        private static void UpdateFarm(string serverEndpointName, Boolean enableAffinity)
        {
            // Get the list of server endpoints for every instance in the role.
            List <IPEndPoint> serverEndpoints = new List <IPEndPoint>();

            if (enableAffinity) // Iterate throw all roles if we need to enable affinity
            {
                foreach (RoleInstance instance in RoleEnvironment.CurrentRoleInstance.Role.Instances)
                {
                    RoleInstanceEndpoint serverEndpoint;
                    if (!instance.InstanceEndpoints.TryGetValue(serverEndpointName, out serverEndpoint))
                    {
                        throw new InvalidOperationException("Invalid server endpoint name");
                    }

                    serverEndpoints.Add(serverEndpoint.IPEndpoint);
                }
            }
            else
            {
                RoleInstance         instance = RoleEnvironment.CurrentRoleInstance;
                RoleInstanceEndpoint serverEndpoint;
                if (!instance.InstanceEndpoints.TryGetValue(serverEndpointName, out serverEndpoint))
                {
                    throw new InvalidOperationException("Invalid server endpoint name");
                }

                serverEndpoints.Add(serverEndpoint.IPEndpoint);
            }

            // Update the webfarm with the list of endpoints.
            using (ServerManager sm = new ServerManager())
            {
                ConfigurationElementCollection farm = GetFarmElement(sm, serverEndpointName, enableAffinity).GetCollection();

                // Remove all server elements from the farm.
                farm.Clear();

                // Add each endpoint to the farm.
                foreach (IPEndPoint endPoint in serverEndpoints)
                {
                    ConfigurationElement server = farm.CreateElement("server");
                    server.SetAttributeValue("address", endPoint.Address.ToString());
                    server.SetAttributeValue("enabled", true);
                    server.GetChildElement("applicationRequestRouting").SetAttributeValue("httpPort", endPoint.Port);
                    farm.Add(server);
                }

                sm.CommitChanges();
            }
        }
Example #5
0
    /// <summary>
    /// 添加指定站点默认文档,参数为该站点全部默认文档数组
    /// </summary>
    public void AddDefaultDocBysiteName(string siteName, params string[] defaultDoc)
    {
        //无ID身份标志,所以全部清除后,再逐一添加
        ConfigurationElementCollection ces = GetDefaultElementsBySiteName(siteName);

        ces.Clear();
        for (int i = 0; i < defaultDoc.Length; i++)
        {
            ConfigurationElement ce = ces.CreateElement();
            ce.Attributes["value"].Value = defaultDoc[i];
            ces.Add(ce);
        }
        iis.CommitChanges();
    }
Example #6
0
        /// <summary>
        ///     Removes all web dav authoring rule.
        /// </summary>
        /// <param name="webSiteName"> Name of the web site. </param>
        public void RemoveAllWebDavAuthoringRules(string webSiteName)
        {
            Trace.TraceInformation("RemoveAllWebDavAuthoringRules...");

            try
            {
                Configuration        configuration         = this.ServerManager.GetApplicationHostConfiguration();
                ConfigurationSection authoringRulesSection = configuration.GetSection("system.webServer/webdav/authoringRules",
                                                                                      webSiteName);

                ConfigurationElementCollection authoringRulesCollection = authoringRulesSection.GetCollection();
                authoringRulesCollection.Clear();

                this.ServerManager.CommitChanges();
            }
            finally
            {
                Trace.TraceInformation("RemoveAllWebDavAuthoringRules...finished.");
            }
        }
            private static void SetServiceNamesMWA(ConfigurationElement extendedProtectionPolicyElement, MultiValuedProperty <string> spnList)
            {
                ConfigurationElement configurationElement = extendedProtectionPolicyElement.ChildElements["customServiceNames"];

                if (configurationElement == null)
                {
                    return;
                }
                ConfigurationElementCollection collection = configurationElement.GetCollection();

                if (collection == null)
                {
                    return;
                }
                collection.Clear();
                foreach (string text in spnList)
                {
                    ConfigurationElement configurationElement2 = collection.CreateElement("add");
                    configurationElement2["name"] = text;
                    collection.Add(configurationElement2);
                }
            }
Example #8
0
        public void SetEnabledEnginesForSite(string siteId, string[] engineNames)
        {
            if (string.IsNullOrEmpty(siteId))
            {
                return;
            }

            using (var srvman = new ServerManager())
            {
                Configuration                  appConfig             = srvman.GetApplicationHostConfiguration();
                ConfigurationSection           zooServer             = appConfig.GetSection("system.webServer/heliconZooServer", siteId);
                ConfigurationElement           switchboard           = zooServer.GetChildElement("switchboard");
                ConfigurationElementCollection switchboardCollection = switchboard.GetCollection();

                switchboardCollection.Clear();

                // first disable all engines if "*" is not present in input engineNames
                if (!engineNames.Contains("*"))
                {
                    ConfigurationElement elementDisableAll = switchboardCollection.CreateElement();
                    elementDisableAll.SetAttributeValue("name", "*");
                    SetSwitchBoardValue(elementDisableAll, false);
                    switchboardCollection.Add(elementDisableAll);
                }

                foreach (string engineName in engineNames)
                {
                    ConfigurationElement element = switchboardCollection.CreateElement();
                    element.SetAttributeValue("name", engineName);
                    SetSwitchBoardValue(element, true);
                    switchboardCollection.Add(element);
                }

                RegisterZooPhpHandlers(siteId, engineNames, appConfig);

                srvman.CommitChanges();
            }
        }
Example #9
0
        /// <summary>
        /// Configures the site for ACME validation without generating an overly complicated web.config
        /// </summary>
        /// <param name="target"></param>
        public void PrepareSite(Target target)
        {
            var config = ServerManager.GetApplicationHostConfiguration();
            var siteId = target.ValidationSiteId ?? target.TargetSiteId ?? -1;
            var site   = GetWebSite(siteId);

            // Only do it for the .well-known folder, do not compromise security for other parts of the application
            var wellKnown     = $"/{_wellKnown}";
            var acmeChallenge = $"/{_wellKnown}/{_acmeChallenge}";
            var parentPath    = site.Name + wellKnown;
            var path          = site.Name + acmeChallenge;

            // Create application
            var rootApp  = site.Applications.FirstOrDefault(x => x.Path == "/");
            var rootVdir = rootApp.VirtualDirectories.FirstOrDefault(x => x.Path == "/");
            var wkApp    = site.Applications.FirstOrDefault(a => a.Path == wellKnown);
            var acApp    = site.Applications.FirstOrDefault(a => a.Path == acmeChallenge);
            var wkVdir   = wkApp?.VirtualDirectories.FirstOrDefault(v => v.Path == "/");
            var acVdir   = acApp?.VirtualDirectories.FirstOrDefault(v => v.Path == "/");

            if (wkApp == null)
            {
                wkApp = site.Applications.CreateElement();
                wkApp.ApplicationPoolName = rootApp.ApplicationPoolName;
                wkApp.Path = wellKnown;
                site.Applications.Add(wkApp);
            }
            if (acApp == null)
            {
                acApp = site.Applications.CreateElement();
                acApp.ApplicationPoolName = rootApp.ApplicationPoolName;
                acApp.Path = acmeChallenge;
                site.Applications.Add(acApp);
            }
            if (wkVdir == null)
            {
                wkVdir      = wkApp.VirtualDirectories.CreateElement();
                wkVdir.Path = "/";
                wkApp.VirtualDirectories.Add(wkVdir);
                wkVdir.PhysicalPath = $"{rootVdir.PhysicalPath.TrimEnd('\\')}\\{_wellKnown}\\";
            }
            if (acVdir == null)
            {
                acVdir      = wkApp.VirtualDirectories.CreateElement();
                acVdir.Path = "/";
                acApp.VirtualDirectories.Add(acVdir);
            }
            acVdir.PhysicalPath = $"{rootVdir.PhysicalPath.TrimEnd('\\')}\\{_wellKnown}\\{_acmeChallenge}\\";

            // Enabled Anonymous authentication
            ConfigurationSection anonymousAuthenticationSection = config.GetSection(_anonymousAuthenticationSection, path);

            anonymousAuthenticationSection["enabled"] = true;

            // Disable "Require SSL"
            ConfigurationSection accessSecuritySection = config.GetSection(_accessSecuritySection, path);

            accessSecuritySection["sslFlags"] = "None";

            // Disable IP restrictions
            ConfigurationSection ipSecuritySection = config.GetSection(_ipSecuritySection, path);

            ipSecuritySection["allowUnlisted"] = true;

            ConfigurationSection globalModules = config.GetSection(_modulesSection);
            var globals = globalModules.GetCollection().Select(gm => gm.GetAttributeValue("name")).ToList();

            var local = ServerManager.GetWebConfiguration(site.Name, path);
            ConfigurationSection localModules = local.GetSection(_modulesSection);

            ConfigurationSection           modulesSection    = config.GetSection(_modulesSection, path);
            ConfigurationElementCollection modulesCollection = modulesSection.GetCollection();

            modulesSection["runAllManagedModulesForAllRequests"] = false;
            foreach (var module in localModules.GetCollection())
            {
                var moduleName = module.GetAttributeValue("name");
                if (!globals.Contains(moduleName))
                {
                    ConfigurationElement newModule = modulesCollection.CreateElement("remove");
                    newModule.SetAttributeValue("name", moduleName);
                    modulesCollection.Add(newModule);
                }
            }

            // Configure handlers
            ConfigurationSection           handlerSection     = config.GetSection(_handlerSection, path);
            ConfigurationElementCollection handlersCollection = handlerSection.GetCollection();

            handlersCollection.Clear();
            ConfigurationElement addElement = handlersCollection.CreateElement("add");

            addElement["modules"]      = "StaticFileModule,DirectoryListingModule";
            addElement["name"]         = "StaticFile";
            addElement["resourceType"] = "Either";
            addElement["path"]         = "*";
            addElement["verb"]         = "GET";
            handlersCollection.Add(addElement);

            // Disable URL rewrite
            if (_rewriteModule)
            {
                try
                {
                    ConfigurationSection           urlRewriteSection    = config.GetSection(_urlRewriteSection, path);
                    ConfigurationElementCollection urlRewriteCollection = urlRewriteSection.GetCollection();
                    urlRewriteCollection.Clear();
                }
                catch { }
            }

            // Save
            Commit();
        }
        public static void CommitToMetabase(ExchangeVirtualDirectory exchangeVirtualDirectory, Task task)
        {
            if (exchangeVirtualDirectory.ExchangeVersion.IsOlderThan(ExchangeObjectVersion.Exchange2010))
            {
                return;
            }
            bool flag  = task.Fields.IsModified("ExtendedProtectionTokenChecking");
            bool flag2 = task.Fields.IsModified("ExtendedProtectionFlags");
            bool flag3 = task.Fields.IsModified("ExtendedProtectionSPNList");

            if (flag || flag2 || flag3)
            {
                string metabasePath = exchangeVirtualDirectory.MetabasePath;
                using (DirectoryEntry directoryEntry = IisUtility.CreateIISDirectoryEntry(metabasePath, new Task.TaskErrorLoggingReThrowDelegate(task.WriteError), exchangeVirtualDirectory.Identity))
                {
                    if (directoryEntry != null)
                    {
                        string text;
                        string text2;
                        string text3;
                        if (ExtendedProtection.GetServerWebSiteAndPath(metabasePath, out text, out text2, out text3))
                        {
                            if (!ExtendedProtection.WebConfigReflectionHelper.IsExtendedProtectionSupported(task))
                            {
                                TaskLogger.Trace("Warning: ExtendedProtectionPolicy has not been added to HttpTransportElement of web.config.  Install the operating system update(s) specified in KB {0} onto server {1} and try again.", new object[]
                                {
                                    "981205",
                                    text
                                });
                                task.WriteWarning(Strings.WarnExtendedProtectionIsNotEnabled(text, "981205"));
                            }
                            else
                            {
                                string text4 = "/" + text2 + text3;
                                using (ServerManager serverManager = ServerManager.OpenRemote(text))
                                {
                                    Configuration applicationHostConfiguration = serverManager.GetApplicationHostConfiguration();
                                    if (applicationHostConfiguration != null)
                                    {
                                        ConfigurationSection section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/windowsAuthentication", text4);
                                        if (section != null)
                                        {
                                            ConfigurationElement configurationElement = section.ChildElements["extendedProtection"];
                                            if (configurationElement != null)
                                            {
                                                if (flag)
                                                {
                                                    int num = (int)exchangeVirtualDirectory[ExchangeVirtualDirectorySchema.ExtendedProtectionTokenChecking];
                                                    configurationElement.SetAttributeValue("tokenChecking", num);
                                                }
                                                if (flag2)
                                                {
                                                    int num2 = (int)exchangeVirtualDirectory[ExchangeVirtualDirectorySchema.ExtendedProtectionFlags];
                                                    configurationElement.SetAttributeValue("flags", num2);
                                                }
                                                if (flag3)
                                                {
                                                    ConfigurationElementCollection collection = configurationElement.GetCollection();
                                                    collection.Clear();
                                                    foreach (string text5 in exchangeVirtualDirectory.ExtendedProtectionSPNList)
                                                    {
                                                        ConfigurationElement configurationElement2 = collection.CreateElement("spn");
                                                        configurationElement2.SetAttributeValue("name", text5);
                                                        collection.Add(configurationElement2);
                                                    }
                                                }
                                                ExtendedProtection.WebConfigReflectionHelper.CommitToWebConfigMWA(exchangeVirtualDirectory, task, text3, text2, text, flag, flag3);
                                                serverManager.CommitChanges();
                                                return;
                                            }
                                            TaskLogger.Trace("Warning: Extended protection has not been enabled.  Install the operating system update specified in KB {0} onto server {1} and try again.", new object[]
                                            {
                                                "973917",
                                                text
                                            });
                                            task.WriteWarning(Strings.WarnExtendedProtectionIsNotEnabled(text, "973917"));
                                            return;
                                        }
                                    }
                                    TaskLogger.Trace("Error:ApplicationHost.config or {0} is not found for virtual directory with metabase path '{1}' and local path '{2}'.", new object[]
                                    {
                                        "system.webServer/security/authentication/windowsAuthentication",
                                        metabasePath,
                                        text4
                                    });
                                    task.WriteError(new ArgumentException(Strings.ErrorAppHostOrWindowsAuthenticationNotFound("system.webServer/security/authentication/windowsAuthentication", metabasePath, text4)), ErrorCategory.ObjectNotFound, exchangeVirtualDirectory.Identity);
                                }
                            }
                        }
                    }
                }
            }
        }
        public void TestIisExpressReadOnly()
        {
            var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Environment.SetEnvironmentVariable("JEXUS_TEST_HOME", directoryName);

            if (directoryName == null)
            {
                return;
            }

            string Current  = Path.Combine(directoryName, @"applicationHost.config");
            string Original = Path.Combine(directoryName, @"original2.config");

            TestHelper.CopySiteConfig(directoryName, "original.config");
            File.Copy(Original, Current, true);
            TestHelper.FixPhysicalPathMono(Current);

            var message =
                "The configuration object is read only, because it has been committed by a call to ServerManager.CommitChanges(). If write access is required, use ServerManager to get a new reference.";

#if IIS
            var server = new ServerManager(true, Current);
#else
            var server = new IisExpressServerManager(true, Current);
#endif
            var exception1 = Assert.Throws <InvalidOperationException>(
                () =>
            {
                TestCases.TestIisExpress(server);
            });
            Assert.Equal(message, exception1.Message);

            // site config "Website1"
            var config = server.Sites[0].Applications[0].GetWebConfiguration();

            // enable Windows authentication
            var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
            Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
            Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
            Assert.Equal(true, windowsSection.IsLocked);
            Assert.Equal(false, windowsSection.IsLocallyStored);

            var windowsEnabled = (bool)windowsSection["enabled"];
            Assert.False(windowsEnabled);

            var compression = config.GetSection("system.webServer/urlCompression");
            Assert.Equal(OverrideMode.Inherit, compression.OverrideMode);
            Assert.Equal(OverrideMode.Allow, compression.OverrideModeEffective);
            Assert.Equal(false, compression.IsLocked);
            Assert.Equal(false, compression.IsLocallyStored);

            Assert.Equal(true, compression["doDynamicCompression"]);

            var compress = Assert.Throws <InvalidOperationException>(() => compression["doDynamicCompression"] = false);
            Assert.Equal(message, compress.Message);

            {
                // disable default document. Saved to web.config as this section can be overridden anywhere.
                ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                Assert.Equal(true, defaultDocumentSection["enabled"]);

                ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                Assert.Equal(7, filesCollection.Count);

                {
                    var first = filesCollection[0];
                    Assert.Equal("home1.html", first["value"]);
                    Assert.True(first.IsLocallyStored);
                }

                var second = filesCollection[1];
                Assert.Equal("Default.htm", second["value"]);
                Assert.False(second.IsLocallyStored);

                var third = filesCollection[2];
                Assert.Equal("Default.asp", third["value"]);
                Assert.False(third.IsLocallyStored);

                var remove = Assert.Throws <FileLoadException>(() => filesCollection.RemoveAt(4));
                Assert.Equal(
                    "Filename: \r\nError: This configuration section cannot be modified because it has been opened for read only access\r\n\r\n",
                    remove.Message);

                ConfigurationElement addElement = filesCollection.CreateElement();
                var add = Assert.Throws <InvalidOperationException>(() => filesCollection.AddAt(0, addElement));
                Assert.Equal(message, add.Message);

                Assert.Equal(7, filesCollection.Count);

                {
                    var first = filesCollection[0];
                    Assert.Equal("home1.html", first["value"]);
                    // TODO: why?
                    // Assert.IsFalse(first.IsLocallyStored);
                }

                Assert.Equal(7, filesCollection.Count);

                var clear = Assert.Throws <InvalidOperationException>(() => filesCollection.Clear());
                Assert.Equal(message, clear.Message);

                var delete = Assert.Throws <InvalidOperationException>(() => filesCollection.Delete());
                Assert.Equal(message, delete.Message);
            }
        }
Example #12
0
        public static void TestIisExpressMissingWebsiteConfig(ServerManager server)
        {
            {
                var config = server.GetApplicationHostConfiguration();

                var windowsSection =
                    config.GetSection("system.webServer/security/authentication/windowsAuthentication");
                windowsSection["enabled"] = true;
                server.CommitChanges();
            }
            {
                // server config "Website1"
                var config         = server.GetApplicationHostConfiguration();
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication",
                                                       "WebSite1");
                windowsSection["enabled"] = false;
                {
                    // disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
                    ConfigurationSection httpLoggingSection =
                        config.GetSection("system.webServer/httpLogging", "WebSite1");
                    httpLoggingSection["dontLog"] = true;
                }

                {
                    ConfigurationSection httpLoggingSection =
                        config.GetSection("system.webServer/httpLogging", "WebSite1/test");
                    httpLoggingSection["dontLog"] = false;
                }
            }
            {
                // site config "Website1"
                var config      = server.Sites[0].Applications[0].GetWebConfiguration();
                var compression = config.GetSection("system.webServer/urlCompression");
                compression["doDynamicCompression"] = false;
                {
                    // disable default document. Saved to web.config as this section can be overridden anywhere.
                    ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                    Assert.Equal(true, defaultDocumentSection["enabled"]);
                    defaultDocumentSection["enabled"] = false;

                    ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                    Assert.Equal(6, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("Default.htm", first["value"]);
                        Assert.False(first.IsLocallyStored);
                    }

                    var second = filesCollection[1];
                    Assert.Equal("Default.asp", second["value"]);
                    Assert.False(second.IsLocallyStored);

                    var third = filesCollection[2];
                    Assert.Equal("index.htm", third["value"]);
                    Assert.False(third.IsLocallyStored);

                    ConfigurationElement addElement = filesCollection.CreateElement();
                    addElement["value"] = @"home.html";
                    filesCollection.AddAt(0, addElement);

                    Assert.Equal(7, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("home.html", first["value"]);
                        // TODO: why?
                        // Assert.False(first.IsLocallyStored);
                    }

                    filesCollection.RemoveAt(4);
                    Assert.Equal(6, filesCollection.Count);

                    ConfigurationElement lastElement = filesCollection.CreateElement();
                    lastElement["value"] = @"home.html";
                    var dup = Assert.Throws <COMException>(() => filesCollection.Add(lastElement));
#if IIS
                    Assert.Equal(
                        "Filename: \r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
                        dup.Message);
#else
                    Assert.Equal(
                        $"Filename: \\\\?\\{config.FileContext.FileName}\r\nLine number: 0\r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
                        dup.Message);
#endif
                    lastElement["value"] = @"home2.html";
                    filesCollection.Add(lastElement);
                    Assert.Equal(7, filesCollection.Count);
                }

                var errorsSection    = config.GetSection("system.webServer/httpErrors");
                var errorsCollection = errorsSection.GetCollection();
                var error            = errorsCollection.CreateElement();
                error["statusCode"]             = 500;
                error["subStatusCode"]          = 55;
                error["prefixLanguageFilePath"] = string.Empty;
                error["responseMode"]           = "File";
                error["path"] = "test.htm";
                errorsCollection.Add(error);

                var staticContent = config.GetSection("system.webServer/staticContent").GetChildElement("clientCache");
                staticContent["cacheControlMode"] = "DisableCache";

                ConfigurationSection requestFilteringSection =
                    config.GetSection("system.webServer/security/requestFiltering");
                ConfigurationElement           hiddenSegmentsElement    = requestFilteringSection.GetChildElement("hiddenSegments");
                ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
                var test = hiddenSegmentsCollection.CreateElement();
                test["segment"] = "test";
                hiddenSegmentsCollection.Add(test);
                var old = hiddenSegmentsCollection[0];
                hiddenSegmentsCollection.Remove(old);

                var section = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationElementCollection collection = section.GetCollection();
                collection.Clear();
                var newElement = collection.CreateElement();
                newElement["name"] = "test";
                collection.Add(newElement);
            }

            {
                // server config "Website1"
                var config = server.GetApplicationHostConfiguration();
                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication",
                                                       "WebSite1");
                var windowsEnabled = (bool)windowsSection["enabled"];
            }
            {
                Configuration config = server.GetApplicationHostConfiguration();

                var anonymousSection = config.GetSection(
                    "system.webServer/security/authentication/anonymousAuthentication",
                    "WebSite2");
                ConfigurationSection windowsAuthenticationSection =
                    config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite2");
                windowsAuthenticationSection["enabled"] = true;

                ConfigurationElement extendedProtectionElement =
                    windowsAuthenticationSection.GetChildElement("extendedProtection");
                extendedProtectionElement["tokenChecking"] = @"Allow";
                extendedProtectionElement["flags"]         = @"None";
                ConfigurationElementCollection extendedProtectionCollection =
                    extendedProtectionElement.GetCollection();

                ConfigurationElement spnElement = extendedProtectionCollection.CreateElement("spn");
                spnElement["name"] = @"HTTP/www.contoso.com";
                extendedProtectionCollection.Add(spnElement);

                ConfigurationElement spnElement1 = extendedProtectionCollection.CreateElement("spn");
                spnElement1["name"] = @"HTTP/contoso.com";
                extendedProtectionCollection.Add(spnElement1);

                server.CommitChanges();
            }
            // remove application pool
            Assert.False(server.ApplicationPools.AllowsRemove);
            Assert.Equal(5, server.ApplicationPools.Count);
            server.ApplicationPools.RemoveAt(4);
            Assert.Equal(4, server.ApplicationPools.Count);

            // remove binding
            server.Sites[1].Bindings.RemoveAt(1);

            // remove site
            server.Sites.RemoveAt(4);

            // remove application
            var site1 = server.Sites[9];
            site1.Applications.RemoveAt(1);

            // remove virtual directory
            var application = server.Sites[2].Applications[0];
            application.VirtualDirectories.RemoveAt(1);

            server.CommitChanges();
        }
Example #13
0
        //添加ftp站点
        public void createFTP(string ftpname, string ftpPath, string username, string ipaddress)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetApplicationHostConfiguration();

                ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");

                ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

                ConfigurationElement siteElement = sitesCollection.CreateElement("site");
                siteElement["name"] = ftpname;
                siteElement["id"]   = GetNewSiteID();

                ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");

                ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
                bindingElement["protocol"]           = @"ftp";
                bindingElement["bindingInformation"] = ipaddress + @":21:";
                bindingsCollection.Add(bindingElement);

                //ftp 授权规则
                ConfigurationSection           authorizationSection    = config.GetSection("system.ftpServer/security/authorization");
                ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection();
                // 清除子节点授权,防止有残余
                authorizationCollection.Clear();
                ConfigurationElement addElement1 = authorizationCollection.CreateElement("add");
                addElement1["accessType"]  = @"Allow";
                addElement1["users"]       = username;
                addElement1["permissions"] = @"Read,Write";
                authorizationCollection.Add(addElement1);

                ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");
                //设置ftp ssl
                ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");
                ConfigurationElement sslElement      = securityElement.GetChildElement("ssl");
                //sslElement["serverCertHash"] = @"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
                sslElement["controlChannelPolicy"] = @"SslAllow";
                sslElement["dataChannelPolicy"]    = @"SslAllow";
                // 设置ftp身份验证
                ConfigurationElement authenticationElement = securityElement.GetChildElement("authentication");
                //ConfigurationElementCollection authenticationElementCollection = authorizationSection.GetCollection();
                ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
                basicAuthenticationElement["enabled"] = @"true";
                ConfigurationElement anonymousAuthenticationElement = authenticationElement.GetChildElement("anonymousAuthentication");
                anonymousAuthenticationElement["enabled"] = @"true";



                ConfigurationElementCollection siteCollection     = siteElement.GetCollection();
                ConfigurationElement           applicationElement = siteCollection.CreateElement("application");
                applicationElement["path"] = @"/";

                ConfigurationElementCollection applicationCollection   = applicationElement.GetCollection();
                ConfigurationElement           virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
                virtualDirectoryElement["path"]         = @"/";
                virtualDirectoryElement["physicalPath"] = ftpPath;
                applicationCollection.Add(virtualDirectoryElement);
                siteCollection.Add(applicationElement);
                sitesCollection.Add(siteElement);
                serverManager.CommitChanges();
            }
        }
        private bool ConfigureHandler(ServerManager mgr, string siteName, string virtualPath, string physicalPath, string isapiFileName, ModeType mode)
        {
            Site ste = mgr.Sites[siteName];

            if (ste == null)
            {
                if (mode == ModeType.Undeploy)
                {
                    base.Log.LogWarning("Cannot find IIS site '" + siteName + "'.");
                    return(true);
                }
                else
                {
                    base.Log.LogError("Cannot find IIS site '" + siteName + "'.");
                    return(false);
                }
            }

            Application app = ste.Applications[virtualPath];

            if (app == null)
            {
                if (mode == ModeType.Undeploy)
                {
                    base.Log.LogWarning("Cannot find IIS application '" + virtualPath + "'.");
                    return(true);
                }
                else
                {
                    base.Log.LogError("Cannot find IIS application '" + virtualPath + "'.");
                    return(false);
                }
            }

            Configuration config = app.GetWebConfiguration();

            ConfigurationSection           handlersSection    = config.GetSection("system.webServer/handlers");
            ConfigurationElementCollection handlersCollection = handlersSection.GetCollection();

            ConfigurationElement addElement =
                handlersCollection.FirstOrDefault(elem => string.Compare(elem.Attributes["scriptProcessor"].Value.ToString(), physicalPath, true) == 0);

            if (mode == ModeType.Deploy)
            {
                base.Log.LogMessage("Adding handler mapping '{0}'...", physicalPath);
                if (addElement == null)
                {
                    addElement                    = handlersCollection.CreateElement("add");
                    addElement["name"]            = isapiFileName;
                    addElement["path"]            = isapiFileName;
                    addElement["verb"]            = "*";
                    addElement["modules"]         = "IsapiModule";
                    addElement["scriptProcessor"] = physicalPath;
                    handlersCollection.Clear();
                    handlersCollection.AddAt(0, addElement);
                }
                else
                {
                    addElement["name"]            = isapiFileName;
                    addElement["path"]            = isapiFileName;
                    addElement["verb"]            = "*";
                    addElement["modules"]         = "IsapiModule";
                    addElement["scriptProcessor"] = physicalPath;
                }
                mgr.CommitChanges();
                base.Log.LogMessage("Added handler mapping '{0}'.", physicalPath);
            }
            else if (mode == ModeType.Undeploy && addElement != null)
            {
                base.Log.LogMessage("Removing handler mapping '{0}'...", physicalPath);
                handlersCollection.Remove(addElement);
                mgr.CommitChanges();
                base.Log.LogMessage("Removed handler mapping '{0}'...", physicalPath);
            }

            return(true);
        }
        private static void AddImageHandlers(string siteName)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                //MessageBox.Show("AddImageHandlers called for siteName " + siteName);

                Configuration config = serverManager.GetWebConfiguration(siteName);

                ConfigurationSection           handlersSection    = config.GetSection("system.webServer/handlers");
                ConfigurationElementCollection handlersCollection = handlersSection.GetCollection();
                bool pngHandlerMissing  = true;
                bool jpgHandlerMissing  = true;
                bool jpegHandlerMissing = true;
                bool add1Missing        = true;
                bool remove1Missing     = true;
                bool remove2Missing     = true;
                bool remove3Missing     = true;
                //ConfigurationElement toRemoveCe = null;

                List <ConfigurationElement> toRemoveElements = new List <ConfigurationElement>();

                foreach (ConfigurationElement ce in handlersCollection)
                {
                    //if (ce.GetAttributeValue("name").ToString() == "get-image-png")
                    //{
                    //    //MessageBox.Show("pngHandlerMissing");
                    //    pngHandlerMissing = false;
                    //}
                    //if (ce.GetAttributeValue("name").ToString() == "get-image-jpg")
                    //{
                    //    //MessageBox.Show("jpgHandlerMissing");
                    //    jpgHandlerMissing = false;
                    //}
                    //if (ce.GetAttributeValue("name").ToString() == "get-image-jpeg")
                    //{
                    //    //MessageBox.Show("jpegHandlerMissing");
                    //    jpegHandlerMissing = false;
                    //}
                    //if (ce.GetAttributeValue("name").ToString() == "ExtensionlessUrlHandler-Integrated-4.0")
                    //{
                    //    add1Missing = false;
                    //}
                    //if (ce.GetAttributeValue("name").ToString() == "OPTIONSVerbHandler")
                    //{
                    //    remove2Missing = false;
                    //}
                    //if (ce.GetAttributeValue("name").ToString() == "TRACEVerbHandler")
                    //{
                    //    remove3Missing = false;
                    //}

                    //if (ce.GetAttributeValue("name").ToString() == "ExtensionlessUrlHandler-Integrated-4.0")
                    //{
                    //    toRemoveCe = ce;
                    //}
                    toRemoveElements.Add(ce);
                }
                //try
                //{
                //    if (toRemoveCe != null)
                //        handlersCollection.Remove(toRemoveCe);
                //} catch { }
                foreach (ConfigurationElement ce in toRemoveElements)
                {
                    handlersCollection.Remove(ce);
                }
                handlersCollection.Clear();

                if (remove1Missing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("remove");
                        ele["name"] = "ExtensionlessUrlHandler-Integrated-4.0";
                        handlersCollection.Add(ele);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show("ExtensionlessUrlHandler ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }

                if (remove2Missing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("remove");
                        ele["name"] = "OPTIONSVerbHandler";
                        handlersCollection.Add(ele);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show("OPTIONSVerbHandler ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }

                if (remove3Missing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("remove");
                        ele["name"] = "TRACEVerbHandler";
                        handlersCollection.Add(ele);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show("TRACEVerbHandler ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }
                if (add1Missing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("add");
                        ele["name"]         = "ExtensionlessUrlHandler-Integrated-4.0";
                        ele["path"]         = @"*.";
                        ele["verb"]         = "*";
                        ele["type"]         = @"System.Web.Handlers.TransferRequestHandler";
                        ele["preCondition"] = "integratedMode,runtimeVersionv4.0";
                        handlersCollection.Add(ele);
                    }
                    catch
                    {
                        //MessageBox.Show("pngHandlerMissing ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }

                if (pngHandlerMissing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("add");
                        ele["name"]                = "get-image-png";
                        ele["path"]                = @"*.png";
                        ele["verb"]                = "GET";
                        ele["type"]                = @"System.Web.Handlers.TransferRequestHandler";
                        ele["preCondition"]        = "integratedMode,runtimeVersionv4.0";
                        ele["responseBufferLimit"] = 0;
                        handlersCollection.Add(ele);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("pngHandlerMissing ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }

                if (jpgHandlerMissing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("add");
                        ele["name"]                = "get-image-jpg";
                        ele["path"]                = @"*.jpg";
                        ele["verb"]                = "GET";
                        ele["type"]                = @"System.Web.Handlers.TransferRequestHandler";
                        ele["preCondition"]        = "integratedMode,runtimeVersionv4.0";
                        ele["responseBufferLimit"] = 0;
                        handlersCollection.Add(ele);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("jpgHandlerMissing ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }

                if (jpegHandlerMissing)
                {
                    try
                    {
                        ConfigurationElement ele = handlersCollection.CreateElement("add");
                        ele["name"]                = "get-image-jpeg";
                        ele["path"]                = @"*.jpeg";
                        ele["verb"]                = "GET";
                        ele["type"]                = @"System.Web.Handlers.TransferRequestHandler";
                        ele["preCondition"]        = "integratedMode,runtimeVersionv4.0";
                        ele["responseBufferLimit"] = 0;

                        handlersCollection.Add(ele);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("jpegHandlerMissing ex is : " + ex.Message + "stacktrace : " + ex.StackTrace);
                    }
                }

                serverManager.CommitChanges();
            }
        }
Example #16
0
        public static void TestIisExpress(ServerManager server)
        {
            Assert.Equal(5, server.ApplicationPools.Count);
            Assert.True(server.ApplicationPools.AllowsAdd);
            Assert.False(server.ApplicationPools.AllowsClear);
            Assert.False(server.ApplicationPools.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '/', '"', '|', '<', '>', ':', '*', '?', ']', '[', '+', '=', ';', ',', '@', '&' },
                ApplicationPoolCollection.InvalidApplicationPoolNameCharacters());

            Assert.Equal(12, server.Sites.Count);
            Assert.True(server.Sites.AllowsAdd);
            Assert.False(server.Sites.AllowsClear);
            Assert.False(server.Sites.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '/', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>' },
                SiteCollection.InvalidSiteNameCharacters());

            var siteDefaults = server.SiteDefaults;

            //Assert.Equal("[http] :8080:localhost", server.Sites[0].Bindings[0].ToString());
            Assert.Equal("localhost on *:8080 (http)", server.Sites[0].Bindings[0].ToShortString());
            Assert.Equal("%IIS_USER_HOME%\\Logs", siteDefaults.LogFile.Directory);
            Assert.Equal(LogFormat.W3c, siteDefaults.LogFile.LogFormat);
            Assert.Equal("%IIS_USER_HOME%\\TraceLogFiles", siteDefaults.TraceFailedRequestsLogging.Directory);
            Assert.True(siteDefaults.TraceFailedRequestsLogging.Enabled);
            Assert.True(siteDefaults.LogFile.Enabled);
            Assert.Equal("Clr4IntegratedAppPool", server.ApplicationDefaults.ApplicationPoolName);

            var pool = server.ApplicationPools[0];

            var model = pool.GetChildElement("processModel");
            var item  = model["maxProcesses"];

            Assert.Equal("Clr4IntegratedAppPool", pool.Name);
            Assert.Equal("v4.0", pool.ManagedRuntimeVersion);
            Assert.Equal(1, pool.ProcessModel.MaxProcesses);
            Assert.Equal(string.Empty, pool.ProcessModel.UserName);
#if IIS
            Assert.Equal(1L, item);
#else
            Assert.Equal(1U, item);
#endif

            // TODO: why it should be int.
#if IIS
            Assert.Equal(0, pool.GetAttributeValue("managedPipelineMode"));
            pool.SetAttributeValue("managedPipelineMode", 1);
            Assert.Equal(1, pool.GetAttributeValue("managedPipelineMode"));
            pool.SetAttributeValue("managedPipelineMode", "Integrated");
            Assert.Equal(0, pool.GetAttributeValue("managedPipelineMode"));
#else
            Assert.Equal(0L, pool.GetAttributeValue("managedPipelineMode"));
            pool.SetAttributeValue("managedPipelineMode", 1);
            Assert.Equal(1L, pool.GetAttributeValue("managedPipelineMode"));
            pool.SetAttributeValue("managedPipelineMode", "Integrated");
            Assert.Equal(0L, pool.GetAttributeValue("managedPipelineMode"));

            Assert.Equal(14, pool.ApplicationCount);
#endif
            var name = Assert.Throws <COMException>(() => pool.SetAttributeValue("name", ""));
            Assert.Equal("Invalid application pool name\r\n", name.Message);

            var time = Assert.Throws <COMException>(() => pool.ProcessModel.IdleTimeout = TimeSpan.MaxValue);
            Assert.Equal("Timespan value must be between 00:00:00 and 30.00:00:00 seconds inclusive, with a granularity of 60 seconds\r\n", time.Message);

            var site = server.Sites[0];
            Assert.Equal("WebSite1", site.Name);
            Assert.Equal(14, site.Bindings.Count);
            {
                var binding = site.Bindings[0];
                Assert.Equal(IPAddress.Any, binding.EndPoint.Address);
                Assert.Equal(8080, binding.EndPoint.Port);
                Assert.Equal("localhost", binding.Host);
                Assert.Equal("*:8080:localhost", binding.ToString());
                Assert.Equal(":8080:localhost", binding.BindingInformation);
            }
            {
                var siteBinding = site.Bindings[1];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("808:* (net.tcp)", siteBinding.ToShortString());
            }
            {
                var siteBinding = site.Bindings[2];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("localhost (net.msmq)", siteBinding.ToShortString());
            }
            {
                var siteBinding = site.Bindings[3];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("localhost (msmq.formatname)", siteBinding.ToShortString());
            }
            {
                var siteBinding = site.Bindings[4];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("* (net.pipe)", siteBinding.ToShortString());
            }
            {
                var siteBinding = site.Bindings[5];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("*:21: (ftp)", siteBinding.ToShortString());
            }
            {
                var siteBinding = site.Bindings[6];
                Assert.Equal("* on *:8080 (http)", siteBinding.ToShortString());
                Assert.Equal("0.0.0.0:8080", siteBinding.EndPoint.ToString());
                Assert.Equal("*", siteBinding.Host);
            }
            {
                var siteBinding = site.Bindings[7];
                Assert.Equal("localhost on *:443 (https)", siteBinding.ToShortString());
                Assert.Equal("0.0.0.0:443", siteBinding.EndPoint.ToString());
                Assert.Equal("localhost", siteBinding.Host);
            }
            {
                var siteBinding = site.Bindings[8];
                Assert.Equal("* on *:44300 (https)", siteBinding.ToShortString());
                Assert.Equal("0.0.0.0:44300", siteBinding.EndPoint.ToString());
                Assert.Equal("*", siteBinding.Host);
            }
            {
                var siteBinding = site.Bindings[9];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("*:210:localhost (ftp)", siteBinding.ToShortString());
            }
            {
                var binding = site.Bindings[10];
                Assert.Null(binding.EndPoint);
                Assert.Equal(string.Empty, binding.Host);
                Assert.False(binding.IsIPPortHostBinding);
                Assert.False(binding.UseDsMapper);
                Assert.Null(binding.CertificateHash);
                Assert.Null(binding.CertificateStoreName);
                Assert.Equal("* (net.tcp)", binding.ToShortString());
            }
            {
                var binding = site.Bindings[11];
                Assert.Null(binding.EndPoint);
                Assert.Equal(string.Empty, binding.Host);
                Assert.False(binding.IsIPPortHostBinding);
                Assert.False(binding.UseDsMapper);
                Assert.Null(binding.CertificateHash);
                Assert.Null(binding.CertificateStoreName);
                Assert.Equal("* (net.msmq)", binding.ToShortString());
            }
            {
                var siteBinding = site.Bindings[12];
                Assert.Null(siteBinding.EndPoint);
                Assert.Equal(string.Empty, siteBinding.Host);
                Assert.False(siteBinding.IsIPPortHostBinding);
                Assert.False(siteBinding.UseDsMapper);
                Assert.Null(siteBinding.CertificateHash);
                Assert.Null(siteBinding.CertificateStoreName);
                Assert.Equal("* (msmq.formatname)", siteBinding.ToShortString());
            }
            {
                var binding = site.Bindings[13];
                Assert.Null(binding.EndPoint);
                Assert.Equal(string.Empty, binding.Host);
                Assert.False(binding.IsIPPortHostBinding);
                Assert.False(binding.UseDsMapper);
                Assert.Null(binding.CertificateHash);
                Assert.Null(binding.CertificateStoreName);
                Assert.Equal("localhost (net.pipe)", binding.ToShortString());
            }

            Assert.True(site.Bindings.AllowsAdd);
            Assert.True(site.Bindings.AllowsClear);
            Assert.False(site.Bindings.AllowsRemove);
            Assert.Equal("%IIS_USER_HOME%\\Logs", site.LogFile.Directory);

            var sslSite              = server.Sites[1];
            var sslBinding           = sslSite.Bindings[1];
            var certificateHash      = sslBinding.CertificateHash;
            var certificateStoreName = sslBinding.CertificateStoreName;
            Assert.Equal(SslFlags.Sni, sslBinding.SslFlags);

            sslSite.Bindings.RemoveAt(1);
            sslSite.Bindings.Add(":443:localhost", "https");
            sslBinding = sslSite.Bindings[1];
            Assert.Equal(SslFlags.None, sslBinding.SslFlags);

            sslSite.Bindings.RemoveAt(1);
            sslSite.Bindings.Add(":443:localhost", certificateHash, certificateStoreName, SslFlags.Sni);
            sslBinding = sslSite.Bindings[1];
            Assert.Equal(SslFlags.Sni, sslBinding.SslFlags);

            sslSite.Bindings.RemoveAt(1);
            sslSite.Bindings.Add(":443:localhost", certificateHash, certificateStoreName);
            sslBinding = sslSite.Bindings[1];
            Assert.Equal(SslFlags.None, sslBinding.SslFlags);

            {
                sslBinding = sslSite.Bindings.CreateElement();
                var exception = Assert.Throws <FileNotFoundException>(() => sslSite.Bindings.Add(sslBinding));
                Assert.Equal("Filename: \r\nError: Element is missing required attributes protocol,bindingInformation\r\n\r\n", exception.Message);
            }

            var app = site.Applications[0];
            Assert.True(site.Applications.AllowsAdd);
            Assert.False(site.Applications.AllowsClear);
            Assert.False(site.Applications.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
                ApplicationCollection.InvalidApplicationPathCharacters());
            Assert.Equal("Clr4IntegratedAppPool", app.ApplicationPoolName);

            Assert.Equal("/", app.Path);
            var vDir = app.VirtualDirectories[0];
            Assert.True(app.VirtualDirectories.AllowsAdd);
            Assert.False(app.VirtualDirectories.AllowsClear);
            Assert.False(app.VirtualDirectories.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
                VirtualDirectoryCollection.InvalidVirtualDirectoryPathCharacters());

            Assert.Equal(Helper.IsRunningOnMono() ? "%JEXUS_TEST_HOME%/WebSite1" : "%JEXUS_TEST_HOME%\\WebSite1", vDir.PhysicalPath);

            {
                var config  = server.GetApplicationHostConfiguration();
                var section = config.GetSection("system.applicationHost/log");
                var mode    = section.Attributes["centralLogFileMode"];
#if IIS
                Assert.Equal(0, mode.Value);
#else
                Assert.Equal(0L, mode.Value);
#endif
                var encoding = section.Attributes["logInUTF8"];
                Assert.Equal(true, encoding.Value);
                ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
                Assert.Equal(false, httpLoggingSection["dontLog"]);

                ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                Assert.Equal(true, defaultDocumentSection["enabled"]);
                ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                Assert.Equal(6, filesCollection.Count);

                var errorsSection    = config.GetSection("system.webServer/httpErrors");
                var errorsCollection = errorsSection.GetCollection();
                Assert.Equal(9, errorsCollection.Count);

                var anonymousSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
                var anonymousEnabled = (bool)anonymousSection["enabled"];
                Assert.True(anonymousEnabled);
                var value = anonymousSection["password"];
                Assert.Equal(string.Empty, value);

                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.False(windowsEnabled);

                windowsSection["enabled"] = true;
                server.CommitChanges();
            }

            {
                var config  = server.GetApplicationHostConfiguration();
                var asp     = config.GetSection("system.webServer/asp");
                var comPlus = asp.ChildElements["comPlus"];
                var sxsName = comPlus.GetAttribute("sxsName");
                sxsName.Delete();
                Assert.Equal("", (string)sxsName.Value);

                comPlus["sxsName"] = "test";
                server.CommitChanges();
            }

            {
                var config  = server.GetApplicationHostConfiguration();
                var asp     = config.GetSection("system.webServer/asp");
                var comPlus = asp.ChildElements["comPlus"];
                var sxsName = (string)comPlus["sxsName"];
                Assert.Equal("test", sxsName);

                var exception = Assert.Throws <COMException>(() => comPlus["sxsName"] = string.Empty);
                Assert.Equal("String must not be empty\r\n", exception.Message);
                server.CommitChanges();
            }

            {
                var config  = server.GetApplicationHostConfiguration();
                var asp     = config.GetSection("system.webServer/asp");
                var comPlus = asp.ChildElements["comPlus"];
                var sxsName = (string)comPlus["sxsName"];
                Assert.Equal("test", sxsName);

                comPlus.GetAttribute("sxsName").Delete();
                server.CommitChanges();

                sxsName = (string)comPlus.GetAttribute("sxsName").Value;
                Assert.Equal("", sxsName);
            }

            {
                var config    = server.GetApplicationHostConfiguration();
                var locations = config.GetLocationPaths();
                Assert.Equal(3, locations.Length);

                var exception =
                    Assert.Throws <FileNotFoundException>(
                        () =>
                        config.GetSection(
                            "system.webServer/security/authentication/anonymousAuthentication",
                            "Default Web Site"));
                Assert.Equal(
                    "Filename: \r\nError: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/Default Web Site'\r\n\r\n",
                    exception.Message);
                Assert.Null(exception.FileName);

                var anonymousSection = config.GetSection(
                    "system.webServer/security/authentication/anonymousAuthentication",
                    "WebSite2");
                var anonymousEnabled = (bool)anonymousSection["enabled"];
                Assert.True(anonymousEnabled);
                Assert.Equal("test", anonymousSection["userName"]);

                // Assert.Equal("123456", anonymousSection["password"]);
            }

            {
                // server config "Website1"
                var config = server.GetApplicationHostConfiguration();

                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
                Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
                Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
                Assert.Equal(false, windowsSection.IsLocked);
                Assert.True(windowsSection.IsLocallyStored);

                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.True(windowsEnabled);
                windowsSection["enabled"] = false;
                Assert.Equal(false, windowsSection["enabled"]);

                {
                    // disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
                    ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1");
                    Assert.Equal(false, httpLoggingSection["dontLog"]);
                    httpLoggingSection["dontLog"] = true;
                }

                {
                    ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1/test");
                    // TODO:
                    // Assert.Equal(true, httpLoggingSection["dontLog"]);
                    httpLoggingSection["dontLog"] = false;
                }
            }

            var siteName = Assert.Throws <COMException>(() => server.Sites[0].Name = "");
            Assert.Equal("Invalid site name\r\n", siteName.Message);

            var limit = Assert.Throws <COMException>(() => server.Sites[0].Limits.MaxBandwidth = 12);
            Assert.Equal("Integer value must not be between 0 and 1023 inclusive\r\n", limit.Message);

            var appPath = Assert.Throws <COMException>(() => server.Sites[0].Applications[0].Path = "");
            Assert.Equal("Invalid application path\r\n", appPath.Message);

            var vDirPath =
                Assert.Throws <COMException>(() => server.Sites[0].Applications[0].VirtualDirectories[0].Path = "");
            Assert.Equal("Invalid virtual directory path\r\n", vDirPath.Message);

            {
                // site config "Website1"
                var config = server.Sites[0].Applications[0].GetWebConfiguration();

                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
                Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
                Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
                Assert.True(windowsSection.IsLocked);
                Assert.Equal(false, windowsSection.IsLocallyStored);

                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.True(windowsEnabled);
                var exception = Assert.Throws <FileLoadException>(() => windowsSection["enabled"] = false);
                Assert.Equal(
                    "This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n",
                    exception.Message);
                Assert.Null(exception.FileName);

                var compression = config.GetSection("system.webServer/urlCompression");
                Assert.Equal(OverrideMode.Inherit, compression.OverrideMode);
                Assert.Equal(OverrideMode.Allow, compression.OverrideModeEffective);
                Assert.Equal(false, compression.IsLocked);
                Assert.Equal(false, compression.IsLocallyStored);

                Assert.Equal(true, compression["doDynamicCompression"]);

                compression["doDynamicCompression"] = false;

                {
                    // disable default document. Saved to web.config as this section can be overridden anywhere.
                    ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                    Assert.Equal(true, defaultDocumentSection["enabled"]);
                    defaultDocumentSection["enabled"] = false;

                    ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                    Assert.Equal(7, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("home1.html", first["value"]);
                        Assert.True(first.IsLocallyStored);
                    }

                    var second = filesCollection[1];
                    Assert.Equal("Default.htm", second["value"]);
                    Assert.False(second.IsLocallyStored);

                    var third = filesCollection[2];
                    Assert.Equal("Default.asp", third["value"]);
                    Assert.False(third.IsLocallyStored);

                    ConfigurationElement addElement = filesCollection.CreateElement();
                    addElement["value"] = @"home.html";
                    filesCollection.AddAt(0, addElement);

                    Assert.Equal(8, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("home.html", first["value"]);
                        // TODO: why?
                        // Assert.False(first.IsLocallyStored);
                    }

                    filesCollection.RemoveAt(4);
                    Assert.Equal(7, filesCollection.Count);

                    ConfigurationElement lastElement = filesCollection.CreateElement();
                    lastElement["value"] = @"home1.html";
                    lastElement["value"] = @"home2.html";
                    filesCollection.Add(lastElement);
                    Assert.Equal(8, filesCollection.Count);
                }

                //{
                //    var last = filesCollection[8];
                //    Assert.Equal("home2.html", last["value"]);
                //    // TODO: why?
                //    Assert.False(last.IsLocallyStored);
                //}

                {
                    // disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
                    ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
                    Assert.Equal(false, httpLoggingSection["dontLog"]);
                    Assert.Throws <FileLoadException>(() => httpLoggingSection["dontLog"] = true);
                }
                {
                    ConfigurationSection httpLoggingSection = config.GetSection(
                        "system.webServer/httpLogging",
                        "WebSite1/test");
                    // TODO:
                    //Assert.Equal(true, httpLoggingSection["dontLog"]);
                    Assert.Throws <FileLoadException>(() => httpLoggingSection["dontLog"] = false);
                }

                var errorsSection = config.GetSection("system.webServer/httpErrors");
                Assert.Equal(OverrideMode.Inherit, errorsSection.OverrideMode);
                Assert.Equal(OverrideMode.Allow, errorsSection.OverrideModeEffective);
                Assert.Equal(false, errorsSection.IsLocked);
                Assert.Equal(false, errorsSection.IsLocallyStored);

                var errorsCollection = errorsSection.GetCollection();
                Assert.Equal(9, errorsCollection.Count);

                var error = errorsCollection.CreateElement();
                var cast  = Assert.Throws <InvalidCastException>(() => error.SetAttributeValue("statusCode", "500"));
#if IIS
                Assert.Equal(Helper.IsRunningOnMono() ? "Cannot cast from source type to destination type." : "Specified cast is not valid.", cast.Message);
#else
                Assert.Equal(Helper.IsRunningOnMono() ? "Cannot cast from source type to destination type." : "Cannot convert 500 of System.String to uint.", cast.Message);
#endif

                var ex2 = Assert.Throws <COMException>(() => error["statusCode"] = 90000);
                Assert.Equal("Integer value must be between 400 and 999 inclusive\r\n", ex2.Message);

                error["statusCode"]             = 500;
                error["subStatusCode"]          = 55;
                error["prefixLanguageFilePath"] = string.Empty;

                error["responseMode"] = 0;
                error["responseMode"] = ResponseMode.Test;
#if IIS
                Assert.Equal(1, error["responseMode"]);
#else
                Assert.Equal(1L, error["responseMode"]);
#endif

                error["responseMode"] = "File";
                var ex1 = Assert.Throws <FileNotFoundException>(() => errorsCollection.Add(error));
                Assert.Equal("Filename: \r\nError: Element is missing required attributes path\r\n\r\n", ex1.Message);
                Assert.Null(ex1.FileName);

                var ex = Assert.Throws <COMException>(() => error["path"] = "");
                Assert.Equal("String must not be empty\r\n", ex.Message);

                error["path"] = "test.htm";
                errorsCollection.Add(error);

                var staticContent = config.GetSection("system.webServer/staticContent").GetChildElement("clientCache");
                staticContent["cacheControlMode"] = "DisableCache";

                ConfigurationSection requestFilteringSection =
                    config.GetSection("system.webServer/security/requestFiltering");
                ConfigurationElement           hiddenSegmentsElement    = requestFilteringSection.GetChildElement("hiddenSegments");
                ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
                Assert.Equal(8, hiddenSegmentsCollection.Count);

                var test = hiddenSegmentsCollection.CreateElement();
                test["segment"] = "test";
                hiddenSegmentsCollection.Add(test);

                var old = hiddenSegmentsCollection[0];
                hiddenSegmentsCollection.Remove(old);

                var section = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationElementCollection collection = section.GetCollection();
                //collection.Clear();
                ////collection.Delete();

                //collection = section.GetCollection();
                //Assert.Equal(0, collection.Count);

                var newElement = collection.CreateElement();
                newElement["name"] = "test";
                collection.Add(newElement);
                Assert.Equal(2, collection.Count);

                collection.Clear();
                Assert.Empty(collection);

                newElement         = collection.CreateElement();
                newElement["name"] = "test";
                collection.Add(newElement);
                Assert.Single(collection);
            }

            {
                // server config "Website1"
                var config = server.GetApplicationHostConfiguration();

                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
                Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
                Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
                Assert.Equal(false, windowsSection.IsLocked);
                Assert.True(windowsSection.IsLocallyStored);

                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.False(windowsEnabled);
            }

            {
                Configuration config = server.GetApplicationHostConfiguration();

                var anonymousSection = config.GetSection(
                    "system.webServer/security/authentication/anonymousAuthentication",
                    "WebSite2");

                // anonymousSection["userName"] = "******";
                // anonymousSection["password"] = "******";
                ConfigurationSection windowsAuthenticationSection =
                    config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite2");
                windowsAuthenticationSection["enabled"] = true;

                ConfigurationElement extendedProtectionElement =
                    windowsAuthenticationSection.GetChildElement("extendedProtection");
                extendedProtectionElement["tokenChecking"] = @"Allow";
                extendedProtectionElement["flags"]         = @"None";

                var exception = Assert.Throws <COMException>(() => extendedProtectionElement["tokenChecking"] = @"NotExist");
                Assert.Equal("Enum must be one of None, Allow, Require\r\n", exception.Message);

                exception = Assert.Throws <COMException>(() => extendedProtectionElement["flags"] = @"NotExist");
                Assert.Equal("Flags must be some combination of None, Proxy, NoServiceNameCheck, AllowDotlessSpn, ProxyCohosting\r\n", exception.Message);

                ConfigurationElementCollection extendedProtectionCollection = extendedProtectionElement.GetCollection();

                ConfigurationElement spnElement = extendedProtectionCollection.CreateElement("spn");
                spnElement["name"] = @"HTTP/www.contoso.com";
                extendedProtectionCollection.Add(spnElement);

                ConfigurationElement spnElement1 = extendedProtectionCollection.CreateElement("spn");
                spnElement1["name"] = @"HTTP/contoso.com";
                extendedProtectionCollection.Add(spnElement1);

                server.CommitChanges();

                ConfigurationSection           rulesSection    = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();
                Assert.Single(rulesCollection);

                ConfigurationElement ruleElement = rulesCollection[0];
                Assert.Equal("lextudio2", ruleElement["name"]);
#if IIS
                Assert.Equal(0, ruleElement["patternSyntax"]);
#else
                Assert.Equal(0L, ruleElement["patternSyntax"]);
#endif
                Assert.Equal(true, ruleElement["stopProcessing"]);

                ConfigurationElement matchElement = ruleElement.GetChildElement("match");
                Assert.Equal(@"(.*)", matchElement["url"]);

                ConfigurationElement actionElement = ruleElement.GetChildElement("action");
#if IIS
                Assert.Equal(1, actionElement["type"]);
#else
                Assert.Equal(1L, actionElement["type"]);
#endif
                Assert.Equal("/www/{R:0}", actionElement["url"]);
            }

            // remove application pool
            Assert.False(server.ApplicationPools.AllowsRemove);
            Assert.Equal(5, server.ApplicationPools.Count);
            server.ApplicationPools.RemoveAt(4);
            Assert.Equal(4, server.ApplicationPools.Count);

            // remove binding
            server.Sites[1].Bindings.RemoveAt(1);

            // remove site
            server.Sites.RemoveAt(4);

            // remove application
            var site1 = server.Sites[9];
            site1.Applications.RemoveAt(1);

            // remove virtual directory
            var application = server.Sites[2].Applications[0];
            application.VirtualDirectories.RemoveAt(1);

            server.CommitChanges();
        }
        internal static bool UpdateAuthenticationSettingsAndProviders(ServerManager serverManager, string siteName, string virtualPath, MultiValuedProperty <AuthenticationMethod> authMethods)
        {
            bool                 flag = false;
            string               text = siteName + virtualPath;
            Configuration        applicationHostConfiguration = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/anonymousAuthentication", text);

            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", false);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/basicAuthentication", text);
            bool flag2 = authMethods.Contains(AuthenticationMethod.Basic);

            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/clientCertificateMappingAuthentication", text);
            flag2   = authMethods.Contains(AuthenticationMethod.Certificate);
            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/digestAuthentication", text);
            flag2   = authMethods.Contains(AuthenticationMethod.Digest);
            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication", text);
            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", false);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/windowsAuthentication", text);
            bool flag3 = authMethods.Contains(AuthenticationMethod.Negotiate);
            bool flag4 = authMethods.Contains(AuthenticationMethod.Kerberos);
            bool flag5 = authMethods.Contains(AuthenticationMethod.Ntlm);
            bool flag6 = authMethods.Contains(AuthenticationMethod.LiveIdNegotiate);

            flag2 = (flag3 || flag4 || flag5 || flag6);
            flag |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            flag |= IISConfigurationUtilities.UpdateSectionAttribute(section, "useKernelMode", false);
            if (flag2)
            {
                ConfigurationElementCollection collection = section.GetCollection("providers");
                int  num   = (flag3 ? 1 : 0) + (flag4 ? 1 : 0) + (flag5 ? 1 : 0);
                bool flag7 = false;
                if (collection.Count != num)
                {
                    flag7 = true;
                }
                else
                {
                    int num2 = 0;
                    if (flag6)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "Negotiate:MSOIDSSP");
                        num2++;
                    }
                    if (flag3)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "Negotiate");
                        num2++;
                    }
                    if (flag4)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "Negotiate:Kerberos");
                        num2++;
                    }
                    if (flag5)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "NTLM");
                        num2++;
                    }
                }
                if (flag7)
                {
                    flag = true;
                    collection.Clear();
                    if (flag6)
                    {
                        ConfigurationElement configurationElement = collection.CreateElement("add");
                        configurationElement["value"] = "Negotiate:MSOIDSSP";
                        collection.Add(configurationElement);
                    }
                    if (flag3)
                    {
                        ConfigurationElement configurationElement2 = collection.CreateElement("add");
                        configurationElement2["value"] = "Negotiate";
                        collection.Add(configurationElement2);
                    }
                    if (flag4)
                    {
                        ConfigurationElement configurationElement3 = collection.CreateElement("add");
                        configurationElement3["value"] = "Negotiate:Kerberos";
                        collection.Add(configurationElement3);
                    }
                    if (flag5)
                    {
                        ConfigurationElement configurationElement4 = collection.CreateElement("add");
                        configurationElement4["value"] = "NTLM";
                        collection.Add(configurationElement4);
                    }
                }
            }
            return(flag);
        }