예제 #1
0
 private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
 {
     foreach (var element in collection)
     {
         if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
         {
             var matches = true;
             for (var i = 0; i < keyValues.Length; i += 2)
             {
                 var o = element.GetAttributeValue(keyValues[i]);
                 string value = null;
                 if (o != null)
                 {
                     value = o.ToString();
                 }
                 if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
                 {
                     matches = false;
                     break;
                 }
             }
             if (matches)
             {
                 return element;
             }
         }
     }
     return null;
 }
 public ProviderSettingsCollection(ConfigurationElementCollection collection)
     : base(collection.ElementTagName, collection.Schema, collection.ParentElement, collection.InnerEntity, null)
 {
     foreach (ConfigurationElement element in collection)
     {
         InternalAdd(new ProviderSettings(element, null, null, element.ParentElement, element.InnerEntity));
     }
 }
 /// <summary>
 /// Adds (Creates an instance) the filters that are declared in the configuration
 /// </summary>
 /// <param name="filters">the filter list to add the integration filters to</param>
 protected virtual void AddFiltersFromConfig(ConfigurationElementCollection<FilterElement> filterElementList, List<Filter> filters)
 {
     foreach (var filterElement in filterElementList)
     {
         var f = Activator.CreateInstance(filterElement.Type);
         if (!(f is NearForumsActionFilter))
         {
             throw new NotSupportedException("Registering action filters of type '" + filterElement.Type.FullName + "' is not supported. Action filter extensions must inherit from NearForumsActionFilter.");
         }
         filters.Add(new Filter(f, FilterScope.Action, null));
     }
 }
예제 #4
0
        /// <summary> 
        /// Helper method to find an element based on an attribute 
        /// </summary> 
        private static ConfigurationElement FindByAttribute(ConfigurationElementCollection collection, string attributeName, string value)
        {
            foreach (ConfigurationElement element in collection)
            {
                if (String.Equals((string)element.GetAttribute(attributeName).Value, value, StringComparison.OrdinalIgnoreCase))
                {
                    return element;
                }
            }

            return null;
        }
예제 #5
0
        internal static IEnumerable <string> GetServersFromConfiguration(string farmName)
        {
            List <string> serversList = new List <string>();

            using (ServerManager manager = new ServerManager()) {
                ConfigurationElementCollection webFarmsConfiguration = GetWebFarmsConfiguration(manager);
                ConfigurationElement           webFarm = GetWebFarmConfiguration(webFarmsConfiguration, farmName);
                if (webFarm != null)
                {
                    ConfigurationElementCollection servers = webFarm.GetCollection();
                    foreach (ConfigurationElement serverConfiguration in servers)
                    {
                        serversList.Add(ConfigurationElementUtils.GetAttributValue(serverConfiguration, "address"));
                    }
                }
            }
            return(serversList);
        }
예제 #6
0
        /// <summary>
        /// Removes the specified UI Module by name
        /// </summary>
        public static void RemoveUIModuleProvider(string name)
        {
            using (ServerManager mgr = new ServerManager())
            {
                Configuration adminConfig = mgr.GetAdministrationConfiguration();

                // now remove the ModuleProvider
                ConfigurationSection           moduleProvidersSection = adminConfig.GetSection("moduleProviders");
                ConfigurationElementCollection moduleProviders        = moduleProvidersSection.GetCollection();
                ConfigurationElement           moduleProvider         = FindByAttribute(moduleProviders, "name", name);
                if (moduleProvider != null)
                {
                    moduleProviders.Remove(moduleProvider);
                }

                mgr.CommitChanges();
            }
        }
        private ConfigurationElement CreateHttpError(ConfigurationElementCollection collection, HttpError error, WebAppVirtualDirectory 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);
        }
예제 #8
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           httpCompressionSection    = config.GetSection("system.webServer/httpCompression");
            ConfigurationElementCollection httpCompressionCollection = httpCompressionSection.GetCollection();

            ConfigurationElement schemeElement = httpCompressionCollection.CreateElement("scheme");
            schemeElement["name"] = @"deflate";
            schemeElement["doStaticCompression"]  = true;
            schemeElement["doDynamicCompression"] = true;
            schemeElement["dll"] = @"%Windir%\system32\inetsrv\gzip.dll";
            httpCompressionCollection.Add(schemeElement);

            serverManager.CommitChanges();
        }
    }
