예제 #1
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           httpCompressionSection = config.GetSection("system.webServer/httpCompression");
            ConfigurationElementCollection staticTypesCollection  = httpCompressionSection.GetCollection("staticTypes");

            ConfigurationElement addElement = staticTypesCollection.CreateElement("add");
            addElement["mimeType"] = @"application/msword";
            addElement["enabled"]  = true;
            staticTypesCollection.Add(addElement);

            ConfigurationElement addElement1 = staticTypesCollection.CreateElement("add");
            addElement1["mimeType"] = @"application/vnd.ms-powerpoint";
            addElement1["enabled"]  = true;
            staticTypesCollection.Add(addElement1);

            ConfigurationElement addElement2 = staticTypesCollection.CreateElement("add");
            addElement2["mimeType"] = @"application/vnd.ms-excel";
            addElement2["enabled"]  = true;
            staticTypesCollection.Add(addElement2);

            serverManager.CommitChanges();
        }
    }
예제 #2
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           requestFilteringSection  = config.GetSection("system.ftpServer/security/requestFiltering", "Default Web Site");
            ConfigurationElement           fileExtensionsElement    = requestFilteringSection.GetChildElement("fileExtensions");
            ConfigurationElementCollection fileExtensionsCollection = fileExtensionsElement.GetCollection();

            ConfigurationElement addElement = fileExtensionsCollection.CreateElement("add");
            addElement["fileExtension"] = @".exe";
            addElement["allowed"]       = false;
            fileExtensionsCollection.Add(addElement);

            ConfigurationElement addElement1 = fileExtensionsCollection.CreateElement("add");
            addElement1["fileExtension"] = @".com";
            addElement1["allowed"]       = false;
            fileExtensionsCollection.Add(addElement1);

            ConfigurationElement addElement2 = fileExtensionsCollection.CreateElement("add");
            addElement2["fileExtension"] = @".cmd";
            addElement2["allowed"]       = false;
            fileExtensionsCollection.Add(addElement2);

            ConfigurationElement addElement3 = fileExtensionsCollection.CreateElement("add");
            addElement3["fileExtension"] = @".bat";
            addElement3["allowed"]       = false;
            fileExtensionsCollection.Add(addElement3);

            serverManager.CommitChanges();
        }
    }
예제 #3
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration config = serverManager.GetWebConfiguration("Default Web Site");

            ConfigurationSection requestFilteringSection = config.GetSection("system.webServer/security/requestFiltering");

            ConfigurationElementCollection denyUrlSequencesCollection = requestFilteringSection.GetCollection("denyUrlSequences");

            ConfigurationElement addElement = denyUrlSequencesCollection.CreateElement("add");
            addElement["sequence"] = @"..";
            denyUrlSequencesCollection.Add(addElement);

            ConfigurationElement addElement1 = denyUrlSequencesCollection.CreateElement("add");
            addElement1["sequence"] = @":";
            denyUrlSequencesCollection.Add(addElement1);

            ConfigurationElement addElement2 = denyUrlSequencesCollection.CreateElement("add");
            addElement2["sequence"] = @"\";
            denyUrlSequencesCollection.Add(addElement2);

            serverManager.CommitChanges();
        }
    }
예제 #4
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration config = serverManager.GetApplicationHostConfiguration();

            ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "Default Web Site");
            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);

            serverManager.CommitChanges();
        }
    }
예제 #5
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config          = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           sitesSection    = config.GetSection("system.applicationHost/sites");
            ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
            ConfigurationElement           siteElement     = FindElement(sitesCollection, "site", "name", @"Contoso");

            if (siteElement == null)
            {
                throw new InvalidOperationException("Element not found!");
            }

            ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
            ConfigurationElement           bindingElement     = bindingsCollection.CreateElement("binding");
            bindingElement["protocol"]           = @"http";
            bindingElement["bindingInformation"] = @"192.168.0.1:80:www.contoso.com";
            bindingsCollection.Add(bindingElement);

            ConfigurationElement bindingElement1 = bindingsCollection.CreateElement("binding");
            bindingElement1["protocol"]           = @"https";
            bindingElement1["bindingInformation"] = @"*:443:";
            bindingsCollection.Add(bindingElement1);

            serverManager.CommitChanges();
        }
    }
