Example #1
0
        public async Task SaveAsync(Application application)
        {
            var variables = new SortedDictionary <string, List <string> >();

            foreach (var item in application.Extra)
            {
                variables.Add(item.Key, item.Value);
            }

            var vDir = application.VirtualDirectories[0];

            Configuration                  config = application.GetWebConfiguration();
            ConfigurationSection           defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
            ConfigurationElementCollection filesCollection        = defaultDocumentSection.GetCollection("files");
            ConfigurationSection           httpLoggingSection     = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location);
            ConfigurationSection           ipSecuritySection      = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location);

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

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

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

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

            ConfigurationSection           rewriteSection    = config.GetSection("system.webServer/rewrite/rules");
            ConfigurationElementCollection rewriteCollection = rewriteSection.GetCollection();

            variables.Add("usehttps", new List <string> {
                (application.Site.Bindings[0].Protocol == "https").ToString()
            });
            variables.Add("addr", new List <string> {
                application.Site.Bindings[0].EndPoint.Address.ToString()
            });
            variables.Add("port", new List <string> {
                application.Site.Bindings[0].EndPoint.Port.ToString()
            });
            variables.Add("hosts", new List <string> {
                application.Site.Bindings[0].Host
            });
            variables.Add("root", new List <string> {
                $"{vDir.Path} {vDir.PhysicalPath}"
            });
            variables.Add("nolog", new List <string> {
                httpLoggingSection["dontLog"].ToString()
            });
            variables.Add("keep_alive", new List <string> {
                httpProtocolSection["allowKeepAlive"].ToString()
            });

            var indexes = StringExtensions.Combine(filesCollection.Select(item => item.RawAttributes["value"]), ",");

            variables.Add("indexes", new List <string> {
                indexes
            });

            var allows = new List <string>();
            var denys  = new List <string>();

            foreach (ConfigurationElement item in ipSecuritySection.GetCollection())
            {
                string element = string.IsNullOrEmpty((string)item["subnetMask"])
                    ? (string)item["ipAddress"]
                    : $"{item["ipAddress"]}/{item["subnetMask"]}";
                if ((bool)item["allowed"])
                {
                    allows.Add(element);
                }
                else
                {
                    denys.Add(element);
                }
            }

            variables.Add("allowfrom", allows);
            variables.Add("denyfrom", denys);

            var segments = StringExtensions.Combine(hiddenSegmentsCollection.Select(item => item["segment"].ToString()), ",");

            variables.Add("denydirs", new List <string> {
                segments
            });

            foreach (ConfigurationElement item in httpErrorsCollection)
            {
                if ((uint)item["statusCode"] == 404 && (int)item["subStatusCode"] == 0 &&
                    (string)item["prefixLanguageFilePath"] == @"%SystemDrive%\inetpub\custerr" &&
                    (long)item["responseMode"] == 1)
                {
                    variables.Add("nofile", new List <string> {
                        item["path"].ToString()
                    });
                }
            }

            variables.Add("usegzip", new List <string> {
                urlCompressionSection["doStaticCompression"].ToString()
            });

            var rules = new List <string>();

            foreach (ConfigurationElement item in rewriteCollection)
            {
                var action = item.GetChildElement("action");
                var match  = item.GetChildElement("match");
                if ((long)action["type"] == 2)
                {
                    rules.Add(string.Format("{0}{2} {1}", match["url"], action["url"], (bool)match["ignoreCase"] ? "/i" : string.Empty));
                }
            }

            variables.Add("rewrite", rules);

            if (string.IsNullOrEmpty(application.Server.HostName))
            {
                var rows = new List <string>();
                foreach (var item in variables)
                {
                    foreach (var line in item.Value)
                    {
                        rows.Add($"{item.Key}={line}");
                    }
                }

                var fileName = Path.Combine("siteconf", application.ToFileName());
                File.WriteAllLines(fileName, rows);
            }
            else
            {
                using (var client = GetClient())
                {
                    HttpResponseMessage response = await client.PutAsJsonAsync($"api/site/{application.ToFileName()}", variables);

                    if (response.IsSuccessStatusCode)
                    {
                    }
                }
            }
        }
        private void CheckItem(T element, T item)
        {
            List <Tuple <string, object> > keys = new List <Tuple <string, object> >();

            foreach (ConfigurationAttributeSchema attribute in element.Schema.AttributeSchemas)
            {
                if (!attribute.IsCombinedKey && !attribute.IsUniqueKey)
                {
                    continue;
                }

                if (!item[attribute.Name].Equals(element[attribute.Name]))
                {
                    return;
                }

                keys.Add(new Tuple <string, object>(attribute.Name, item[attribute.Name]));
            }

            if (keys.Count == 0)
            {
                return;
            }

            var line = (element.Entity as IXmlLineInfo).LineNumber;

            if (keys.Count == 1)
            {
                throw new COMException(
                          $"Filename: \\\\?\\{FileContext.FileName}\r\nLine number: {line}\r\nError: Cannot add duplicate collection entry of type '{element.ElementTagName}' with unique key attribute '{keys[0].Item1}' set to '{keys[0].Item2}'\r\n\r\n");
            }

            var keyNames = new string[keys.Count];
            var values   = new object[keys.Count];

            for (var index = 0; index < keys.Count; index++)
            {
                var key = keys[index];
                keyNames[index] = key.Item1;
                values[index]   = key.Item2;
            }

            throw new COMException(
                      $"Filename: \\\\?\\{FileContext.FileName}\r\nLine number: {line}\r\nError: Cannot add duplicate collection entry of type '{element.ElementTagName}' with combined key attributes '{StringExtensions.Combine(keyNames, ", ")}' respectively set to '{StringExtensions.Combine(values.Select(value => value.ToString()), ", ")}'\r\n\r\n");
        }