예제 #9
0
        public static void DeleteWebFarm(string name)
        {
            using (var serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetApplicationHostConfiguration();

                ConfigurationSection           section = config.GetSection("webFarms");
                ConfigurationElementCollection farms   = section.GetCollection();

                ConfigurationElement farm = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);

                if (farm != null)
                {
                    farms.Remove(farm);
                    serverManager.CommitChanges();
                }
            }
        }
 private ConfigurationElement FindHandlerAction(ConfigurationElementCollection handlers, string path, string processor)
 {
     foreach (ConfigurationElement action in handlers)
     {
         // match handler path mapping
         bool pathMatches = (String.Compare((string)action["path"], path, true) == 0) ||
                            (String.Compare((string)action["path"], String.Format("*{0}", path), true) == 0);
         // match handler processor
         bool processorMatches = (String.Compare(FileUtils.EvaluateSystemVariables((string)action["scriptProcessor"]),
                                                 FileUtils.EvaluateSystemVariables(processor), true) == 0);
         // return handler action when match is exact
         if (pathMatches && processorMatches)
         {
             return(action);
         }
     }
     //
     return(null);
 }
예제 #11
0
        private static bool findBlockIp(String ip, String site)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration                  config               = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection           ipSecuritySection    = config.GetSection("system.webServer/security/ipSecurity", site);
                ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();

                foreach (var item1 in ipSecurityCollection)
                {
                    if ((String)item1["ipAddress"] == ip)
                    {
                        return(true);
                    }
                }

                return(false);
            }
        }
예제 #12
0
        /// <summary>
        /// Updates the configuration file to match the model
        /// </summary>
        /// <param name="tcpHostingConfiguration">The configuration file to update</param>
        public static void WriteConfiguration(Configuration tcpHostingConfiguration)
        {
            ConfigurationSectionGroup sg = tcpHostingConfiguration.SectionGroups[ServiceModelTag];
            ConfigurationSection      cs = sg.Sections[NetTcpTag];

            //avoid taking a dependency on System.ServiceModel,
            //use reflection to get the property collections we need.
            System.Reflection.PropertyInfo pi = cs.GetType().GetProperty(AllowAccountsTag);
            ConfigurationElementCollection allowedAccounts = (ConfigurationElementCollection)pi.GetValue(cs, null);

            //enumerates over System.ServiceModel.Activation.Configuration.SecurityIdentifierElement
            List <String> currentSids = new List <string>();

            foreach (ConfigurationElement securityIdentiferElement in allowedAccounts)
            {
                SecurityIdentifier sid = (SecurityIdentifier)securityIdentiferElement.GetType().GetProperty(SecurityIdentifierTag).GetValue(securityIdentiferElement, null);
                if (!currentSids.Contains(sid.ToString()))
                {
                    currentSids.Add(sid.ToString());
                }
            }

            //now add the sids that are missing
            //add, contains, remove
            SecurityIdentifierCollectionHelperClass helper = new SecurityIdentifierCollectionHelperClass(allowedAccounts);

            foreach (String sid in AllowAccounts)
            {
                if (!currentSids.Contains(sid))
                {
                    helper.Add(sid);
                }
                else
                {
                    currentSids.Remove(sid);
                }
            }

            foreach (String sid in currentSids)
            {
                helper.Remove(sid);
            }
        }
예제 #13
0
 private static void Main()
 {
     using (ServerManager serverManager = new ServerManager())
     {
         Configuration                  config = serverManager.GetApplicationHostConfiguration();
         ConfigurationSection           applicationPoolsSection    = config.GetSection("system.applicationHost/applicationPools");
         ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();
         ConfigurationElement           addElement = applicationPoolsCollection.CreateElement("add");
         addElement["name"] = @"Contoso";
         ConfigurationElement           recyclingElement       = addElement.GetChildElement("recycling");
         ConfigurationElement           periodicRestartElement = recyclingElement.GetChildElement("periodicRestart");
         ConfigurationElementCollection scheduleCollection     = periodicRestartElement.GetCollection("schedule");
         ConfigurationElement           addElement1            = scheduleCollection.CreateElement("add");
         addElement1["value"] = TimeSpan.Parse("03:00:00");
         scheduleCollection.Add(addElement1);
         applicationPoolsCollection.Add(addElement);
         serverManager.CommitChanges();
     }
 }