예제 #6
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager()) {
            Configuration config = serverManager.GetWebConfiguration("JavaSites");

            ConfigurationSection httpPlatformSection = config.GetSection("system.webServer/httpPlatform");
            httpPlatformSection["processPath"]   = @"c:\dev\javasites\bin\apache-tomcat-8.0.15\bin\startup.bat";
            httpPlatformSection["arguments"]     = @"";
            httpPlatformSection["stdoutLogFile"] = @"=""\\?c:\dev\javasites\log.txt";

            ConfigurationElementCollection environmentVariablesCollection = httpPlatformSection.GetCollection("environmentVariables");

            ConfigurationElement environmentVariableElement = environmentVariablesCollection.CreateElement("environmentVariable");
            environmentVariableElement["name"]  = @"JRE_HOME";
            environmentVariableElement["value"] = @"=""%programfiles%\java\jdk1.8.0_25";
            environmentVariablesCollection.Add(environmentVariableElement);

            ConfigurationElement environmentVariableElement1 = environmentVariablesCollection.CreateElement("environmentVariable");
            environmentVariableElement1["name"]  = @"CATALINA_OPTS";
            environmentVariableElement1["value"] = @"=""-Dport.http=%HTTP_PLATFORM_PORT% -Dsomeotherconfig=value";
            environmentVariablesCollection.Add(environmentVariableElement1);

            ConfigurationElement environmentVariableElement2 = environmentVariablesCollection.CreateElement("environmentVariable");
            environmentVariableElement2["name"]  = @"CATALINA_HOME";
            environmentVariableElement2["value"] = @"c:\dev\javasites\bin\apache-tomcat-8.0.15";
            environmentVariablesCollection.Add(environmentVariableElement2);

            serverManager.CommitChanges();
        }
    }
예제 #7
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           traceProviderDefinitionsSection    = config.GetSection("system.webServer/tracing/traceProviderDefinitions");
            ConfigurationElementCollection traceProviderDefinitionsCollection = traceProviderDefinitionsSection.GetCollection();

            ConfigurationElement addElement = traceProviderDefinitionsCollection.CreateElement("add");
            addElement["name"] = @"MyTraceProvider";
            addElement["guid"] = @"{00000000-0000-0000-0000-00000000000}";
            ConfigurationElementCollection areasCollection = addElement.GetCollection("areas");

            ConfigurationElement addElement1 = areasCollection.CreateElement("add");
            addElement1["name"]  = @"ProviderAreaOne";
            addElement1["value"] = 0;
            areasCollection.Add(addElement1);

            ConfigurationElement addElement2 = areasCollection.CreateElement("add");
            addElement2["name"]  = @"ProviderAreaTwo";
            addElement2["value"] = 1;
            areasCollection.Add(addElement2);

            traceProviderDefinitionsCollection.Add(addElement);
            serverManager.CommitChanges();
        }
    }
예제 #8
0
        public void Initialize()
        {
            if (_configurationProvider.IsEmulated())
            {
                return;
            }

            // Instantiate the IIS ServerManager
            using (var serverManager = new ServerManager())
            {
                // Disable idle timeout & set queue length to 5000
                serverManager.ApplicationPoolDefaults.ProcessModel.IdleTimeout = TimeSpan.Zero;
                serverManager.ApplicationPoolDefaults.QueueLength = 5000;

                // Server runtime configuration
                Microsoft.Web.Administration.Configuration applicationConfig = serverManager.GetApplicationHostConfiguration();

                // Server runtime settings
                // http://www.iis.net/configreference/system.webserver/serverruntime
                ConfigurationSection serverRuntimeSection = applicationConfig.GetSection("system.webServer/serverRuntime", "");
                serverRuntimeSection["enabled"] = true;
                serverRuntimeSection["frequentHitThreshold"]  = 1;
                serverRuntimeSection["frequentHitTimePeriod"] = TimeSpan.Parse("00:00:10");

                // Compression settings
                // http://www.iis.net/configreference/system.webserver/httpcompression
                ConfigurationSection httpCompressionSection = applicationConfig.GetSection("system.webServer/httpCompression");
                httpCompressionSection["noCompressionForHttp10"]  = false;
                httpCompressionSection["noCompressionForProxies"] = false;
                ConfigurationElementCollection dynamicTypesCollection = httpCompressionSection.GetCollection("dynamicTypes");

                ConfigurationElement addElement = dynamicTypesCollection.CreateElement("add");
                addElement["mimeType"] = @"application/json";
                addElement["enabled"]  = true;
                try
                {
                    dynamicTypesCollection.Add(addElement);
                }
                catch (COMException)
                {
                    // add json element already exists
                }

                addElement             = dynamicTypesCollection.CreateElement("add");
                addElement["mimeType"] = @"application/xml";
                addElement["enabled"]  = true;
                try
                {
                    dynamicTypesCollection.Add(addElement);
                }
                catch (COMException)
                {
                    // add xml element already exists
                }

                // Commit the changes
                serverManager.CommitChanges();
            }
        }
