Beispiel #1
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", @"ftp.example.com");
            if (siteElement == null)
            {
                throw new InvalidOperationException("Element not found!");
            }

            ConfigurationElement           ftpServerElement      = siteElement.GetChildElement("ftpServer");
            ConfigurationElement           customFeaturesElement = ftpServerElement.GetChildElement("customFeatures");
            ConfigurationElementCollection providersCollection   = customFeaturesElement.GetCollection("providers");

            ConfigurationElement addElement = providersCollection.CreateElement("add");
            addElement["name"]    = @"CustomLoggingModule";
            addElement["enabled"] = true;
            providersCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
Beispiel #2
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
                    {
                    }
                }
            }
        }
Beispiel #3
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;
            }
        }
Beispiel #4
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetWebConfiguration("Contoso");
            ConfigurationSection           traceFailedRequestsSection    = config.GetSection("system.webServer/tracing/traceFailedRequests");
            ConfigurationElementCollection traceFailedRequestsCollection = traceFailedRequestsSection.GetCollection();

            ConfigurationElement addElement = traceFailedRequestsCollection.CreateElement("add");
            addElement["path"] = @"*.aspx";

            ConfigurationElementCollection traceAreasCollection = addElement.GetCollection("traceAreas");
            ConfigurationElement           addElement1          = traceAreasCollection.CreateElement("add");
            addElement1["provider"]  = @"ASPNET";
            addElement1["areas"]     = @"Infrastructure,Module,Page,AppServices";
            addElement1["verbosity"] = @"Verbose";
            traceAreasCollection.Add(addElement1);

            ConfigurationElement failureDefinitionsElement = addElement.GetChildElement("failureDefinitions");
            failureDefinitionsElement["statusCodes"] = @"500";
            traceFailedRequestsCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
Beispiel #5
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();
            }
        }
Beispiel #6
0
 private static void AddEnvironmentVariableToAppPool(ConfigurationElementCollection envCollection, string key, string value)
 {
     var addElement = envCollection.CreateElement("add");
     addElement["name"] = key;
     addElement["value"] = value;
     envCollection.Add(addElement);
 }
Beispiel #7
0
        // GET api/values
        public IEnumerable <string> Get()
        {
            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", @"testsite");

                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:test2.site";
                bindingsCollection.Add(bindingElement);

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

                serverManager.CommitChanges();
            }
            return(new string[] { "value1", "value2" });
        }
Beispiel #8
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();
            }
        }
Beispiel #9
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration config = serverManager.GetApplicationHostConfiguration();

            ConfigurationSection iisClientCertificateMappingAuthenticationSection = config.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication", "Default Web Site");
            iisClientCertificateMappingAuthenticationSection["enabled"] = true;
            iisClientCertificateMappingAuthenticationSection["manyToOneCertificateMappingsEnabled"] = true;

            ConfigurationElementCollection manyToOneMappingsCollection = iisClientCertificateMappingAuthenticationSection.GetCollection("manyToOneMappings");
            ConfigurationElement           addElement = manyToOneMappingsCollection.CreateElement("add");
            addElement["name"]           = @"Contoso Employees";
            addElement["enabled"]        = true;
            addElement["permissionMode"] = @"Allow";
            addElement["userName"]       = @"Username";
            addElement["password"]       = @"Password";

            ConfigurationElementCollection rulesCollection = addElement.GetCollection("rules");
            ConfigurationElement           addElement1     = rulesCollection.CreateElement("add");
            addElement1["certificateField"]     = @"Subject";
            addElement1["certificateSubField"]  = @"O";
            addElement1["matchCriteria"]        = @"Contoso";
            addElement1["compareCaseSensitive"] = true;
            rulesCollection.Add(addElement1);
            manyToOneMappingsCollection.Add(addElement);

            ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", "Default Web Site");
            accessSection["sslFlags"] = @"Ssl, SslNegotiateCert";

            serverManager.CommitChanges();
        }
    }