예제 #14
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager()) {
            Configuration config = serverManager.GetWebConfiguration("Default Web Site");

            ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect");
            httpRedirectSection["enabled"]            = true;
            httpRedirectSection["exactDestination"]   = true;
            httpRedirectSection["httpResponseStatus"] = @"Found";

            ConfigurationElementCollection httpRedirectCollection = httpRedirectSection.GetCollection();
            ConfigurationElement           addElement             = httpRedirectCollection.CreateElement("add");
            addElement["wildcard"]    = @"*.asp";
            addElement["destination"] = @"/default.htm";
            httpRedirectCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
예제 #15
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");
            ConfigurationElementCollection hiddenSegmentsCollection = requestFilteringSection.GetCollection("hiddenSegments");

            ConfigurationElement addElement = hiddenSegmentsCollection.CreateElement("add");
            addElement["segment"] = @"bin";
            hiddenSegmentsCollection.Add(addElement);

            ConfigurationElement addElement1 = hiddenSegmentsCollection.CreateElement("add");
            addElement1["segment"] = @"App_Code";
            hiddenSegmentsCollection.Add(addElement1);

            serverManager.CommitChanges();
        }
    }
예제 #16
0
 private static void Main()
 {
     using (ServerManager serverManager = new ServerManager()) {
         Configuration                  config = serverManager.GetApplicationHostConfiguration();
         ConfigurationSection           applicationPoolsSection    = config.GetSection("system.applicationHost/applicationPools");
         ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();
         ConfigurationElement           addElement = FindElement(applicationPoolsCollection, "add", "name", @"Contoso");
         if (addElement == null)
         {
             throw new InvalidOperationException("Element not found!");
         }
         ConfigurationElementCollection environmentVariablesCollection = addElement.GetCollection("environmentVariables");
         ConfigurationElement           addElement1 = environmentVariablesCollection.CreateElement("add");
         addElement1["name"]  = @"foo";
         addElement1["value"] = @"bar";
         environmentVariablesCollection.Add(addElement1);
         serverManager.CommitChanges();
     }
 }
예제 #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serverManager"></param>
        /// <param name="poolName"></param>
        /// <returns>SpecificUser || LocalSystem || LocalService || NetworkService || ApplicationPoolIdentity</returns>
        public static string FindIdentityTypeForPool(ServerManager serverManager, string poolName)
        {
            Configuration config = serverManager.GetApplicationHostConfiguration();

            ConfigurationSection applicationPoolsSection = config.GetSection("system.applicationHost/applicationPools");

            ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();

            ConfigurationElement addElement = FindElement(applicationPoolsCollection, "add", "name", poolName);

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

            ConfigurationElement processModelElement = addElement.GetChildElement("processModel");

            return((string)processModelElement["identityType"]);
        }