예제 #9
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager()) {
            Configuration config = serverManager.GetWebConfiguration("contentSite");

            ConfigurationSection corsSection = config.GetSection("system.webServer/cors");
            corsSection["enabled"]             = true;
            corsSection["failUnlistedOrigins"] = true;

            ConfigurationElementCollection corsCollection = corsSection.GetCollection();

            ConfigurationElement addElement = corsCollection.CreateElement("add");
            addElement["origin"] = @"*";
            corsCollection.Add(addElement);

            ConfigurationElement addElement1 = corsCollection.CreateElement("add");
            addElement1["origin"]           = @"https://*.microsoft.com";
            addElement1["allowCredentials"] = true;
            addElement1["maxAge"]           = 120;

            ConfigurationElement allowHeadersElement = addElement1.GetChildElement("allowHeaders");
            allowHeadersElement["allowAllRequestedHeaders"] = true;

            ConfigurationElementCollection allowHeadersCollection = allowHeadersElement.GetCollection();

            ConfigurationElement addElement2 = allowHeadersCollection.CreateElement("add");
            addElement2["header"] = @"header1";
            allowHeadersCollection.Add(addElement2);

            ConfigurationElement addElement3 = allowHeadersCollection.CreateElement("add");
            addElement3["header"] = @"header2";
            allowHeadersCollection.Add(addElement3);

            ConfigurationElementCollection allowMethodsCollection = addElement1.GetCollection("allowMethods");

            ConfigurationElement addElement4 = allowMethodsCollection.CreateElement("add");
            addElement4["method"] = @"DELETE";
            allowMethodsCollection.Add(addElement4);

            ConfigurationElementCollection exposeHeadersCollection = addElement1.GetCollection("exposeHeaders");

            ConfigurationElement addElement5 = exposeHeadersCollection.CreateElement("add");
            addElement5["header"] = @"header1";
            exposeHeadersCollection.Add(addElement5);

            ConfigurationElement addElement6 = exposeHeadersCollection.CreateElement("add");
            addElement6["header"] = @"header2";
            exposeHeadersCollection.Add(addElement6);
            corsCollection.Add(addElement1);

            ConfigurationElement addElement7 = corsCollection.CreateElement("add");
            addElement7["origin"]  = @"http://*";
            addElement7["allowed"] = false;
            corsCollection.Add(addElement7);

            serverManager.CommitChanges();
        }
    }
예제 #10
0
파일: Program.cs 프로젝트: shobuz03/mvc
        static void Main(string[] args)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration                  config          = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection           sitesSection    = config.GetSection("system.applicationHost/sites");
                ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

                ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", @"EHR");

                if (siteElement == null)
                {
                    throw new InvalidOperationException("Element not found!");
                }

                ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
                ConfigurationElement           bindingElement     = bindingsCollection.CreateElement("binding");
                bindingElement["protocol"]           = @"http";
                bindingElement["bindingInformation"] = @"*:80:ss.text";
                bindingsCollection.Add(bindingElement);
                //==============================

                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);

                // Here, directory is my install dir, and (directory)\bin\certificate.pfx is where the cert file is.
                // 1234 is the password to the certfile (exported from IIS)
                //X509Certificate2 certificate = new X509Certificate2(directory + @"\bin\certificate.pfx", "1234");

                //store.Add(certificate);

                //var binding = site.Bindings.Add("*:443:", certificate.GetCertHash(), store.Name);
                //binding.Protocol = "https";

                Binding bindingElement1 = bindingsCollection.CreateElement("binding") as Binding;
                //bindingElement1["protocol"] = @"https";
                //bindingElement1["bindingInformation"] = @"*:443:";
                if (bindingElement1 != null)
                {
                    bindingElement1.Protocol           = @"https";
                    bindingElement1.BindingInformation = @"*:443:";
                    bindingsCollection.Add(bindingElement1);
                }
                //=======================================================
                serverManager.CommitChanges();
            }
            Console.WriteLine("Success");
        }
