コード例 #1
0
        public bool AddBinding(string domainName)
        {
            var siteName = System.Configuration.ConfigurationManager.AppSettings["webSiteName"];

            using (ServerManager serverManager = new ServerManager())
            {
                Microsoft.Web.Administration.Configuration                  config          = serverManager.GetApplicationHostConfiguration();
                Microsoft.Web.Administration.ConfigurationSection           sitesSection    = config.GetSection("system.applicationHost/sites");
                Microsoft.Web.Administration.ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
                Microsoft.Web.Administration.ConfigurationElement           siteElement     = FindElement(sitesCollection, "site", "name", siteName);

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

                Microsoft.Web.Administration.ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");

                Microsoft.Web.Administration.ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
                bindingElement["protocol"]           = @"http";
                bindingElement["bindingInformation"] = @"*:80:" + domainName;
                bindingsCollection.Add(bindingElement);

                Microsoft.Web.Administration.ConfigurationElement bindingElement1 = bindingsCollection.CreateElement("binding");
                bindingElement1["protocol"]           = @"http";
                bindingElement1["bindingInformation"] = @"*:80:www." + domainName;
                bindingsCollection.Add(bindingElement1);

                serverManager.CommitChanges();
            }

            return(true);
        }
コード例 #2
0
ファイル: UdpInstaller.cs プロジェクト: Br3nda/sfdocsamples
        public static void Install(UdpInstallerOptions options)
        {
            if (options.ListenerAdapterChecked)
            {
                WebAdmin.ServerManager                  sm = new WebAdmin.ServerManager();
                WebAdmin.Configuration                  wasConfiguration           = sm.GetApplicationHostConfiguration();
                WebAdmin.ConfigurationSection           section                    = wasConfiguration.GetSection(ListenerAdapterPath);
                WebAdmin.ConfigurationElementCollection listenerAdaptersCollection = section.GetCollection();
                WebAdmin.ConfigurationElement           element                    = listenerAdaptersCollection.CreateElement();
                element.GetAttribute("name").Value     = UdpConstants.Scheme;
                element.GetAttribute("identity").Value = WindowsIdentity.GetCurrent().User.Value;
                listenerAdaptersCollection.Add(element);
                sm.CommitChanges();
                wasConfiguration = null;
                sm = null;
            }

            if (options.ProtocolHandlerChecked)
            {
                Configuration    rootWebConfig = GetRootWebConfiguration();
                ProtocolsSection section       = (ProtocolsSection)rootWebConfig.GetSection(ProtocolsPath);
                ProtocolElement  element       = new ProtocolElement(UdpConstants.Scheme);

                element.ProcessHandlerType   = typeof(UdpProcessProtocolHandler).AssemblyQualifiedName;
                element.AppDomainHandlerType = typeof(UdpAppDomainProtocolHandler).AssemblyQualifiedName;
                element.Validate             = false;

                section.Protocols.Add(element);
                rootWebConfig.Save();
            }
        }
コード例 #3
0
        /// <summary>
        /// 添加IIS mime类型
        /// </summary>
        /// <param name="mimeDic"></param>
        /// <returns></returns>
        private static bool AddMIMEType(Microsoft.Web.Administration.Configuration confg, Dictionary <string, string> mimeDic)
        {
            try
            {
                Microsoft.Web.Administration.ConfigurationSection section;
                section = confg.GetSection("system.webServer/staticContent");     //取得MimeMap所有节点(路径为:%windir%\Windows\System32\inetsrv\config\applicationHost.config)

                Microsoft.Web.Administration.ConfigurationElement           filesElement    = section.GetCollection();
                Microsoft.Web.Administration.ConfigurationElementCollection filesCollection = filesElement.GetCollection();


                foreach (var key in mimeDic.Keys)
                {
                    Microsoft.Web.Administration.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);
            }
        }