예제 #18
0
        private void actAdd_Execute(object sender, EventArgs e)
        {
            var dialog = new FarmWizard();

            if (dialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            var item = new ListViewItem(new[]
            {
                dialog.FarmName,
                "Online"
            })
            {
                Tag = dialog.Servers, ImageIndex = 0, StateImageIndex = 0
            };

            listView1.Items.Add(item);
            var config = _server.GetApplicationHostConfiguration();
            ConfigurationSection           webFarmsSection    = config.GetSection("webFarms");
            ConfigurationElementCollection webFarmsCollection = webFarmsSection.GetCollection();
            ConfigurationElement           webFarmElement     = webFarmsCollection.CreateElement("webFarm");

            webFarmElement["name"] = dialog.FarmName;
            ConfigurationElementCollection webFarmCollection = webFarmElement.GetCollection();

            foreach (var server in dialog.Servers)
            {
                ConfigurationElement serverElement = webFarmCollection.CreateElement("server");
                serverElement["address"] = server.Name;
                serverElement["enabled"] = true;

                ConfigurationElement applicationRequestRoutingElement = serverElement.GetChildElement("applicationRequestRouting");
                applicationRequestRoutingElement["weight"]    = server.Weight;
                applicationRequestRoutingElement["httpPort"]  = server.HttpPort;
                applicationRequestRoutingElement["httpsPort"] = server.HttpsPort;
                webFarmCollection.Add(serverElement);
            }

            webFarmsCollection.Add(webFarmElement);
            _form.AddFarmNode(dialog.FarmName, dialog.Servers);
        }
예제 #19
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");

            ConfigurationElement fileExtensionsElement = requestFilteringSection.GetChildElement("fileExtensions");
            fileExtensionsElement["applyToWebDAV"] = false;
            ConfigurationElementCollection fileExtensionsCollection = fileExtensionsElement.GetCollection();

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

            serverManager.CommitChanges();
        }
    }
예제 #20
0
        public DataTable ConvertToDataTable(ConfigurationElementCollection ces)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Ext", typeof(string));
            dt.Columns.Add("Type", typeof(string));
            int i = 1;

            foreach (ConfigurationElement ce in ces)
            {
                DataRow dr = dt.NewRow();
                dr["ID"]   = i++;
                dr["Ext"]  = ce.Attributes["fileExtension"].Value;
                dr["Type"] = ce.Attributes["mimeType"].Value;
                dt.Rows.Add(dr);
            }
            return(dt);
        }
예제 #21
0
        /// <summary>
        /// Delete an WebFarm
        /// </summary>
        /// <param name="name">The name of the WebFarm</param>
        /// <returns>If the WebFarm was deleted.</returns>
        public bool Delete(string name)
        {
            ConfigurationElementCollection farms = this.GetFarms();
            ConfigurationElement           farm  = farms.FirstOrDefault(f => f.GetAttributeValue("name").ToString() == name);

            if (farm != null)
            {
                farms.Remove(farm);
                _Server.CommitChanges();

                _Log.Information("WebFarm deleted.");
                return(true);
            }
            else
            {
                _Log.Information("The webfarm '{0}' does not exists.", name);
                return(false);
            }
        }
예제 #22
0
        public virtual void EditItem(T newItem)
        {
            var service = (IConfigurationService)this.GetService(typeof(IConfigurationService));

            if (newItem.Flag != "Local")
            {
                ConfigurationElementCollection collection = this.GetCollection(service);
                collection.Remove(newItem.Element);
                newItem.AppendTo(collection);
                newItem.Flag = "Local";
            }
            else
            {
                newItem.Apply();
            }

            service.ServerManager.CommitChanges();
            this.OnSettingsSaved();
        }
예제 #23
0
파일: IISHelper.cs 프로젝트: xtinker/MyGit
        public static bool CheckRootScriptIsHave(string scriptName)
        {
            ServerManager                  serverManager = new ServerManager();
            Configuration                  applicationHostConfiguration = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           section    = applicationHostConfiguration.GetSection("system.webServer/handlers");
            ConfigurationElementCollection collection = section.GetCollection();
            bool result;

            foreach (ConfigurationElement current in collection)
            {
                if (scriptName.ToLower() == current.GetAttributeValue("name").ToString().ToLower())
                {
                    result = true;
                    return(result);
                }
            }
            result = false;
            return(result);
        }