예제 #11
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config          = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           sitesSection    = config.GetSection("system.applicationHost/sites");
            ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
            ConfigurationElement           siteElement     = FindElement(sitesCollection, "site", "name", @"Contoso");

            if (siteElement == null)
            {
                throw new InvalidOperationException("Element not found!");
            }

            ConfigurationElementCollection siteCollection     = siteElement.GetCollection();
            ConfigurationElement           applicationElement = siteCollection.CreateElement("application");

            applicationElement["path"] = @"/ShoppingCart";
            ConfigurationElementCollection applicationCollection   = applicationElement.GetCollection();
            ConfigurationElement           virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
            virtualDirectoryElement["path"]         = @"/";
            virtualDirectoryElement["physicalPath"] = @"C:\Inetpub\Contoso\ShoppingCart";
            applicationCollection.Add(virtualDirectoryElement);
            siteCollection.Add(applicationElement);

            serverManager.CommitChanges();
        }
    }
예제 #12
0
        public static void AddDefaultDocument(string siteName, string defaultDocName)
        {
            using (ServerManager mgr = new ServerManager())
            {
                Configuration                  cfg = mgr.GetWebConfiguration(siteName);
                ConfigurationSection           defaultDocumentSection = cfg.GetSection("system.webServer/defaultDocument");
                ConfigurationElement           filesElement           = defaultDocumentSection.GetChildElement("files");
                ConfigurationElementCollection filesCollection        = filesElement.GetCollection();

                foreach (ConfigurationElement elt in filesCollection)
                {
                    if (elt.Attributes["value"].Value.ToString() == defaultDocName)
                    {
                        return;
                    }
                }

                try
                {
                    ConfigurationElement docElement = filesCollection.CreateElement();
                    docElement.SetAttributeValue("value", defaultDocName);
                    filesCollection.Add(docElement);
                }
                catch (Exception) { }   //this will fail if existing

                mgr.CommitChanges();
            }
        }
예제 #13
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config          = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           sitesSection    = config.GetSection("system.applicationHost/sites");
            ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

            ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", @"ContosoSite");

            if (siteElement == null)
            {
                throw new InvalidOperationException("Element not found!");
            }


            ConfigurationElement           logFileElement         = siteElement.GetChildElement("logFile");
            ConfigurationElement           customFieldsElement    = logFileElement.GetChildElement("customFields");
            ConfigurationElementCollection customFieldsCollection = customFieldsElement.GetCollection();

            ConfigurationElement addElement = customFieldsCollection.CreateElement("add");
            addElement["logFieldName"] = @"ContosoField";
            addElement["sourceName"]   = @"ContosoSource";
            addElement["sourceType"]   = @"ServerVariable";
            customFieldsCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
예제 #14
0
        public static void AddUIModuleProvider(string name, string type)
        {
            using (ServerManager mgr = new ServerManager())
            {
                // First register the Module Provider
                Configuration adminConfig = mgr.GetAdministrationConfiguration();

                ConfigurationSection           moduleProvidersSection = adminConfig.GetSection("moduleProviders");
                ConfigurationElementCollection moduleProviders        = moduleProvidersSection.GetCollection();
                if (FindByAttribute(moduleProviders, "name", name) == null)
                {
                    ConfigurationElement moduleProvider = moduleProviders.CreateElement();
                    moduleProvider.SetAttributeValue("name", name);
                    moduleProvider.SetAttributeValue("type", type);
                    moduleProviders.Add(moduleProvider);
                }

                // Now register it so that all Sites have access to this module
                ConfigurationSection           modulesSection = adminConfig.GetSection("modules");
                ConfigurationElementCollection modules        = modulesSection.GetCollection();
                if (FindByAttribute(modules, "name", name) == null)
                {
                    ConfigurationElement module = modules.CreateElement();
                    module.SetAttributeValue("name", name);
                    modules.Add(module);
                }

                mgr.CommitChanges();
            }
        }
        private bool ConfigureIsapiRestrictions(ServerManager mgr, string physicalPath, ModeType mode)
        {
            Configuration config = mgr.GetApplicationHostConfiguration();

            ConfigurationSection           isapiCgiRestrictionSection    = config.GetSection("system.webServer/security/isapiCgiRestriction");
            ConfigurationElementCollection isapiCgiRestrictionCollection = isapiCgiRestrictionSection.GetCollection();

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

            if (mode == ModeType.Deploy && addElement == null)
            {
                base.Log.LogMessage("Allowing ISAPI restriction '{0}'...", physicalPath);
                addElement            = isapiCgiRestrictionCollection.CreateElement("add");
                addElement["path"]    = physicalPath;
                addElement["allowed"] = true;
                isapiCgiRestrictionCollection.Add(addElement);
                mgr.CommitChanges();
                base.Log.LogMessage("Allowed ISAPI restriction '{0}'.", physicalPath);
            }
            else if (mode == ModeType.Undeploy && addElement != null)
            {
                base.Log.LogMessage("Disallowing ISAPI restriction '{0}'...", physicalPath);
                isapiCgiRestrictionCollection.Remove(addElement);
                mgr.CommitChanges();
                base.Log.LogMessage("Disallowed ISAPI restriction '{0}'...", physicalPath);
            }

            return(true);
        }