Beispiel #10
0
        static void Main(string[] args)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration                  configuration   = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection           sitesSection    = configuration.GetSection("system.applicationHost/sites");
                ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

                ConfigurationElement siteElement = sitesCollection.CreateElement("site");
                siteElement["name"]            = @"testsite";
                siteElement["id"]              = 14;
                siteElement["serverAutoStart"] = true;

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

                ConfigurationElementCollection siteCollection     = siteElement.GetCollection();
                ConfigurationElement           applicationElement = siteCollection.CreateElement("application");
                applicationElement["path"] = @"/";
                ConfigurationElementCollection applicationCollection   = applicationElement.GetCollection();
                ConfigurationElement           virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
                virtualDirectoryElement["path"]         = @"/";
                virtualDirectoryElement["physicalPath"] = @"C:\site\web";
                applicationCollection.Add(virtualDirectoryElement);
                siteCollection.Add(applicationElement);
                sitesCollection.Add(siteElement);

                serverManager.CommitChanges();
            }
        }
        internal static bool ConfigureApplication(ServerManager serverManager, string webSiteName, string applicationPoolName, string virtualPath, string physicalPath, out bool recycleAppPool)
        {
            bool flag = true;

            recycleAppPool = false;
            Configuration                  applicationHostConfiguration = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           section               = applicationHostConfiguration.GetSection("system.applicationHost/sites");
            ConfigurationElementCollection collection            = section.GetCollection();
            ConfigurationElement           configurationElement  = IISConfigurationUtilities.FindElement(collection, "site", "name", webSiteName);
            ConfigurationElementCollection collection2           = configurationElement.GetCollection();
            ConfigurationElement           configurationElement2 = IISConfigurationUtilities.FindElement(collection2, "application", "path", virtualPath);

            if (configurationElement2 == null)
            {
                configurationElement2         = collection2.CreateElement("application");
                configurationElement2["path"] = virtualPath;
                collection2.Add(configurationElement2);
                flag = true;
            }
            recycleAppPool |= IISConfigurationUtilities.UpdateElementAttribute(configurationElement2, "applicationPool", applicationPoolName);
            flag           |= recycleAppPool;
            ConfigurationElementCollection collection3           = configurationElement2.GetCollection();
            ConfigurationElement           configurationElement3 = IISConfigurationUtilities.FindElement(collection3, "virtualDirectory", "path", "/");

            if (configurationElement3 == null)
            {
                configurationElement3         = collection3.CreateElement("virtualDirectory");
                configurationElement3["path"] = "/";
                collection3.Add(configurationElement3);
                flag = true;
            }
            return(flag | IISConfigurationUtilities.UpdateElementAttribute(configurationElement3, "physicalPath", physicalPath));
        }
Beispiel #12
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           providerDefinitionsSection    = config.GetSection("system.ftpServer/providerDefinitions");
            ConfigurationElementCollection providerDefinitionsCollection = providerDefinitionsSection.GetCollection();

            ConfigurationElement addElement = providerDefinitionsCollection.CreateElement("add");
            addElement["name"] = @"FtpXmlAuthentication";
            addElement["type"] = @"FtpXmlAuthentication, FtpXmlAuthentication, version=1.0.0.0, Culture=neutral, PublicKeyToken=426f62526f636b73";
            providerDefinitionsCollection.Add(addElement);

            ConfigurationElementCollection activationCollection = providerDefinitionsSection.GetCollection("activation");
            ConfigurationElement           providerDataElement  = activationCollection.CreateElement("providerData");
            providerDataElement["name"] = @"FtpXmlAuthentication";

            ConfigurationElementCollection providerDataCollection = providerDataElement.GetCollection();
            ConfigurationElement           addElement1            = providerDataCollection.CreateElement("add");
            addElement1["key"]   = @"xmlFileName";
            addElement1["value"] = @"C:\Inetpub\wwwroot\App_Data\Users.xml";
            providerDataCollection.Add(addElement1);
            activationCollection.Add(providerDataElement);

            serverManager.CommitChanges();
        }
    }
        public static void AddOrUpdateConfigurationElementInCollection(this ConfigurationElementCollection a, string name, string value)
        {
            // We want each site to have it's own PHP.ini contained in the site
            // itself, so use the PHPRC environment variable.
            ConfigurationElement elemPHPRC = null;

            foreach (var evv in a)
            {
                if (evv.HasValue("name", name))
                {
                    elemPHPRC = evv;
                    break;
                }
            }

            bool addElemPHPRC = false;

            if (elemPHPRC == null)
            {
                elemPHPRC    = a.CreateElement("environmentVariable");
                addElemPHPRC = true;
            }

            elemPHPRC.SetAttributeValue("name", name);
            elemPHPRC.SetAttributeValue("value", value);

            if (addElemPHPRC)
            {
                a.Add(elemPHPRC);
            }
        }
        public bool AddModule(string moduleName, string image, string preCondition)
        {
            RemoveModule(moduleName);

            bool result = true;

            using (ServerManager serverManager = GetServerManager())
            {
                Configuration                  config = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection           globalModulesSection    = config.GetSection("system.webServer/globalModules");
                ConfigurationElementCollection globalModulesCollection = globalModulesSection.GetCollection();

                ConfigurationElement globalModule = globalModulesCollection.CreateElement("add");
                globalModule["name"]  = moduleName;
                globalModule["image"] = image;
                if (preCondition != null)
                {
                    globalModule["preCondition"] = preCondition;
                }
                globalModulesCollection.Add(globalModule);

                ConfigurationSection           modulesSection    = config.GetSection("system.webServer/modules");
                ConfigurationElementCollection modulesCollection = modulesSection.GetCollection();
                ConfigurationElement           module            = modulesCollection.CreateElement("add");
                module["name"] = moduleName;
                modulesCollection.Add(module);

                serverManager.CommitChanges();
            }
            return(result);
        }