예제 #24
0
        public void GenerateRule(string domainName)
        {
            string sectionPath = "system.webServer/rewrite/rules";

            if (ManagementUnit.ConfigurationPath.PathType == ConfigurationPathType.Server)
            {
                sectionPath = "system.webServer/rewrite/globalRules";
            }

            ConfigurationSection           rulesSection    = ManagementUnit.Configuration.GetSection(sectionPath);
            ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();

            ConfigurationElement ruleElement = rulesCollection.CreateElement("rule");

            ruleElement["name"]           = @"Canonical domain for " + domainName;
            ruleElement["patternSyntax"]  = @"Wildcard";
            ruleElement["stopProcessing"] = true;

            ConfigurationElement matchElement = ruleElement.GetChildElement("match");

            matchElement["url"] = @"*";

            ConfigurationElement conditionsElement = ruleElement.GetChildElement("conditions");

            ConfigurationElementCollection conditionsCollection = conditionsElement.GetCollection();

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

            addElement["input"]   = @"{HTTP_HOST}";
            addElement["negate"]  = true;
            addElement["pattern"] = domainName;
            conditionsCollection.Add(addElement);

            ConfigurationElement actionElement = ruleElement.GetChildElement("action");

            actionElement["type"] = @"Redirect";
            actionElement["url"]  = @"http://" + domainName + @"/{R:1}";
            actionElement["appendQueryString"] = true;
            rulesCollection.Add(ruleElement);

            ManagementUnit.Update();
        }
예제 #25
0
        //给网站添加ftp
        public void createFtpSite(string ftpSiteName, string ftpLocalPath)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                // Add FTP publishing to Default Web Site
                Site site = serverManager.Sites["Default Web Site"];

                // Add an FTP Binding to the Site
                site.Bindings.Add(@"*:21:", @"ftp");

                ConfigurationElement ftpServerElement = site.GetChildElement("ftpServer");

                ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");



                // Enable SSL
                ConfigurationElement sslElement = securityElement.GetChildElement("ssl");
                sslElement["serverCertHash"]       = @"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
                sslElement["controlChannelPolicy"] = @"SslRequire";
                sslElement["dataChannelPolicy"]    = @"SslRequire";

                // Enable Basic Authentication
                ConfigurationElement authenticationElement      = securityElement.GetChildElement("authentication");
                ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
                basicAuthenticationElement["enabled"] = true;


                // Add Authorization Rules
                Configuration                  appHost            = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection           authorization      = appHost.GetSection("system.ftpServer/security/authorization", site.Name);
                ConfigurationElementCollection authorizationRules = authorization.GetCollection();
                ConfigurationElement           authElement        = authorizationRules.CreateElement();
                authElement["accessType"]  = "Allow";
                authElement["users"]       = "bdc";
                authElement["permissions"] = "Read";
                authorizationRules.Add(authElement);


                serverManager.CommitChanges();
            }
        }
예제 #26
0
        /// <summary>
        /// Add a list of allowed server variables
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="variables">List of headers</param>
        public static void AddAllowedServerVariablesForUrlRewrite(string siteName, params string[] variables)
        {
            if (variables.Length == 0)
            {
                return;
            }

            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetApplicationHostConfiguration();

                ConfigurationSection allowedServerVariablesSection = config.GetSection("system.webServer/rewrite/allowedServerVariables", siteName);

                ConfigurationElementCollection allowedServerVariablesCollection = allowedServerVariablesSection.GetCollection();

                List <string> existingVariables = new List <string>();

                foreach (ConfigurationElement e in allowedServerVariablesCollection)
                {
                    if (variables.Any((i) => i.Equals(Convert.ToString(e["name"]), StringComparison.CurrentCultureIgnoreCase)))
                    {
                        existingVariables.Add(Convert.ToString(e["name"]));
                    }
                }

                var missingVariables = variables.Except(existingVariables).ToList();

                if (!missingVariables.Any())
                {
                    return;
                }

                foreach (var missingVariable in missingVariables)
                {
                    ConfigurationElement addElement = allowedServerVariablesCollection.CreateElement("add");
                    addElement["name"] = missingVariable;
                    allowedServerVariablesCollection.Add(addElement);
                }

                serverManager.CommitChanges();
            }
        }
        public AddServerVariableDialog(IServiceProvider serviceProvider, ServerVariableItem existing)
            : base(serviceProvider)
        {
            InitializeComponent();
            Item              = existing ?? new ServerVariableItem(null);
            cbName.Text       = Item.Name;
            txtValue.Text     = Item.Value;
            cbReplace.Checked = Item.Replace;
            var service      = (IConfigurationService)serviceProvider.GetService(typeof(IConfigurationService));
            var rulesSection = service.GetSection("system.webServer/rewrite/allowedServerVariables");
            ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();

            foreach (ConfigurationElement ruleElement in rulesCollection)
            {
                cbName.Items.Add(ruleElement["name"]);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtValue, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(cbName, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(0.5))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(cbName.Text) && !string.IsNullOrWhiteSpace(txtValue.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                Item.Name    = cbName.Text;
                Item.Value   = txtValue.Text;
                Item.Replace = cbReplace.Checked;
                DialogResult = DialogResult.OK;
            }));
        }