예제 #16
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config  = serverManager.GetWebConfiguration(siteName);
            ConfigurationSection           section = config.GetSection("system.webServer/security/ipSecurity");
            ConfigurationElementCollection coll    = section.GetCollection();
            string ips = TextBox1.Text.Replace(" ", "");
            foreach (string ip in ConvertIP(ips))
            {
                ConfigurationElement element = coll.CreateElement("add");
                element.SetAttributeValue("ipAddress", ip);
                if (ComboBox1.SelectedValue == "Allow")
                {
                    element["allowed"] = false;
                }
                else
                {
                    element["allowed"] = true;
                }

                coll.Add(element);
                CheckBoxList1.Items.Add(ip);
            }
            serverManager.CommitChanges();
            TextBox1.Text = "";
        }
    }
예제 #17
0
    /// <summary>
    /// 添加一个新的Mime映射,如果存在,则更新
    /// </summary>
    /// <param name="siteName"></param>
    /// <param name="ext"></param>
    /// <param name="mimeType"></param>
    /// <returns></returns>
    public bool AddMimeType(string siteName, string ext, string mimeType)
    {
        Configuration confg = iis.GetWebConfiguration(siteName); //webSiteName站点名称

        ConfigurationSection section;

        section = confg.GetSection("system.webServer/staticContent");

        ConfigurationElement           filesElement    = section.GetCollection();
        ConfigurationElementCollection filesCollection = filesElement.GetCollection();

        ConfigurationElement newElement = filesCollection.CreateElement(); //新建MimeMap节点

        newElement.Attributes["fileExtension"].Value = ext;
        newElement.Attributes["mimeType"].Value      = mimeType;

        if (CheckMimeTypeIsExist(newElement, filesCollection, true))//如果存在,则更新它
        {
        }
        else
        {
            filesCollection.Add(newElement);
        }
        iis.CommitChanges();
        return(true);
    }
예제 #18
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // Add Handler to web.config to force VPP registering
            SPSite site = properties.Feature.Parent as SPSite;

            if (site != null)
            {
                using (ServerManager manager = new ServerManager())
                {
                    try
                    {
                        Configuration                  webConfig         = manager.GetWebConfiguration("SharePoint - 80");
                        ConfigurationSection           modules           = webConfig.GetSection("system.webServer/modules");
                        ConfigurationElementCollection modulesCollection = modules.GetCollection();
                        ConfigurationElement           moduleElement     = modulesCollection.CreateElement("add");
                        moduleElement["name"] = VPPRegisterHandler;
                        moduleElement["type"] = typeof(WebPartVPPRegModule).AssemblyQualifiedName;
                        modulesCollection.Add(moduleElement);
                        manager.CommitChanges();
                    }
                    catch
                    {
                    }
                }
            }
        }
예제 #19
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration        config              = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection sitesSection        = config.GetSection("system.applicationHost/sites");
            ConfigurationElement siteDefaultsElement = sitesSection.GetChildElement("siteDefaults");

            ConfigurationElement limitsElement = siteDefaultsElement.GetChildElement("limits");
            limitsElement["connectionTimeout"] = TimeSpan.Parse("00:02:00");

            ConfigurationElement logFileElement = siteDefaultsElement.GetChildElement("logFile");
            logFileElement["logFormat"] = @"W3C";
            logFileElement["directory"] = @"%SystemDrive%\inetpub\logs\LogFiles";
            logFileElement["enabled"]   = true;

            ConfigurationElement traceFailedRequestsLoggingElement = siteDefaultsElement.GetChildElement("traceFailedRequestsLogging");
            traceFailedRequestsLoggingElement["enabled"]     = true;
            traceFailedRequestsLoggingElement["directory"]   = @"%SystemDrive%\inetpub\logs\FailedReqLogFiles";
            traceFailedRequestsLoggingElement["maxLogFiles"] = 20;

            ConfigurationElementCollection bindingsCollection = siteDefaultsElement.GetCollection("bindings");
            ConfigurationElement           bindingElement     = bindingsCollection.CreateElement("binding");
            bindingElement["protocol"]           = @"http";
            bindingElement["bindingInformation"] = @"127.0.0.1:8080:";
            bindingsCollection.Add(bindingElement);

            ConfigurationElement ftpServerElement = siteDefaultsElement.GetChildElement("ftpServer");
            ftpServerElement["serverAutoStart"] = true;

            serverManager.CommitChanges();
        }
    }