Beispiel #15
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", @"Default Web Site");
            if (siteElement == null)
            {
                throw new InvalidOperationException("Element not found!");
            }

            ConfigurationElement           ftpServerElement           = siteElement.GetChildElement("ftpServer");
            ConfigurationElement           securityElement            = ftpServerElement.GetChildElement("security");
            ConfigurationElement           commandFilteringElement    = securityElement.GetChildElement("commandFiltering");
            ConfigurationElementCollection commandFilteringCollection = commandFilteringElement.GetCollection();

            commandFilteringElement["allowUnlisted"] = true;

            ConfigurationElement addElement = commandFilteringCollection.CreateElement("add");
            addElement["command"] = @"SYST";
            addElement["allowed"] = false;
            commandFilteringCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
Beispiel #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 = "";
        }
    }
Beispiel #17
0
        public void CreateVirtualDirectory(string sitename, string parentFolder, string virtualName, string path)
        {
            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", sitename);

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

                ConfigurationElementCollection siteCollection = siteElement.GetCollection();
                //siteCollection.Clear();
                ConfigurationElement applicationElement = FindElement(siteCollection, "application", "path", parentFolder);

                //applicationElement["path"] = @"/" ;
                ConfigurationElementCollection applicationCollection = applicationElement.GetCollection();

                ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
                virtualDirectoryElement["path"]         = @"/" + virtualName;
                virtualDirectoryElement["physicalPath"] = path;

                applicationCollection.Add(virtualDirectoryElement);
                // siteCollection.Add(applicationElement);

                serverManager.CommitChanges();
            }
        }
Beispiel #18
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();
        }
    }
Beispiel #19
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);
    }
        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();
                }
            }
        }
        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();
                }
            }
        }
        public void ConfigureCustomLogging(string siteName, string appName, int statusCode, int subStatusCode, string path)
        {
            using (ServerManager serverManager = GetServerManager())
            {
                Configuration        config            = serverManager.GetWebConfiguration(siteName, appName);
                ConfigurationSection httpErrorsSection = config.GetSection("system.webServer/httpErrors");
                httpErrorsSection["errorMode"] = @"Custom";

                ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection();
                ConfigurationElement           errorElement         = FindElement(httpErrorsCollection, "error", "statusCode", statusCode.ToString(), "subStatusCode", subStatusCode.ToString());
                if (errorElement != null)
                {
                    httpErrorsCollection.Remove(errorElement);
                }

                ConfigurationElement errorElement2 = httpErrorsCollection.CreateElement("error");
                errorElement2["statusCode"]    = statusCode;
                errorElement2["subStatusCode"] = subStatusCode;
                errorElement2["path"]          = path;
                httpErrorsCollection.Add(errorElement2);

                serverManager.CommitChanges();
            }
            Thread.Sleep(500);
        }
Beispiel #23
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);
        }
Beispiel #24
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.");
        }
Beispiel #25
0
        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();
            }
        }
Beispiel #26
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);
            }
        }
Beispiel #27
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();
        }
    }
        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);
        }
Beispiel #29
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();
        }
    }
Beispiel #30
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();
        }
    }
 private static void AddServerVariable(ConfigurationElementCollection variablesCollection, string name,
     string value)
 {
     var variableElement = variablesCollection.CreateElement("set");
     variableElement["name"] = name;
     variableElement["value"] = value;
     variablesCollection.Add(variableElement);
 }