예제 #28
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 virtualDirectoryDefaultsElement = siteElement.GetChildElement("virtualDirectoryDefaults");
            virtualDirectoryDefaultsElement["logonMethod"] = @"Network";

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

            ConfigurationSection applicationInitializationSection = config.GetSection("system.webServer/applicationInitialization", "Default Web Site");
            applicationInitializationSection["remapManagedRequestsTo"] = @"HelloJoe.htm";
            applicationInitializationSection["skipManagedModules"]     = true;
            applicationInitializationSection["doAppInitAfterRestart"]  = true;

            ConfigurationElementCollection applicationInitializationCollection = applicationInitializationSection.GetCollection();

            ConfigurationElement addElement = applicationInitializationCollection.CreateElement("add");
            addElement["initializationPage"] = @"JoesSite.htm";
            addElement["hostName"]           = @"JoesHost";
            applicationInitializationCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
예제 #30
0
    private static void Main()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           applicationPoolsSection    = config.GetSection("system.applicationHost/applicationPools");
            ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();
            ConfigurationElement           addElement = FindElement(applicationPoolsCollection, "add", "name", @"DefaultAppPool");
            if (addElement == null)
            {
                throw new InvalidOperationException("Element not found!");
            }

            ConfigurationElement failureElement = addElement.GetChildElement("failure");
            failureElement["rapidFailProtection"]           = true;
            failureElement["rapidFailProtectionInterval"]   = TimeSpan.Parse("00:05:00");
            failureElement["rapidFailProtectionMaxCrashes"] = 5;
            serverManager.CommitChanges();
        }
    }
예제 #31
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           logFileElement         = siteDefaultsElement.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();
        }
    }
예제 #32
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 ftpServerElement    = siteDefaultsElement.GetChildElement("ftpServer");

            ConfigurationElement           securityElement            = ftpServerElement.GetChildElement("security");
            ConfigurationElement           commandFilteringElement    = securityElement.GetChildElement("commandFiltering");
            ConfigurationElementCollection commandFilteringCollection = commandFilteringElement.GetCollection();
            ConfigurationElement           addElement = commandFilteringCollection.CreateElement("add");
            addElement["command"] = @"SYST";
            addElement["allowed"] = false;
            commandFilteringCollection.Add(addElement);

            serverManager.CommitChanges();
        }
    }