コード例 #4
0
        private static void EnsureDefaultDocument(ServerManager iis)
        {
            IIS.Configuration        applicationHostConfiguration = iis.GetApplicationHostConfiguration();
            IIS.ConfigurationSection defaultDocumentSection       = applicationHostConfiguration.GetSection("system.webServer/defaultDocument");

            IIS.ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");

            if (filesCollection.Any(ConfigurationElementContainsHostingStart))
            {
                return;
            }

            IIS.ConfigurationElement addElement = filesCollection.CreateElement("add");
            addElement["value"] = HostingStartHtml;
            filesCollection.Add(addElement);

            iis.CommitChanges();
        }
コード例 #5
0
        public async Task LoadAsync(Application application, string file, string appName, SortedDictionary <string, List <string> > variables)
        {
            if (variables == null)
            {
                if (Credentials == null)
                {
                    var rows = File.ReadAllLines(file);
                    variables = new SortedDictionary <string, List <string> >();
                    foreach (var line in rows)
                    {
                        var index   = line.IndexOf('#');
                        var content = index == -1 ? line : line.Substring(0, index);
                        var parts   = content.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                        if (parts.Length != 2)
                        {
                            continue;
                        }

                        var key   = parts[0].Trim().ToLowerInvariant();
                        var value = parts[1].Trim();
                        if (variables.ContainsKey(key))
                        {
                            variables[key].Add(value);
                            continue;
                        }

                        variables.Add(key, new List <string> {
                            value
                        });
                    }
                }
                else
                {
                    using (var client = GetClient())
                    {
                        HttpResponseMessage response = await client.GetAsync(string.Format("api/app/get/{0}", appName));

                        if (response.IsSuccessStatusCode)
                        {
                            variables = (SortedDictionary <string, List <string> >) await response.Content.ReadAsAsync(typeof(SortedDictionary <string, List <string> >));
                        }
                    }
                }
            }

            variables.Load(new List <string> {
                "false"
            }, "usehttps");
            variables.Load(new List <string> {
                "*"
            }, "hosts", "host");
            variables.Load(new List <string> {
                IPAddress.Any.ToString()
            }, "addr", "address");
            variables.Load(new List <string> {
                "80"
            }, "port");
            var root = variables.Load(new List <string> {
                "/ /var/www/default"
            }, "root")[0];
            var split = root.IndexOf(' ');

            if (split == -1 || split == 0)
            {
                throw new ServerManagerException("invalid root mapping");
            }

            var virtualDirectory = new VirtualDirectory(null, application.VirtualDirectories);

            virtualDirectory.Path         = root.Substring(0, split);
            virtualDirectory.PhysicalPath = root.Substring(split + 1);
            application.VirtualDirectories.Add(virtualDirectory);
            var configuration   = application.GetWebConfiguration();
            var defaultDocument = configuration.GetSection("system.webServer/defaultDocument");

            defaultDocument["enabled"] = true;
            var collection = defaultDocument.GetCollection("files");

            collection.Clear();
            var names = variables.Load(new List <string> {
                Constants.DefaultDocumentList
            }, "indexes", "indexs")[0];
            var pageNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var name in pageNames)
            {
                var file1 = collection.CreateElement();
                file1.Attributes["value"].Value = name;
                collection.Add(file1);
            }


            ConfigurationSection httpLoggingSection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location);
            var dontLog = Convert.ToBoolean(variables.Load(new List <string> {
                "false"
            }, "nolog")[0]);

            httpLoggingSection["dontLog"] = dontLog;

            var ipSecuritySection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location);

            ipSecuritySection["enableReverseDns"] = false;
            ipSecuritySection["allowUnlisted"]    = true;

            ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();

            ipSecurityCollection.Clear();
            var deny = variables.Load(new List <string>(), "denyfrom", "ip.deny");

            foreach (var denyEntry in deny)
            {
                var denyItems = denyEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in denyItems)
                {
                    ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                    if (item.Contains("/"))
                    {
                        var parts = item.Split('/');
                        addElement["ipAddress"]  = parts[0];
                        addElement["subnetMask"] = parts[1];
                    }
                    else
                    {
                        addElement["ipAddress"] = item;
                    }

                    addElement["allowed"] = false;
                    ipSecurityCollection.Add(addElement);
                }
            }

            var allow = variables.Load(new List <string>(), "allowfrom", "ip.allow");

            foreach (var allowEntry in allow)
            {
                var allowItems = allowEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in allowItems)
                {
                    ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                    if (item.Contains("/"))
                    {
                        var parts = item.Split('/');
                        addElement["ipAddress"]  = parts[0];
                        addElement["subnetMask"] = parts[1];
                    }
                    else
                    {
                        addElement["ipAddress"] = item;
                    }

                    addElement["allowed"] = true;
                    ipSecurityCollection.Add(addElement);
                }
            }

            ConfigurationSection           requestFilteringSection  = configuration.GetSection("system.webServer/security/requestFiltering");
            ConfigurationElement           hiddenSegmentsElement    = requestFilteringSection.ChildElements["hiddenSegments"];
            ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();

            hiddenSegmentsCollection.Clear();
            var hidden = variables.Load(new List <string> {
                string.Empty
            }, "denydirs")[0];
            var hiddenItems = hidden.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in hiddenItems)
            {
                ConfigurationElement add = hiddenSegmentsCollection.CreateElement("add");
                add["segment"] = item;
                hiddenSegmentsCollection.Add(add);
            }

            ConfigurationSection           httpErrorsSection    = configuration.GetSection("system.webServer/httpErrors");
            ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection();

            httpErrorsCollection.Clear();
            Debug.Assert(variables != null, "variables != null");
            if (variables.ContainsKey("nofile"))
            {
                var error = variables["nofile"][0];
                ConfigurationElement errorElement = httpErrorsCollection.CreateElement("error");
                errorElement["statusCode"]             = 404;
                errorElement["subStatusCode"]          = 0;
                errorElement["prefixLanguageFilePath"] = @"%SystemDrive%\inetpub\custerr";
                errorElement["responseMode"]           = "ExecuteURL";
                errorElement["path"] = error;
                httpErrorsCollection.Add(errorElement);
                variables.Remove("nofile");
            }

            var urlCompressionSection = configuration.GetSection("system.webServer/urlCompression");

            urlCompressionSection["doStaticCompression"] = Convert.ToBoolean(variables.Load(new List <string> {
                "true"
            }, "usegzip")[0]);

            ConfigurationSection httpProtocolSection = configuration.GetSection("system.webServer/httpProtocol");

            httpProtocolSection["allowKeepAlive"] = Convert.ToBoolean(variables.Load(new List <string> {
                "true"
            }, "keep_alive")[0]);

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

            rulesCollection.Clear();
            if (variables.ContainsKey("rewrite"))
            {
                var rules = variables["rewrite"];
                for (int i = 0; i < rules.Count; i++)
                {
                    var rule = rules[i];
                    ConfigurationElement ruleElement = rulesCollection.CreateElement("rule");
                    ruleElement["name"]           = @"rule" + i;
                    ruleElement["enabled"]        = true;
                    ruleElement["patternSyntax"]  = 0;
                    ruleElement["stopProcessing"] = false;

                    var parts = rule.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    ConfigurationElement matchElement = ruleElement.GetChildElement("match");
                    matchElement["ignoreCase"] = parts[0].EndsWith("/i", StringComparison.Ordinal);
                    matchElement["url"]        = parts[0].EndsWith("/i", StringComparison.Ordinal) ? parts[0].Substring(0, parts[0].Length - 2) : parts[0];

                    ConfigurationElement actionElement = ruleElement.GetChildElement("action");
                    actionElement["type"] = 2;
                    actionElement["url"]  = parts[1];
                    actionElement["appendQueryString"] = true;
                    rulesCollection.Add(ruleElement);
                }

                variables.Remove("rewrite");
            }

            application.Extra = variables;
        }