public void GetCustomErrors(ServerManager srvman, WebVirtualDirectory virtualDir) { var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath); // var httpErrorsSection = config.GetSection(Constants.HttpErrorsSection); virtualDir.ErrorMode = (HttpErrorsMode)httpErrorsSection.GetAttributeValue("errorMode"); virtualDir.ExistingResponse = (HttpErrorsExistingResponse)httpErrorsSection.GetAttributeValue("existingResponse"); // var errorsCollection = httpErrorsSection.GetCollection(); // var errors = new List<HttpError>(); // foreach (var item in errorsCollection) { var item2Get = GetHttpError(item, virtualDir); // if (item2Get == null) continue; // errors.Add(item2Get); } // virtualDir.HttpErrors = errors.ToArray(); }
private void backgroundAssociatedSiteHttpRedirect_DoWork(object sender, DoWorkEventArgs e) { IEnumerable<TreeNode> selectedNoneWwwSiteNodes = e.Argument as IEnumerable<TreeNode>; int i = 1; int totalCount = selectedNoneWwwSiteNodes.Count(); foreach (TreeNode siteNode in selectedNoneWwwSiteNodes) { if (!backgroundAssociatedSiteHttpRedirect.CancellationPending) { Node site = (Node)siteNode.Tag; bool enableChecked = true; string destination = string.Format("http://www.{0}", siteNode.Text); bool enableExactDestination = false; bool enableChildOnly = false; string httpResponseStatus = "永久(301)"; try { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(site.Site.Name); SetHttpRedirectElement(enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus, config); string log = DateTime.Now.ToString() + ":" + string.Format("为站点 {0} 添加Http重定向,启用:{1},重定向目标:{2},定向到确切目标:{3},定向到非子目录中的内容:{4},状态代码:{5}", siteNode.Text, enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus); backgroundAssociatedSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); serverManager.CommitChanges(); } } catch (Exception exception) { string log = DateTime.Now.ToString() + ":" + string.Format("为站点 {0} 添加Http重定向失败,错误详情如下", siteNode.Name) + exception.ToString(); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); } i++; } } }
private static IDictionary<string, string> ParseMimeTypes() { using (var serverManager = new ServerManager()) { var siteName = HostingEnvironment.ApplicationHost.GetSiteName(); var config = serverManager.GetWebConfiguration(siteName); var staticContentSection = config.GetSection("system.webServer/staticContent"); var staticContentCollection = staticContentSection.GetCollection(); var mimeMaps = staticContentCollection.Where(c => c.ElementTagName == "mimeMap" && c.GetAttributeValue("fileExtension") != null && !string.IsNullOrWhiteSpace(c.GetAttributeValue("fileExtension").ToString()) && c.GetAttributeValue("mimeType") != null && !string.IsNullOrWhiteSpace(c.GetAttributeValue("mimeType").ToString()) ); var results = mimeMaps.Select(m => new KeyValuePair<string, string>(m.GetAttributeValue("fileExtension").ToString(), m.GetAttributeValue("mimeType").ToString())); return results.ToDictionary(pair => pair.Key, pair => pair.Value); } }
protected void AlterWebConfig() { Configuration appHost = IISManager.GetApplicationHostConfiguration(); ConfigurationSection configPaths = appHost.GetSection("connectionstring"); using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration("TestSite"); ConfigurationSection directoryBrowseSection = config.GetSection("system.webServer/directoryBrowse"); if ((bool)directoryBrowseSection["enabled"] != true) { directoryBrowseSection["enabled"] = true; } serverManager.CommitChanges(); } }
/// <summary> /// Loads available mime maps into supplied virtual iisDirObject description. /// </summary> /// <param name="vdir">Virtual iisDirObject description.</param> public void GetMimeMaps(ServerManager srvman, WebVirtualDirectory virtualDir) { var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath); // var section = config.GetSection(Constants.StaticContentSection); // var mappings = new List<MimeMap>(); // foreach (var item in section.GetCollection()) { var item2Get = GetMimeMap(item); // if (item2Get == null) continue; // mappings.Add(item2Get); } // virtualDir.MimeMaps = mappings.ToArray(); }
public ActionResult Delete(String id) { using (var serverManager = new ServerManager(Environment.ExpandEnvironmentVariables(@"%APP_POOL_CONFIG%"))) { var path = @"Web.config"; var sites = serverManager.Sites; var webConfig = serverManager.GetWebConfiguration(webSiteName); string rulesSection = "rules"; var inboundRulesCollection = webConfig.GetSection("system.webServer/rewrite/" + rulesSection).GetCollection(); var ruleToDelete = inboundRulesCollection.FirstOrDefault(i => i.GetAttribute("name").Value.ToString() == id); if(ruleToDelete != null) inboundRulesCollection.Remove(ruleToDelete); serverManager.CommitChanges(); } return RedirectToAction("Index"); }
public string GetDefaultDocumentSettings(ServerManager srvman, string siteId) { // Load web site configuration var config = srvman.GetWebConfiguration(siteId); // Load corresponding section var section = config.GetSection(Constants.DefaultDocumentsSection); // var filesCollection = section.GetCollection("files"); // Build default documents var defaultDocs = new List<String>(); // foreach (var item in filesCollection) { var item2Get = GetDefaultDocument(item); // if (String.IsNullOrEmpty(item2Get)) continue; // defaultDocs.Add(item2Get); } // return String.Join(",", defaultDocs.ToArray()); }
public ActionResult Create(ConfigModel model) { using (var serverManager = new ServerManager(Environment.ExpandEnvironmentVariables(@"%APP_POOL_CONFIG%"))) { var path = @"Web.config"; var sites = serverManager.Sites; var webConfig = serverManager.GetWebConfiguration(webSiteName); string rulesSection = "rules"; var inboundRulesCollection = webConfig.GetSection("system.webServer/rewrite/" + rulesSection).GetCollection(); var outboundRulesSection = webConfig.GetSection("system.webServer/rewrite/outboundRules"); var outbBoundRulesCollection = outboundRulesSection.GetCollection(); var preConditionsCollection = outboundRulesSection.GetCollection("preConditions"); inboundRulesCollection.AddAt(inboundRulesCollection.Count - 1, CreateInboundGwRemoteUserRule(model, inboundRulesCollection.CreateElement("rule"))); serverManager.CommitChanges(); } return RedirectToAction("Index"); }
// GET: Configure public ActionResult Index() { var list = new List<ConfigModel>(); using (var serverManager = new ServerManager(Environment.ExpandEnvironmentVariables(@"%APP_POOL_CONFIG%"))) { var path = @"Web.config"; var sites = serverManager.Sites; var webConfig = serverManager.GetWebConfiguration(webSiteName); string rulesSection = "rules"; var inboundRulesCollection = webConfig.GetSection("system.webServer/rewrite/" + rulesSection).GetCollection(); var outboundRulesSection = webConfig.GetSection("system.webServer/rewrite/outboundRules"); var outboundRulesCollection = outboundRulesSection.GetCollection(); var preConditionsCollection = outboundRulesSection.GetCollection("preConditions"); inboundRulesCollection.ForEach( r => { var conditions = r.GetCollection("conditions"); var condition = conditions.FirstOrDefault(c => c.GetAttribute("input").Value.ToString() == "{HTTP_HOST}"); list.Add(new ConfigModel() { RuleName = r.GetAttribute("name").Value.ToString(), Pattern = condition != null ? condition.GetAttribute("pattern").Value.ToString() : string.Empty, }); }) ; } return View(list); }
private static ConfigModel GetConfigModelFromId(string id) { ConfigModel model; using (var serverManager = new ServerManager(Environment.ExpandEnvironmentVariables(@"%APP_POOL_CONFIG%"))) { var path = @"Web.config"; var sites = serverManager.Sites; var webConfig = serverManager.GetWebConfiguration(webSiteName); string rulesSection = "rules"; var inboundRulesCollection = webConfig.GetSection("system.webServer/rewrite/" + rulesSection).GetCollection(); var outboundRulesSection = webConfig.GetSection("system.webServer/rewrite/outboundRules"); var outboundRulesCollection = outboundRulesSection.GetCollection(); var preConditionsCollection = outboundRulesSection.GetCollection("preConditions"); var rule = inboundRulesCollection.First( r => r.GetAttribute("name").Value.ToString() == id); var conditions = rule.GetCollection("conditions"); var condition = conditions.FirstOrDefault(c => c.GetAttribute("input").Value.ToString() == "{HTTP_HOST}"); var action = rule.GetChildElement("action"); model = new ConfigModel() { Pattern = condition != null ? condition.GetAttribute("pattern").Value.ToString() : string.Empty, RuleName = id, UrlRewrite = action.GetAttributeValue("url").ToString() }; } return model; }
public void SetHandlersAccessPolicy(ServerManager srvman, string fqPath, HandlerAccessPolicy policy) { var config = srvman.GetWebConfiguration(fqPath); // HandlersSection section = (HandlersSection)config.GetSection(Constants.HandlersSection, typeof(HandlersSection)); // section.AccessPolicy = policy; }
private static void SetAuthenticationSection(string attributeName, string value) { using (ServerManager serverManager = new ServerManager()) { Site site = serverManager.Sites.Where(s => s.Name == IISHelper.DefaultWebSiteName).Single(); Configuration config = serverManager.GetWebConfiguration(site.Name); ConfigurationSection authenticationSection = config.GetSection("system.web/authentication"); authenticationSection.SetAttributeValue(attributeName, value); serverManager.CommitChanges(); } }
protected PhpVersion[] GetPhpVersions(ServerManager srvman, WebVirtualDirectory virtualDir) { var config = srvman.GetWebConfiguration(GetSiteIdFromVirtualDir(virtualDir), virtualDir.VirtualPath); //var config = srvman.GetApplicationHostConfiguration(); var handlersSection = config.GetSection(Constants.HandlersSection); var result = new List<PhpVersion>(); // Loop through available maps and fill installed processors foreach (var handler in handlersSection.GetCollection()) { if (string.Equals(handler["path"].ToString(), "*.php", StringComparison.OrdinalIgnoreCase)) { var executable = handler["ScriptProcessor"].ToString().Split('|')[0]; if (string.Equals(handler["Modules"].ToString(), "FastCgiModule", StringComparison.OrdinalIgnoreCase) && File.Exists(executable)) { var handlerName = handler["Name"].ToString(); result.Add(new PhpVersion() {HandlerName = handlerName, Version = GetPhpExecutableVersion(executable), ExecutionPath = handler["ScriptProcessor"].ToString()}); } } } return result.ToArray(); }
private void FillVirtualDirectoryRestFromIISObject(ServerManager srvman, WebVirtualDirectory virtualDir) { // HTTP REDIRECT httpRedirectSvc.GetHttpRedirectSettings(srvman, virtualDir); // HTTP HEADERS customHeadersSvc.GetCustomHttpHeaders(srvman, virtualDir); // HTTP ERRORS customErrorsSvc.GetCustomErrors(srvman, virtualDir); // MIME MAPPINGS mimeTypesSvc.GetMimeMaps(srvman, virtualDir); // SCRIPT MAPS // Load installed script maps. virtualDir.AspInstalled = false; // not installed virtualDir.PhpInstalled = ""; // none virtualDir.PerlInstalled = false; // not installed virtualDir.PythonInstalled = false; // not installed virtualDir.ColdFusionInstalled = false; // not installed // var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath); var handlersSection = config.GetSection(Constants.HandlersSection); // Loop through available maps and fill installed processors foreach (ConfigurationElement action in handlersSection.GetCollection()) { // Extract and evaluate scripting processor path string processor = FileUtils.EvaluateSystemVariables( Convert.ToString(action.GetAttributeValue("scriptProcessor"))); // string actionName = Convert.ToString(action.GetAttributeValue("name")); // Detect whether ASP scripting is enabled if (!String.IsNullOrEmpty(AspPath) && String.Equals(AspPath, processor, StringComparison.InvariantCultureIgnoreCase)) virtualDir.AspInstalled = true; //// Detect whether PHP 5 scripting is enabled (non fast_cgi) if (PhpMode != Constants.PhpMode.FastCGI && !String.IsNullOrEmpty(PhpExecutablePath) && String.Equals(PhpExecutablePath, processor, StringComparison.InvariantCultureIgnoreCase)) virtualDir.PhpInstalled = PHP_5; // Detect whether PHP 4 scripting is enabled if (!String.IsNullOrEmpty(Php4Path) && String.Equals(Php4Path, processor, StringComparison.InvariantCultureIgnoreCase)) virtualDir.PhpInstalled = PHP_4; // Detect whether ColdFusion scripting is enabled if (!String.IsNullOrEmpty(ColdFusionPath) && String.Compare(ColdFusionPath, processor, true) == 0 && actionName.Contains(".cfm")) virtualDir.ColdFusionInstalled = true; // Detect whether Perl scripting is enabled if (!String.IsNullOrEmpty(PerlPath) && String.Equals(PerlPath, processor, StringComparison.InvariantCultureIgnoreCase)) virtualDir.PerlInstalled = true; } // Detect PHP 5 Fast_cgi version(s) var activePhp5Handler = GetActivePhpHandlerName(srvman, virtualDir); if (!string.IsNullOrEmpty(activePhp5Handler)) { virtualDir.PhpInstalled = PHP_5 + "|" + activePhp5Handler; var versions = GetPhpVersions(srvman, virtualDir); // This versionstring is used in UI to view and change php5 version. var versionString = string.Join("|", versions.Select(v => v.HandlerName + ";" + v.Version).ToArray()); virtualDir.Php5VersionsInstalled = versionString; } // string fqPath = virtualDir.FullQualifiedPath; if (!fqPath.EndsWith(@"/")) fqPath += "/"; // fqPath += CGI_BIN_FOLDER; // HandlerAccessPolicy policy = handlersSvc.GetHandlersAccessPolicy(srvman, fqPath); virtualDir.CgiBinInstalled = (policy & HandlerAccessPolicy.Execute) > 0; // ASP.NET FillAspNetSettingsFromIISObject(srvman, virtualDir); }
protected string GetActivePhpHandlerName(ServerManager srvman, WebVirtualDirectory virtualDir) { var config = srvman.GetWebConfiguration(GetSiteIdFromVirtualDir(virtualDir), virtualDir.VirtualPath); var handlersSection = config.GetSection(Constants.HandlersSection); // Find first handler for *.php return (from handler in handlersSection.GetCollection() where string.Equals(handler["path"].ToString(), "*.php", StringComparison.OrdinalIgnoreCase) && string.Equals(handler["Modules"].ToString(), "FastCgiModule", StringComparison.OrdinalIgnoreCase) select handler["name"].ToString() ).FirstOrDefault(); }
public ActionResult Edit(ConfigModel model) { using (var serverManager = new ServerManager(Environment.ExpandEnvironmentVariables(@"%APP_POOL_CONFIG%"))) { var path = @"Web.config"; var sites = serverManager.Sites; var webConfig = serverManager.GetWebConfiguration(webSiteName); string rulesSection = "rules"; var inboundRulesCollection = webConfig.GetSection("system.webServer/rewrite/" + rulesSection).GetCollection(); var outboundRulesSection = webConfig.GetSection("system.webServer/rewrite/outboundRules"); var outboundRulesCollection = outboundRulesSection.GetCollection(); var preConditionsCollection = outboundRulesSection.GetCollection("preConditions"); var rule = inboundRulesCollection.First( r => r.GetAttribute("name").Value.ToString() == model.RuleName); var conditions = rule.GetCollection("conditions"); var condition = conditions.FirstOrDefault(c => c.GetAttribute("input").Value.ToString() == "{HTTP_HOST}"); var action = rule.GetChildElement("action"); action.GetAttribute("url").Value = model.UrlRewrite; condition.GetAttribute("pattern").Value = model.Pattern; serverManager.CommitChanges(); } return View(); }
/// <summary> /// 判断一个Node是否配置了Http重定向 /// </summary> /// <param name="node"></param> /// <returns></returns> private bool enableHttpRedirect(Node node, ServerManager serverManager) { if (node.NodeType == NodeType.Site) { string siteName = node.Site.Name; Configuration config = serverManager.GetWebConfiguration(siteName); ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect"); return (bool)httpRedirectSection["enabled"]; } else if (node.NodeType == NodeType.Application) { string siteName = node.Site.Name; string appPath = node.Application.Path; { Configuration config = serverManager.GetWebConfiguration(siteName, appPath); ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect"); return (bool)httpRedirectSection["enabled"]; } } else if (node.NodeType == NodeType.VirtualDirectory) { string siteName = node.Site.Name; string appPath = node.Application.Path; string virDirPath = node.VirtualDirectoty.Path; Configuration config = serverManager.GetWebConfiguration(siteName, appPath + virDirPath); ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect"); return (bool)httpRedirectSection["enabled"]; } else if (node.NodeType == NodeType.Root) { return true; } else { return false; } }
private void backgroundSiteHttpRedirect_DoWork(object sender, DoWorkEventArgs e) { HttpRedirectSettingParams settingParams = (HttpRedirectSettingParams)e.Argument; IEnumerable<TreeNode> selectedSiteNodes = settingParams.SelectedSiteNodes; IEnumerable<TreeNode> selectedAppNodes = settingParams.SelectedAppNodes; IEnumerable<TreeNode> selectedVirtualDirNodes = settingParams.SelectedVirtualDirNodes; bool enableChecked = settingParams.EnableChecked; string destination = settingParams.Destination; bool enableExactDestination = settingParams.EnableExactDestination; bool enableChildOnly = settingParams.EnableChildOnly; string httpResponseStatus = settingParams.HttpResponseStatus; int totalCount = selectedSiteNodes.Count() + selectedAppNodes.Count() + selectedVirtualDirNodes.Count(); #region 为网站设置Http重定向 if (selectedSiteNodes.Count() > 0) { int i = 1; foreach (TreeNode siteNode in selectedSiteNodes) { if (!backgroundSiteHttpRedirect.CancellationPending) { Node site = (Node)siteNode.Tag; try { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(site.Site.Name); SetHttpRedirectElement(enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus, config); string log = DateTime.Now.ToString() + ":" + string.Format("为站点 {0} 添加Http重定向,启用:{1},重定向目标:{2},定向到确切目标:{3},定向到非子目录中的内容:{4},状态代码:{5}", siteNode.Text, enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); serverManager.CommitChanges(); } } catch (Exception exception) { string log = DateTime.Now.ToString() + ":" + string.Format("为站点 {0} 添加Http重定向失败,错误详情如下", siteNode.Name) + exception.ToString(); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); } i++; } } } #endregion #region 为应用程序设置Http重定向 if (selectedAppNodes.Count() > 0) { int i = selectedSiteNodes.Count() + 1; foreach (TreeNode appNode in selectedAppNodes) { if (!backgroundSiteHttpRedirect.CancellationPending) { Node app = (Node)appNode.Tag; try { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(app.Site.Name, app.Application.Path); SetHttpRedirectElement(enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus, config); string log = DateTime.Now.ToString() + ":" + string.Format("为应用程序 {0} 添加Http重定向,启用:{1},重定向目标:{2},定向到确切目标:{3},定向到非子目录中的内容:{4},状态代码:{5}", app.Application.Path, enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); serverManager.CommitChanges(); } } catch (Exception exception) { string log = DateTime.Now.ToString() + ":" + string.Format("为应用程序 {0} 添加Http重定向失败,错误详情如下", app.Application.Path) + exception.ToString(); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); } i++; } } } #endregion #region 为虚拟路径设置Http重定向 if (selectedVirtualDirNodes.Count() > 0) { int i = selectedSiteNodes.Count() + selectedAppNodes.Count() + 1; foreach (TreeNode treeNode in selectedVirtualDirNodes) { if (!backgroundSiteHttpRedirect.CancellationPending) { Node node = (Node)treeNode.Tag; string siteName = node.Site.Name; string appPath = node.Application.Path; string virtualDirPath = node.VirtualDirectoty.Path; try { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(siteName, appPath + virtualDirPath); SetHttpRedirectElement(enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus, config); string log = DateTime.Now.ToString() + ":" + string.Format("为虚拟路径 {0} 添加Http重定向,启用:{1},重定向目标:{2},定向到确切目标:{3},定向到非子目录中的内容:{4},状态代码:{5}", appPath + virtualDirPath, enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); serverManager.CommitChanges(); } } catch (Exception exception) { string log = DateTime.Now.ToString() + ":" + string.Format("为虚拟路径 {0} 添加Http重定向失败,错误详情如下", appPath + virtualDirPath) + exception.ToString(); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); } } } } #endregion }
private void ShowSiteInfo(TreeNode clickedNode, Node node) { if (node.NodeType == NodeType.Site) { using (ServerManager serverManager = new ServerManager()) { string siteName = clickedNode.Text; Microsoft.Web.Administration.Site site = serverManager.Sites[siteName]; string state = site.State.ToString(); string appPool = site.Applications["/"].ApplicationPoolName; string physicalPath = site.Applications["/"].VirtualDirectories["/"].PhysicalPath; Microsoft.Web.Administration.Binding[] bindingInfos = site.Bindings.ToArray(); Configuration config = serverManager.GetWebConfiguration(siteName); ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect"); bool enableChecked = (bool)httpRedirectSection["enabled"]; string destination = httpRedirectSection["destination"] as string; bool enableExactDestination = (bool)httpRedirectSection["exactDestination"]; bool enableChildOnly = (bool)httpRedirectSection["childOnly"]; string httpResponseStatus = httpRedirectSection["httpResponseStatus"].ToString(); string[] siteInfoes = { string.Format("网站名称 :{0}", siteName), string.Format("网站状态 :{0}", state), string.Format("应用程序池:{0}", appPool), string.Format("物理路径 :{0}", physicalPath) }; listBoxLogs.Items.AddRange(siteInfoes); int i = 1; foreach (Microsoft.Web.Administration.Binding binding in bindingInfos) { listBoxLogs.Items.Add(string.Format("绑定信息{0}:类型 {1},主机名 {2},IP {3},端口 {4}", i, binding.Protocol, binding.Host, binding.EndPoint.Address, binding.EndPoint.Port)); i++; } listBoxLogs.Items.Add(string.Format("Http重定向:启用:{0},目标:{1},将所有请求重定向到确切的目标:{2},仅将请求重定向到非子目录中的内容:{3},状态代码:{4}", enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus)); listBoxLogs.Items.Add(""); } } }
private static void AddRewriteRules(ServerManager serverManager, Site site) { var config = serverManager.GetWebConfiguration(site.Name); var rulesSection = config.GetSection("system.webServer/rewrite/rules"); var rulesCollection = rulesSection.GetCollection(); //HTTP to HTTPS var ruleElement = rulesCollection.CreateElement("rule"); ruleElement["name"] = @"HTTP to HTTPS"; ruleElement["stopProcessing"] = true; var matchElement = ruleElement.GetChildElement("match"); matchElement["url"] = @".*"; var conditionsElement = ruleElement.GetChildElement("conditions"); var conditionsCollection = conditionsElement.GetCollection(); var addElement = conditionsCollection.CreateElement("add"); addElement["input"] = @"{HTTPS}"; addElement["pattern"] = @"off"; conditionsCollection.Add(addElement); addElement = conditionsCollection.CreateElement("add"); addElement["input"] = @"{REQUEST_URI}"; addElement["pattern"] = @"products/files/services/wcfservice/service.svc.*"; addElement["negate"] = @"true"; conditionsCollection.Add(addElement); var actionElement = ruleElement.GetChildElement("action"); actionElement["type"] = @"Redirect"; actionElement["url"] = @"https://{HTTP_HOST}/{R:0}"; actionElement["appendQueryString"] = "true"; actionElement["redirectType"] = @"Temporary"; if (rulesCollection.Count(r => "HTTP to HTTPS".Equals(r.GetAttributeValue("name"))) <= 0) { rulesCollection.Add(ruleElement); } //WCF files HTTPS to HTTP ruleElement = rulesCollection.CreateElement("rule"); ruleElement["name"] = @"WCF files HTTPS to HTTP"; ruleElement["stopProcessing"] = true; matchElement = ruleElement.GetChildElement("match"); matchElement["url"] = @"products/files/services/wcfservice/service.svc.*"; conditionsElement = ruleElement.GetChildElement("conditions"); conditionsCollection = conditionsElement.GetCollection(); addElement = conditionsCollection.CreateElement("add"); addElement["input"] = @"{HTTPS}"; addElement["pattern"] = @"on"; conditionsCollection.Add(addElement); actionElement = ruleElement.GetChildElement("action"); actionElement["type"] = @"Rewrite"; actionElement["url"] = @"http://{HTTP_HOST}/{R:0}"; actionElement["appendQueryString"] = "true"; if (rulesCollection.Count(r => "WCF files HTTPS to HTTP".Equals(r.GetAttributeValue("name"))) <= 0) { rulesCollection.Add(ruleElement); } }
public static void SetServiceInstanceAuth(string virtualApplicationName, bool allowAnonymousAuth, bool allowWindowsAuth) { var applicationPath = "/" + virtualApplicationName; using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(WebApplicationName, applicationPath); ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication"); anonymousAuthenticationSection["enabled"] = allowAnonymousAuth; ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication"); windowsAuthenticationSection["enabled"] = allowWindowsAuth; serverManager.CommitChanges(); } }
protected PhpVersion[] GetPhpVersions(ServerManager srvman, WebVirtualDirectory virtualDir) { var result = new List<PhpVersion>(); // Loop through all available maps installed for virtualDir, site and server and and fill installed processors var config = srvman.GetWebConfiguration(GetSiteIdFromVirtualDir(virtualDir), virtualDir.VirtualPath); var handlersSection = config.GetSection(Constants.HandlersSection); foreach (var handler in handlersSection.GetCollection()) { AddUniquePhpHandlerToList(result, handler); } if (!(virtualDir is WebSite)) { var siteConfig = srvman.GetWebConfiguration(GetSiteIdFromVirtualDir(virtualDir), "/"); var siteHandlersSection = siteConfig.GetSection(Constants.HandlersSection); foreach (var handler in siteHandlersSection.GetCollection()) { AddUniquePhpHandlerToList(result, handler); } } var srvConfig = srvman.GetApplicationHostConfiguration(); var srvHandlersSection = srvConfig.GetSection(Constants.HandlersSection); foreach (var handler in srvHandlersSection.GetCollection()) { AddUniquePhpHandlerToList(result, handler); } return result.ToArray(); }
static ContentController() { _mimeLookup = new Dictionary<string, string>(); using (ServerManager serverManager = new ServerManager()) { var siteName = HostingEnvironment.ApplicationHost.GetSiteName(); Configuration config = serverManager.GetWebConfiguration(siteName); ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent"); ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); foreach (ConfigurationElement confElem in staticContentCollection) { _mimeLookup.Add(confElem.GetAttributeValue("fileExtension").ToString(), confElem.GetAttributeValue("mimeType").ToString()); } } }