예제 #33
0
        /// <summary>
        ///     Removes all web dav authoring rule.
        /// </summary>
        /// <param name="webSiteName"> Name of the web site. </param>
        public void RemoveAllWebDavAuthoringRules(string webSiteName)
        {
            Trace.TraceInformation("RemoveAllWebDavAuthoringRules...");

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

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

                this.ServerManager.CommitChanges();
            }
            finally
            {
                Trace.TraceInformation("RemoveAllWebDavAuthoringRules...finished.");
            }
        }
        public void AddPoolSite(ServerManager serverManager, string name)
        {
            Configuration                  config = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           applicationPoolsSection    = config.GetSection("system.applicationHost/applicationPools");
            ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();
            ConfigurationElement           addElement = applicationPoolsCollection.CreateElement("add");

            addElement["name"] = name;
            ConfigurationElement           recyclingElement       = addElement.GetChildElement("recycling");
            ConfigurationElement           periodicRestartElement = recyclingElement.GetChildElement("periodicRestart");
            ConfigurationElementCollection scheduleCollection     = periodicRestartElement.GetCollection("schedule");
            ConfigurationElement           addElement1            = scheduleCollection.CreateElement("add");

            addElement1["value"] = TimeSpan.Parse("03:00:00");
            scheduleCollection.Add(addElement1);
            applicationPoolsCollection.Add(addElement);
            serverManager.CommitChanges();
            Console.WriteLine("Pool added successfully");
            Console.ReadLine();
        }
		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 int FindHttpError(ConfigurationElementCollection collection, HttpError error)
		{
			for (int i = 0; i < collection.Count; i++)
			{
				var item = collection[i];
				//
				if ((Int64)item.GetAttributeValue(StatusCodeAttribute) == Int64.Parse(error.ErrorCode)
					&& (Int32)item.GetAttributeValue(SubStatusCodeAttribute) == Int32.Parse(error.ErrorSubcode))
				{
					return i;
				}
			}
			//
			return -1;
		}
		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;
		}
        public ConfigurationElementCollection GetCollection(string collectionName)
        {
            var child = ChildElements[collectionName];
            if (child != null)
            {
                return child.GetCollection();
            }

            var schema = Schema.ChildElementSchemas[collectionName];
            if (schema == null)
            {
                return null;
            }

            var result = new ConfigurationElementCollection(collectionName, schema, this, this.InnerEntity, null);
            ChildElements.Add(result);
            return result.GetCollection();
        }
 private static void AddServerVariable(ConfigurationElementCollection variablesCollection, string name,
     string value)
 {
     var variableElement = variablesCollection.CreateElement("set");
     variableElement["name"] = name;
     variableElement["value"] = value;
     variablesCollection.Add(variableElement);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WorkflowExtensionsBehavior"/> class. 
 ///   Initializes the WorkflowExtensionsBehavior
 /// </summary>
 /// <param name="extensionConfigElements">
 /// The extension config elements 
 /// </param>
 public WorkflowExtensionsBehavior(
     ConfigurationElementCollection<WorkflowExtensionConfigElement> extensionConfigElements)
 {
     this.ExtensionConfigElements = extensionConfigElements;
 }
		private int FindCustomHttpHeader(ConfigurationElementCollection collection, HttpHeader header)
		{
			for (int i = 0; i < collection.Count; i++)
			{
				var item = collection[i];
				//
				if (String.Equals(item.GetAttributeValue(NameAttribute), header.Key))
				{
					return i;
				}
			}
			//
			return -1;
		}
예제 #42
0
        private bool FindHttpErrorElement(ConfigurationElementCollection elementCollection, int statusCode)
        {
            foreach (ConfigurationElement element in elementCollection)
            {
                if (
                    element.Attributes["responseMode"] != null
                    && element.Attributes["statusCode"] != null
                    && Convert.ToInt32(element["responseMode"]) == 1
                    && Convert.ToInt32(element["statusCode"]) == statusCode
                    )
                {
                    return true;
                }
            }

            return false;
        }
		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 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;
		}
		private ConfigurationElement FindHandlerAction(ConfigurationElementCollection handlers, string path, string processor)
		{
			foreach (ConfigurationElement action in handlers)
			{
				// match handler path mapping
				bool pathMatches = (String.Compare((string)action["path"], path, true) == 0)
					|| (String.Compare((string)action["path"], String.Format("*{0}", path), true) == 0);
				// match handler processor
				bool processorMatches = (String.Compare(FileUtils.EvaluateSystemVariables((string)action["scriptProcessor"]), 
					FileUtils.EvaluateSystemVariables(processor), true) == 0);
				// return handler action when match is exact
				if (pathMatches && processorMatches)
					return action;
			}
			// 
			return null;
		}
		private int FindDefaultDocument(ConfigurationElementCollection collection, string valueStr)
		{
			for (int i = 0; i < collection.Count; i++)
			{
				var item = collection[i];
				//
				var valueObj = item.GetAttributeValue(ValueAttribute);
				//
				if (String.Equals((String)valueObj, valueStr, StringComparison.OrdinalIgnoreCase))
				{
					return i;
				}
			}
			//
			return -1;
		}
		private int FindMimeMap(ConfigurationElementCollection collection, MimeMap mapping)
		{
			for (int i = 0; i < collection.Count; i++)
			{
				var item = collection[i];
				//
				if (String.Equals(item.GetAttributeValue(FileExtensionAttribute), mapping.Extension))
				{
					return i;
				}
			}
			//
			return -1;
		}