예제 #20
0
        private void ConvertHeliconZooEngineToElement(HeliconZooEngine item, ConfigurationElement engine)
        {
            engine.SetAttributeValue("name", item.name);
            engine.SetAttributeValue("displayName", item.displayName);
            engine.SetAttributeValue("arguments", item.arguments);
            engine.SetAttributeValue("fullPath", item.fullPath);
            engine.SetAttributeValue("arguments", item.arguments);
            engine.SetAttributeValue("transport", item.transport);
            engine.SetAttributeValue("protocol", item.protocol);
            engine.SetAttributeValue("host", item.host);

            engine.SetAttributeValue("portLower", item.portLower);
            engine.SetAttributeValue("portUpper", item.portUpper);
            engine.SetAttributeValue("maxInstances", item.maxInstances);
            engine.SetAttributeValue("minInstances", item.minInstances);
            engine.SetAttributeValue("timeLimit", item.timeLimit);
            engine.SetAttributeValue("gracefulShutdownTimeout", item.gracefulShutdownTimeout);
            engine.SetAttributeValue("memoryLimit", item.memoryLimit);


            ConfigurationElementCollection envColl = engine.GetChildElement("environmentVariables").GetCollection();


            foreach (HeliconZooEnv env in item.environmentVariables)
            {
                ConfigurationElement envElement = envColl.CreateElement();
                envElement.SetAttributeValue("name", env.Name);
                envElement.SetAttributeValue("value", env.Value);
                envColl.Add(envElement);
            }
        }
예제 #21
0
        private static void RegisterPhpDefaultDocument(ConfigurationSection defaultDocument)
        {
            ConfigurationElement           defaultFiles    = defaultDocument.GetChildElement("files");
            ConfigurationElementCollection filesCollection = defaultFiles.GetCollection();

            // search index.php in default documents
            bool indexPhpPresent = false;

            foreach (ConfigurationElement configurationElement in filesCollection)
            {
                string value = configurationElement.GetAttributeValue("value") as string;
                if (!string.IsNullOrEmpty(value))
                {
                    if (string.Equals(value, "index.php", StringComparison.OrdinalIgnoreCase))
                    {
                        indexPhpPresent = true;
                        break;
                    }
                }
            }

            if (!indexPhpPresent)
            {
                // add index.php
                ConfigurationElement indexPhp = filesCollection.CreateElement();
                indexPhp.SetAttributeValue("value", "index.php");
                filesCollection.AddAt(0, indexPhp);
            }
        }
예제 #22
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();
            }
        }
예제 #23
0
        public void SetWebCosoleEnabled(bool enabled)
        {
            using (var srvman = new ServerManager())
            {
                Configuration appConfig = srvman.GetApplicationHostConfiguration();

                ConfigurationSection heliconZooServer = appConfig.GetSection("system.webServer/heliconZooServer");

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

                bool found = false;
                foreach (ConfigurationElement switchboardElement in switchboardCollection)
                {
                    if ((string)switchboardElement.GetAttributeValue("name") == "console")
                    {
                        SetSwitchBoardValue(switchboardElement, enabled);

                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    ConfigurationElement element = switchboardCollection.CreateElement();
                    element.SetAttributeValue("name", "console");
                    SetSwitchBoardValue(element, enabled);
                    switchboardCollection.Add(element);
                }

                srvman.CommitChanges();
            }
        }
예제 #24
0
        private void AddResponseHeaders()
        {
            if (!this.SiteExists())
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The website: {0} was not found on: {1}", this.Name, this.MachineName));
                return;
            }

            Configuration                  config = this.iisServerManager.GetWebConfiguration(this.Name);
            ConfigurationSection           httpProtocolSection     = config.GetSection("system.webServer/httpProtocol");
            ConfigurationElementCollection customHeadersCollection = httpProtocolSection.GetCollection("customHeaders");

            foreach (ITaskItem header in this.HttpResponseHeaders)
            {
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding HttpResponseHeader: {0} to: {1} on: {2}", header.ItemSpec, this.Name, this.MachineName));
                ConfigurationElement addElement = customHeadersCollection.CreateElement("add");
                addElement["name"]  = header.ItemSpec;
                addElement["value"] = header.GetMetadata("Value");
                bool headerExists = customHeadersCollection.Any(obj => obj.Attributes["name"].Value.ToString() == header.ItemSpec);
                if (!headerExists)
                {
                    customHeadersCollection.Add(addElement);
                    this.iisServerManager.CommitChanges();
                }
            }
        }
예제 #25
0
        /// <summary>
        ///     Sets the WebDAV authoring rule.
        /// </summary>
        /// <param name="webSiteName"> Name of the web site. </param>
        public void SetWebDavAuthoringRule(string webSiteName)
        {
            Trace.TraceInformation("AddWebDavAuthoringRule...");

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

                ConfigurationElementCollection authoringRulesCollection = authoringRulesSection.GetCollection();
                ConfigurationElement           addElement = authoringRulesCollection.CreateElement("add");

                addElement["users"]  = @"*";
                addElement["path"]   = @"*";
                addElement["access"] = @"Read, Write, Source";
                authoringRulesCollection.Add(addElement);

                this.ServerManager.CommitChanges();
            }
            finally
            {
                Trace.TraceInformation("AddWebDavAuthoringRule...finished.");
            }
        }
예제 #26
0
        /// <summary>
        /// Creates a WebFarm
        /// </summary>
        /// <param name="settings">The settings of the WebFarm</param>
        /// <returns>If the WebFarm was added.</returns>
        public void Create(WebFarmSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (string.IsNullOrWhiteSpace(settings.Name))
            {
                throw new ArgumentException("WebFarm name cannot be null!");
            }



            //Get Farm
            ConfigurationElementCollection farms = this.GetFarms();
            ConfigurationElement           farm  = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == settings.Name);

            if (farm != null)
            {
                _Log.Information("WebFarm '{0}' already exists.", settings.Name);

                if (settings.Overwrite)
                {
                    _Log.Information("WebFarm '{0}' will be overriden by request.", settings.Name);

                    this.Delete(settings.Name);
                }
                else
                {
                    return;
                }
            }



            //Create Farm
            farm         = farms.CreateElement("webFarm");
            farm["name"] = settings.Name;



            //Add Server
            ConfigurationElementCollection servers = farm.GetCollection();

            foreach (string server in settings.Servers)
            {
                ConfigurationElement serverElement = servers.CreateElement("server");
                serverElement["address"] = server;

                servers.Add(serverElement);

                _Log.Information("Adding server '{0}'.", server);
            }

            farms.Add(farm);
            _Server.CommitChanges();

            _Log.Information("WebFarm created.");
        }
예제 #27
0
        private void AddMimeType()
        {
            if (!this.SiteExists())
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The website: {0} was not found on: {1}", this.Name, this.MachineName));
                return;
            }

            Configuration config = this.iisServerManager.GetWebConfiguration(this.Name);

            foreach (ITaskItem mimetype in this.MimeTypes)
            {
                ConfigurationSection           staticContentSection    = config.GetSection("system.webServer/staticContent");
                ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection();
                ConfigurationElement           mimeMapElement          = staticContentCollection.CreateElement("mimeMap");
                mimeMapElement["fileExtension"] = mimetype.ItemSpec;
                mimeMapElement["mimeType"]      = mimetype.GetMetadata("Value");
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding MimeType: {0} to: {1} on: {2}", mimetype.ItemSpec, this.Name, this.MachineName));
                bool typeExists = staticContentCollection.Any(obj => obj.Attributes["fileExtension"].Value.ToString() == mimetype.ItemSpec);
                if (!typeExists)
                {
                    staticContentCollection.Add(mimeMapElement);
                    this.iisServerManager.CommitChanges();
                }
            }
        }
예제 #28
0
        /// <summary>
        /// 添加IIS 默认站点 mime类型
        /// </summary>
        /// <param name="mimeDic"></param>
        /// <returns></returns>
        public static bool AddMIMEType(Dictionary <string, string> mimeDic)
        {
            try
            {
                ServerManager server = new ServerManager();
                Configuration confg  = server.GetWebConfiguration("Default Web Site"); //webSiteName站点名称

                ConfigurationSection section;
                section = confg.GetSection("system.webServer/staticContent");     //取得MimeMap所有节点(路径为:%windir%\Windows\System32\inetsrv\config\applicationHost.config)

                ConfigurationElement           filesElement    = section.GetCollection();
                ConfigurationElementCollection filesCollection = filesElement.GetCollection();

                foreach (var key in mimeDic.Keys)
                {
                    ConfigurationElement newElement = filesCollection.CreateElement(); //新建MimeMap节点
                    newElement.Attributes["fileExtension"].Value = key;
                    newElement.Attributes["mimeType"].Value      = mimeDic[key];
                    if (!filesCollection.Contains(newElement))
                    {
                        filesCollection.Add(newElement);
                    }
                }
                server.CommitChanges();//更改
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #29
0
        /// <summary>
        /// Adds a server to the WebFarm
        /// </summary>
        /// <param name="farm">The name of the WebFarm</param>
        /// <param name="address">The address of the server</param>
        /// <returns>If the server was added.</returns>
        public bool AddServer(string farm, string address)
        {
            ConfigurationElement farmElement = this.GetFarm(farm);

            if (farmElement != null)
            {
                ConfigurationElementCollection servers = farmElement.GetCollection();
                ConfigurationElement           server  = servers.FirstOrDefault(f => f.GetAttributeValue("address").ToString() == address);

                if (server == null)
                {
                    ConfigurationElement serverElement = servers.CreateElement("server");
                    serverElement["address"] = server;

                    servers.Add(serverElement);
                    _Server.CommitChanges();

                    _Log.Information("Adding server '{0}'.", address);
                    return(true);
                }
                else
                {
                    _Log.Information("The server '{0}' already exists.", address);
                    return(false);
                }
            }

            return(false);
        }
예제 #30
0
파일: WebDav.cs 프로젝트: pasamsin/SolidCP
        public void CreateWebDavRule(string organizationId, string folder, WebDavFolderRule rule)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetApplicationHostConfiguration();

                ConfigurationSection authoringRulesSection = config.GetSection("system.webServer/webdav/authoringRules", string.Format("{0}/{1}/{2}", _Setting.Domain, organizationId, folder));

                ConfigurationElementCollection authoringRulesCollection = authoringRulesSection.GetCollection();

                ConfigurationElement addElement = authoringRulesCollection.CreateElement("add");

                if (rule.Users.Any())
                {
                    addElement["users"] = string.Join(", ", rule.Users.Select(x => x.ToString()).ToArray());
                }

                if (rule.Roles.Any())
                {
                    addElement["roles"] = string.Join(", ", rule.Roles.Select(x => x.ToString()).ToArray());
                }

                if (rule.Pathes.Any())
                {
                    addElement["path"] = string.Join(", ", rule.Pathes.ToArray());
                }

                addElement["access"] = rule.AccessRights;
                authoringRulesCollection.Add(addElement);

                serverManager.CommitChanges();
            }
        }
		private ConfigurationElement CreateHttpError(ConfigurationElementCollection collection, HttpError error, WebVirtualDirectory virtualDir)
		{
			// Skip elements either empty or with empty data
			if (error == null || String.IsNullOrEmpty(error.ErrorContent))
				return null;
			
			// Create new custom error
			ConfigurationElement error2Add = collection.CreateElement("error");
			
			if (!FillConfigurationElementWithData(error2Add, error, virtualDir))
				return null;
			//
			return error2Add;
		}
		private ConfigurationElement CreateDefaultDocument(ConfigurationElementCollection collection, string valueStr)
		{
			if (valueStr == null)
				return null;
			//
			valueStr = valueStr.Trim();
			//
			if (String.IsNullOrEmpty(valueStr))
				return null;

			//
			ConfigurationElement file2Add = collection.CreateElement("add");
			file2Add.SetAttributeValue(ValueAttribute, valueStr);
			//
			return file2Add;
		}
		private ConfigurationElement CreateCustomHttpHeader(ConfigurationElementCollection collection, HttpHeader header)
		{
			// Skip elements either empty or with empty data
			if (header == null || String.IsNullOrEmpty(header.Key))
				return null;

			//
			ConfigurationElement header2Add = collection.CreateElement("add");
			//
			FillConfigurationElementWithData(header2Add, header);
			//
			return header2Add;
		}
 private static void AddServerVariable(ConfigurationElementCollection variablesCollection, string name,
     string value)
 {
     var variableElement = variablesCollection.CreateElement("set");
     variableElement["name"] = name;
     variableElement["value"] = value;
     variablesCollection.Add(variableElement);
 }
		private ConfigurationElement CreateMimeMap(ConfigurationElementCollection collection, MimeMap mapping)
		{
			if (mapping == null
				|| String.IsNullOrEmpty(mapping.MimeType)
					|| String.IsNullOrEmpty(mapping.Extension))
			{
				return null;
			}
			//
			var item2Add = collection.CreateElement("mimeMap");
			//
			FillConfigurationElementWithData(item2Add, mapping);
			//
			return item2Add;
		}