public GetSection ( string sectionPath ) : |
||
sectionPath | string | |
Результат |
} // SetWebSiteUploadLimitation private int GetWebSiteUploadLimitation(Microsoft.Web.Administration.Configuration oConfig, string sControllerAction) { int nResult = 0; try { ConfigurationSection requestFilteringSection = string.IsNullOrWhiteSpace(sControllerAction) ? oConfig.GetSection(SectionPath) : oConfig.GetSection(SectionPath, sControllerAction); ConfigurationElement requestLimitsElement = requestFilteringSection.GetChildElement(ElementName); ConfigurationAttribute oAttr = requestLimitsElement.GetAttribute(AttributeName); if (oAttr != null) { int macl; if (int.TryParse(oAttr.Value.ToString(), out macl)) { nResult = macl; } else { m_oLog.Warn("Failed to parse upload limit for action '{0}'.", sControllerAction); } } // if m_oLog.Debug("Current upload limit for action '{1}' is {0} bytes.", nResult, sControllerAction); } catch (Exception e) { m_oLog.Warn(e, "Failed to load upload limit for action '{0}'.", sControllerAction); } // try return(nResult); } // GetWebSiteUploadLimitation
public void Initialize() { if (_configurationProvider.IsEmulated()) { return; } // Instantiate the IIS ServerManager using (var serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration applicationConfig = serverManager.GetApplicationHostConfiguration(); ConfigurationSection httpLoggingSection = applicationConfig.GetSection("system.webServer/httpLogging"); httpLoggingSection["selectiveLogging"] = @"LogAll"; httpLoggingSection["dontLog"] = false; ConfigurationSection sitesSection = applicationConfig.GetSection("system.applicationHost/sites"); ConfigurationElement siteElement = sitesSection.GetCollection().Single(); ConfigurationElement logFileElement = siteElement.GetChildElement("logFile"); logFileElement["logFormat"] = "W3C"; logFileElement["period"] = "Hourly"; logFileElement["enabled"] = true; logFileElement["logExtFileFlags"] = "BytesRecv,BytesSent,ClientIP,ComputerName,Cookie,Date,Host,HttpStatus,HttpSubStatus,Method,ProtocolVersion,Referer,ServerIP,ServerPort,SiteName,Time,TimeTaken,UriQuery,UriStem,UserAgent,UserName,Win32Status"; serverManager.CommitChanges(); } }
public void Initialize() { if (_configurationProvider.IsEmulated()) { return; } // Instantiate the IIS ServerManager using (var serverManager = new ServerManager()) { // Disable idle timeout & set queue length to 5000 serverManager.ApplicationPoolDefaults.ProcessModel.IdleTimeout = TimeSpan.Zero; serverManager.ApplicationPoolDefaults.QueueLength = 5000; // Server runtime configuration Microsoft.Web.Administration.Configuration applicationConfig = serverManager.GetApplicationHostConfiguration(); // Server runtime settings // http://www.iis.net/configreference/system.webserver/serverruntime ConfigurationSection serverRuntimeSection = applicationConfig.GetSection("system.webServer/serverRuntime", ""); serverRuntimeSection["enabled"] = true; serverRuntimeSection["frequentHitThreshold"] = 1; serverRuntimeSection["frequentHitTimePeriod"] = TimeSpan.Parse("00:00:10"); // Compression settings // http://www.iis.net/configreference/system.webserver/httpcompression ConfigurationSection httpCompressionSection = applicationConfig.GetSection("system.webServer/httpCompression"); httpCompressionSection["noCompressionForHttp10"] = false; httpCompressionSection["noCompressionForProxies"] = false; ConfigurationElementCollection dynamicTypesCollection = httpCompressionSection.GetCollection("dynamicTypes"); ConfigurationElement addElement = dynamicTypesCollection.CreateElement("add"); addElement["mimeType"] = @"application/json"; addElement["enabled"] = true; try { dynamicTypesCollection.Add(addElement); } catch (COMException) { // add json element already exists } addElement = dynamicTypesCollection.CreateElement("add"); addElement["mimeType"] = @"application/xml"; addElement["enabled"] = true; try { dynamicTypesCollection.Add(addElement); } catch (COMException) { // add xml element already exists } // Commit the changes serverManager.CommitChanges(); } }
/// <summary> /// Deploy's the IIS PHP handler at the application hosts level, but site specific. /// </summary> protected void deployIISHandlers() { using (ServerManager serverManager = new ServerManager()) { var siteName = this.Deployment.getShortId(); string siteAlias = this.Deployment.getShortId(); // fastCgi settings in IIS can only be set at the HOSTS level // we found no way to set this at a web.config level. Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationElement cfs = null; ConfigurationSection section; ConfigurationElementCollection elems; section = config.GetSection("system.webServer/handlers", siteName); elems = section.GetCollection(); cfs = elems.CreateElement("add"); cfs.SetAttributeValue("name", "php-" + this.Deployment.getShortId()); cfs.SetAttributeValue("path", "*.php"); cfs.SetAttributeValue("verb", "GET,HEAD,POST,PUT,PATCH,DELETE"); cfs.SetAttributeValue("modules", "FastCgiModule"); cfs.SetAttributeValue("scriptProcessor", this.GetFastCgiExe() + "|" + this.Deployment.getShortId()); cfs.SetAttributeValue("resourceType", "Either"); cfs.SetAttributeValue("requireAccess", "Script"); cfs.SetAttributeValue("responseBufferLimit", 0); // Add as the first handler... order matters here. elems.AddAt(0, cfs); // And index.php as a default document... var files = config.GetSection("system.webServer/defaultDocument", siteName).GetChildElement("files"); elems = files.GetCollection(); // We might have inherited settings from a higher level // that already cover the default document configuration. var exists = (from p in elems where p.Schema.Name == "add" && ((string)p.GetAttributeValue("value")) == "index.php" select 1).Any(); if (!exists) { // TODO: This fails if the default document is already configured at a higher level. Ensure it does // not exist before trying to create it! cfs = elems.CreateElement("add"); cfs.SetAttributeValue("value", "index.php"); elems.Add(cfs); } UtilsIis.CommitChanges(serverManager); } }
public virtual Application CreateApplication(string appName, Site site, string Path, string physicsPath, string appPoolName) { try { Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); Application newApp = site.Applications[Path]; if (newApp != null) { site.Applications.Remove(newApp); //delete this application config.RemoveLocationPath(string.Format("{0}{1}", site.Name, Path)); //delete the node of the applicationHostConfig.config file with this application } newApp = site.Applications.Add(Path, physicsPath); newApp.ApplicationPoolName = appPoolName; //开启目录浏览 string path = "system.webServer/directoryBrowse";//the attribue path in the applictionHostConfig.config file. Microsoft.Web.Administration.ConfigurationSection dbS = config.GetSection(path, string.Format("{0}{1}", site.Name, Path)); dbS.Attributes["enabled"].Value = true; serverManager_CommitChanges(); return(newApp); } catch (Exception error) { throw new Exception(string.Format("创建应用程序[{0}]时出错:{1}", appName, error.Message)); } }
/// <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); } }
public static void Uninstall(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(); for (int i = 0; i < listenerAdaptersCollection.Count; i++) { WebAdmin.ConfigurationElement element = listenerAdaptersCollection[i]; if (string.Compare((string)element.GetAttribute("name").Value, UdpConstants.Scheme, StringComparison.OrdinalIgnoreCase) == 0) { listenerAdaptersCollection.RemoveAt(i); } } sm.CommitChanges(); wasConfiguration = null; sm = null; } if (options.ProtocolHandlerChecked) { Configuration rootWebConfig = GetRootWebConfiguration(); ProtocolsSection section = (ProtocolsSection)rootWebConfig.GetSection(ProtocolsPath); section.Protocols.Remove(UdpConstants.Scheme); rootWebConfig.Save(); } }
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(); } }
private void SetWebSiteUploadLimitation(Microsoft.Web.Administration.Configuration oConfig, int nUploadLimit, string sControllerAction) { try { ConfigurationSection requestFilteringSection = string.IsNullOrWhiteSpace(sControllerAction) ? oConfig.GetSection(SectionPath) : oConfig.GetSection(SectionPath, sControllerAction); ConfigurationElement requestLimitsElement = requestFilteringSection.GetChildElement(ElementName); requestLimitsElement.SetAttributeValue(AttributeName, nUploadLimit); m_oLog.Debug("Updated upload limit to '{0}' for action '{1}'.", nUploadLimit, sControllerAction); } catch (Exception e) { m_oLog.Warn(e, "Failed to update upload limit to '{0}' for action '{1}'.", nUploadLimit, sControllerAction); } // try } // SetWebSiteUploadLimitation
/// <summary> /// Adds mime types. /// </summary> /// <param name="config">Config of the website or web application</param> /// <param name="mimeTypes">List of mime types to be added</param> protected static void AddMimeTypes(Microsoft.Web.Administration.Configuration config, IList <MimeType> mimeTypes) { if (mimeTypes != null && mimeTypes.Count > 0) { var staticContentSection = config.GetSection("system.webServer/staticContent"); ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); foreach (var mimeType in mimeTypes) { ConfigurationElement mimeMapElement = staticContentCollection.CreateElement("mimeMap"); mimeMapElement["fileExtension"] = mimeType.FileExtension; mimeMapElement["mimeType"] = mimeType.MimeTypeName; staticContentCollection.Add(mimeMapElement); } } }
public static void SetAutoStart(string siteUri, bool enabled) { var manager = new ServerManager(); Microsoft.Web.Administration.Configuration config = manager.GetApplicationHostConfiguration(); var configSection = config.GetSection("system.applicationHost/sites"); foreach (var application in from site in configSection.GetCollection() from application in site.GetCollection() where application.Schema.Name == "application" && application["path"].ToString() == siteUri select application) { application.SetAttributeValue("serviceAutoStartEnabled", enabled); application.SetAttributeValue("serviceAutoStartProvider", "IISProcessSchedulerPreWarmUp"); } manager.CommitChanges(); }
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(); }
public static void SetAutoStartProvider() { var manager = new ServerManager(); Microsoft.Web.Administration.Configuration config = manager.GetApplicationHostConfiguration(); var configSection = config.GetSection("system.applicationHost/serviceAutoStartProviders"); if (configSection.GetCollection().Any(provider => provider["name"].ToString() == "IISProcessSchedulerPreWarmUp")) { return; } var element = configSection.GetCollection().CreateElement("add"); element.SetAttributeValue("name", "IISProcessSchedulerPreWarmUp"); element.SetAttributeValue("type", "IISProcessScheduler.PreWarmUp, IISProcessScheduler"); configSection.GetCollection().Add(element); manager.CommitChanges(); }
public void GetConfigurrationAttribute() { ServerManager manager = new ServerManager(); Microsoft.Web.Administration.Configuration config = manager.GetApplicationHostConfiguration(); ConfigurationSection configSection = config.GetSection("system.applicationHost/serviceAutoStartProviders"); foreach (var item in configSection.GetCollection()) { if (item.Attributes["type"].Value.ToString() == "IISProcessScheduler.PreWarmUp, IISProcessScheduler") { } } ConfigurationAttributeCollection configAttributeCollection = configSection.Attributes; }
private static void SetHttpRedirectElement(bool enableChecked, string destination, bool enableExactDestination, bool enableChildOnly, string httpResponseStatus, Configuration config) { ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect"); httpRedirectSection["enabled"] = enableChecked; httpRedirectSection["destination"] = destination; httpRedirectSection["exactDestination"] = enableExactDestination; httpRedirectSection["childOnly"] = enableChildOnly; if (httpResponseStatus == "已找到(302)") { httpRedirectSection["httpResponseStatus"] = "Found"; } else if (httpResponseStatus == "永久(301)") { httpRedirectSection["httpResponseStatus"] = "Permanent"; } else { httpRedirectSection["httpResponseStatus"] = "Temporary"; } }
private static Hashtable LoadMimeMappings(string arg) { Hashtable ht = new Hashtable(); using (HostingEnvironment.Impersonate()) { using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration config = serverManager.GetWebConfiguration(arg); ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent"); foreach (ConfigurationElement elm in staticContentSection.GetCollection()) { object attrExt = elm.GetAttributeValue("fileExtension"); object attrMimeType = elm.GetAttributeValue("mimeType"); if (attrExt != null && attrMimeType != null) { ht[attrExt.ToString()] = attrMimeType.ToString().Split(';')[0]; } } } } return(ht); }
/// <summary> /// Gets the mimetype for the extension provided, using IIS to lookup the mimetype, or this fails, /// a dictionary lookup of common extensions to mimetypes. /// </summary> /// <param name="fileExtension">The file extension to lookup, which should include the "." e.g. ".jpg"</param> /// <returns>The mimetype for the extension, or "application/octet-stream" if the mimetype cannot be found.</returns> public static string GetMimeType(string fileExtension) { if (string.IsNullOrEmpty(fileExtension)) { return("application/octet-stream"); } fileExtension = fileExtension.ToLower(); #if MONO || DEBUG return(MimeTypes.GetMimeMapping(fileExtension)); #endif try { using (ServerManager serverManager = new ServerManager()) { string mimeType = "application/octet-stream"; Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent"); ConfigurationElementCollection mimemaps = staticContentSection.GetCollection(); ConfigurationElement element = mimemaps.FirstOrDefault(m => m.Attributes["fileExtension"].Value.ToString() == fileExtension); if (element != null) { mimeType = element.Attributes["mimeType"].Value.ToString(); } return(mimeType); } } catch (Exception) { // Shared hosting won't have access to the applicationhost.config file (UnauthorizedAccessException) // also IIS Express doesn't have ServerManager registered as a COM type (COMException) return(MimeTypes.GetMimeMapping(fileExtension)); } }
/// <summary> /// Retrieves all default documents for a server and site matching the specified <see cref="SiteInformation"/>. /// </summary> /// <param name="siteInformation"></param> /// <returns></returns> public static IEnumerable <string> GetDefaultDocuments(SiteInformation siteInformation) { if (siteInformation == null) { throw new ArgumentNullException("siteInformation"); } if (string.IsNullOrEmpty(siteInformation.SiteName)) { return(new List <string>()); } using (ServerManager serverManager = string.IsNullOrEmpty(siteInformation.Server) ? new ServerManager() : ServerManager.OpenRemote(siteInformation.Server)) { // Retrieve default documents Microsoft.Web.Administration.Configuration webConfig = serverManager.GetWebConfiguration(siteInformation.SiteName); ConfigurationSection section = webConfig.GetSection("system.webServer/defaultDocument"); return(section.GetCollection("files").Select(x => (string)x["value"]) .ToList()); } }
public bool DeleteBinding(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"); var binding = FindElement(bindingsCollection, "binding", "bindingInformation", "*:80:" + domainName); if (binding == null) { throw new InvalidOperationException("Binding not found!"); } bindingsCollection.Remove(binding); var binding1 = FindElement(bindingsCollection, "binding", "bindingInformation", "*:80:www." + domainName); if (binding1 == null) { throw new InvalidOperationException("Binding not found!"); } bindingsCollection.Remove(binding1); serverManager.CommitChanges(); } return(true); }
public void RunDeploy(String[] args) { if (args.Length < 3) { Console.Error.WriteLine("rdfWebDeploy: Error: 3 Arguments are required in order to use the -deploy mode, type rdfWebDeploy -help to see usage summary"); return; } if (args.Length > 3) { if (!this.SetOptions(args.Skip(3).ToArray())) { Console.Error.WriteLine("rdfWebDeploy: Deployment aborted since one/more options were not valid"); return; } } if (this._noLocalIIS) { Console.WriteLine("rdfWebDeploy: No Local IIS Server available so switching to -xmldeploy mode"); XmlDeploy xdeploy = new XmlDeploy(); xdeploy.RunXmlDeploy(args); return; } //Define the Server Manager object Admin.ServerManager manager = null; try { //Connect to the Server Manager if (!this._noIntegratedRegistration) { manager = new Admin.ServerManager(); } //Open the Configuration File System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(args[1], this._site); Console.Out.WriteLine("rdfWebDeploy: Opened the Web.config file for the specified Web Application"); //Detect Folders String appFolder = Path.GetDirectoryName(config.FilePath); String binFolder = Path.Combine(appFolder, "bin\\"); String appDataFolder = Path.Combine(appFolder, "App_Data\\"); if (!Directory.Exists(binFolder)) { Directory.CreateDirectory(binFolder); Console.WriteLine("rdfWebDeploy: Created a bin\\ directory for the web application"); } if (!Directory.Exists(appDataFolder)) { Directory.CreateDirectory(appDataFolder); Console.WriteLine("rdfWebDeploy: Created an App_Data\\ directory for the web application"); } //Deploy dotNetRDF and required DLLs to the bin directory of the application String sourceFolder = RdfWebDeployHelper.ExecutablePath; IEnumerable <String> dlls = RdfWebDeployHelper.RequiredDLLs; if (this._sql) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredSqlDLLs); } if (this._virtuoso) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredVirtuosoDLLs); } if (this._fulltext) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredFullTextDLLs); } foreach (String dll in dlls) { if (File.Exists(Path.Combine(sourceFolder, dll))) { File.Copy(Path.Combine(sourceFolder, dll), Path.Combine(binFolder, dll), true); Console.WriteLine("rdfWebDeploy: Deployed " + dll + " to the web applications bin directory"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Required DLL " + dll + " which needs deploying to the web applications bin directory could not be found"); return; } } //Deploy the configuration file to the App_Data directory if (File.Exists(args[2])) { File.Copy(args[2], Path.Combine(appDataFolder, args[2]), true); Console.WriteLine("rdfWebDeploy: Deployed the configuration file to the web applications App_Data directory"); } else if (!File.Exists(Path.Combine(appDataFolder, args[2]))) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to continue deployment as the configuration file " + args[2] + " could not be found either locally for deployment to the App_Data folder or already present in the App_Data folder"); return; } //Set the AppSetting for the configuration file config.AppSettings.Settings.Remove("dotNetRDFConfig"); config.AppSettings.Settings.Add("dotNetRDFConfig", "~/App_Data/" + Path.GetFileName(args[2])); Console.WriteLine("rdfWebDeploy: Set the \"dotNetRDFConfig\" appSetting to \"~/App_Data/" + Path.GetFileName(args[2]) + "\""); //Now load the Configuration Graph from the App_Data folder Graph g = new Graph(); FileLoader.Load(g, Path.Combine(appDataFolder, args[2])); Console.WriteLine("rdfWebDeploy: Successfully deployed required DLLs and appSettings"); Console.WriteLine(); //Get the sections of the Configuration File we want to edit HttpHandlersSection handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection; if (handlersSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Handlers section of the web applications Web.Config file"); return; } //Detect Handlers from the Configution Graph and deploy IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); IUriNode dnrType = g.CreateUriNode(new Uri(ConfigurationLoader.PropertyType)); IUriNode httpHandler = g.CreateUriNode(new Uri(ConfigurationLoader.ClassHttpHandler)); //Deploy for IIS Classic Mode if (!this._noClassicRegistration) { Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Classic Mode"); foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject)) { if (n.NodeType == NodeType.Uri) { String handlerPath = ((IUriNode)n).Uri.AbsolutePath; INode type = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault(); if (type == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified"); continue; } if (type.NodeType == NodeType.Literal) { String handlerType = ((ILiteralNode)type).Value; //First remove any existing registration handlersSection.Handlers.Remove("*", handlerPath); //Then add the new registration handlersSection.Handlers.Add(new HttpHandlerAction(handlerPath, handlerType, "*")); Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal"); continue; } } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node"); } } //Deploy Negotiate by File Extension if appropriate if (this._negotiate) { HttpModulesSection modulesSection = config.GetSection("system.web/httpModules") as HttpModulesSection; if (modulesSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file"); return; } modulesSection.Modules.Remove("NegotiateByExtension"); modulesSection.Modules.Add(new HttpModuleAction("NegotiateByExtension", "VDS.RDF.Web.NegotiateByFileExtension")); Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module"); } Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Classic Mode"); } //Save the completed Configuration File config.Save(ConfigurationSaveMode.Minimal); Console.WriteLine(); //Deploy for IIS Integrated Mode if (!this._noIntegratedRegistration) { Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Integrated Mode"); Admin.Configuration adminConfig = manager.GetWebConfiguration(this._site, args[1]); Admin.ConfigurationSection newHandlersSection = adminConfig.GetSection("system.webServer/handlers"); Admin.ConfigurationElementCollection newHandlers = newHandlersSection.GetCollection(); foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject)) { if (n.NodeType == NodeType.Uri) { String handlerPath = ((IUriNode)n).Uri.AbsolutePath; INode type = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault(); if (type == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified"); continue; } if (type.NodeType == NodeType.Literal) { String handlerType = ((ILiteralNode)type).Value; //First remove any existing registration foreach (Admin.ConfigurationElement oldReg in newHandlers.Where(el => el.GetAttributeValue("name").Equals(handlerPath)).ToList()) { newHandlers.Remove(oldReg); } //Then add the new registration Admin.ConfigurationElement reg = newHandlers.CreateElement("add"); reg["name"] = handlerPath; reg["path"] = handlerPath; reg["verb"] = "*"; reg["type"] = handlerType; newHandlers.AddAt(0, reg); Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal"); continue; } } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node"); } //Deploy Negotiate by File Extension if appropriate if (this._negotiate) { Admin.ConfigurationSection newModulesSection = adminConfig.GetSection("system.webServer/modules"); if (newModulesSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file"); return; } //First remove the Old Module Admin.ConfigurationElementCollection newModules = newModulesSection.GetCollection(); foreach (Admin.ConfigurationElement oldReg in newModules.Where(el => el.GetAttribute("name").Equals("NegotiateByExtension")).ToList()) { newModules.Remove(oldReg); } //Then add the new Module Admin.ConfigurationElement reg = newModules.CreateElement("add"); reg["name"] = "NegotiateByExtension"; reg["type"] = "VDS.RDF.Web.NegotiateByFileExtension"; newModules.AddAt(0, reg); Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module"); } } manager.CommitChanges(); Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Integrated Mode"); } } catch (ConfigurationException configEx) { Console.Error.WriteLine("rdfWebDeploy: Configuration Error: " + configEx.Message); } catch (Exception ex) { Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message); Console.Error.WriteLine(ex.StackTrace); } finally { if (manager != null) { manager.Dispose(); } } }
public override void Install(IDictionary stateSaver) { base.Install(stateSaver); string targetDir = Context.Parameters[Argument.TargetDir].TrimEnd('\\'); string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config"); System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile); System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args) { return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll"))); }); UhuruSection section = (UhuruSection)config.GetSection("uhuru"); if (!string.IsNullOrEmpty(Context.Parameters[Argument.Capacity])) { section.Service.Capacity = int.Parse(Context.Parameters[Argument.Capacity], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Argument.BaseDir])) { section.Service.BaseDir = Context.Parameters[Argument.BaseDir]; if (!Directory.Exists(section.Service.BaseDir)) { Directory.CreateDirectory(section.Service.BaseDir); } } if (!string.IsNullOrEmpty(Context.Parameters[Argument.Index])) { section.Service.Index = int.Parse(Context.Parameters[Argument.Index], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Argument.StatusPort])) { int port = Convert.ToInt32(Context.Parameters[Argument.StatusPort], CultureInfo.InvariantCulture); section.Service.StatusPort = port; if (port != 0) { FirewallTools.OpenPort(port, "FileService Status"); } } if (!string.IsNullOrEmpty(Context.Parameters[Argument.LocalDb])) { section.Service.LocalDB = Context.Parameters[Argument.LocalDb]; } if (!string.IsNullOrEmpty(Context.Parameters[Argument.LocalRoute])) { section.Service.LocalRoute = Context.Parameters[Argument.LocalRoute]; } else { string ip = string.Empty; foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ip = address.ToString(); break; } } section.Service.LocalRoute = ip; } if (!string.IsNullOrEmpty(Context.Parameters[Argument.Mbus])) { section.Service.MBus = Context.Parameters[Argument.Mbus]; } if (!string.IsNullOrEmpty(Context.Parameters[Argument.MigrationNfs])) { section.Service.MigrationNFS = Context.Parameters[Argument.MigrationNfs]; } if (!string.IsNullOrEmpty(Context.Parameters[Argument.NodeId])) { section.Service.NodeId = Context.Parameters[Argument.NodeId]; } if (!string.IsNullOrEmpty(Context.Parameters[Argument.ZInterval])) { section.Service.ZInterval = int.Parse(Context.Parameters[Argument.ZInterval], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Argument.Plan])) { section.Service.Plan = Context.Parameters[Argument.Plan]; } if (!string.IsNullOrEmpty(Context.Parameters[Argument.UseVhd])) { section.Service.Uhurufs.UseVHD = bool.Parse(Context.Parameters[Argument.UseVhd]); } if (!string.IsNullOrEmpty(Context.Parameters[Argument.MaxStorageSize])) { section.Service.Uhurufs.MaxStorageSize = long.Parse(Context.Parameters[Argument.MaxStorageSize], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Argument.VhdFixedSize])) { section.Service.Uhurufs.VHDFixedSize = bool.Parse(Context.Parameters[Argument.VhdFixedSize]); } section.DEA = null; config.Save(); int lowPort = 5000; int highPort = 6000; using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration iisConfig = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection firewallSupportSection = iisConfig.GetSection("system.ftpServer/firewallSupport"); firewallSupportSection["lowDataChannelPort"] = lowPort; firewallSupportSection["highDataChannelPort"] = highPort; Microsoft.Web.Administration.ConfigurationSection sitesSection = iisConfig.GetSection("system.applicationHost/sites"); Microsoft.Web.Administration.ConfigurationElement siteDefaultsElement = sitesSection.GetChildElement("siteDefaults"); Microsoft.Web.Administration.ConfigurationElement ftpServerElement = siteDefaultsElement.GetChildElement("ftpServer"); Microsoft.Web.Administration.ConfigurationElement firewallSupportElement = ftpServerElement.GetChildElement("firewallSupport"); firewallSupportElement["externalIp4Address"] = @"0.0.0.0"; serverManager.CommitChanges(); } FirewallTools.OpenPortRange(lowPort, highPort, "UhuruFS Ports"); }
private void Initialize() { if (this.Initialized) { return; } this.Initialized = true; PreInitialize(); var machineConfig = Helper.IsRunningOnMono() ? "/Library/Frameworks/Mono.framework/Versions/Current/etc/mono/4.5/machine.config" : Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET", IntPtr.Size == 2 ? "Framework" : "Framework64", "v4.0.30319", "config", "machine.config"); var machine = new Configuration( new FileContext( this, machineConfig, null, null, false, true, true)); var webConfig = Helper.IsRunningOnMono() ? "/Library/Frameworks/Mono.framework/Versions/Current/etc/mono/4.5/web.config" : Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET", IntPtr.Size == 2 ? "Framework" : "Framework64", "v4.0.30319", "config", "web.config"); var web = new Configuration( new FileContext( this, webConfig, machine.FileContext, null, false, true, true)); _applicationHost = new Configuration( new FileContext(this, this.FileName, web.FileContext, null, true, false, this.ReadOnly)); this.LoadCache(); var poolSection = _applicationHost.GetSection("system.applicationHost/applicationPools"); _applicationPoolDefaults = new ApplicationPoolDefaults(poolSection.GetChildElement("applicationPoolDefaults"), poolSection); this.ApplicationPoolCollection = new ApplicationPoolCollection(poolSection, this); var siteSection = _applicationHost.GetSection("system.applicationHost/sites"); _siteDefaults = new SiteDefaults(siteSection.GetChildElement("siteDefaults"), siteSection); _applicationDefaults = new ApplicationDefaults( siteSection.GetChildElement("applicationDefaults"), siteSection); _virtualDirectoryDefaults = new VirtualDirectoryDefaults(siteSection.GetChildElement("virtualDirectoryDefaults"), siteSection); this.SiteCollection = new SiteCollection(siteSection, this); PostInitialize(); }
private static ConfigurationSection EnableIisClientCertificateMappingAuthentication(Configuration config, string siteName) { var iisClientCertificateMappingAuthenticationSection = config.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication", siteName); iisClientCertificateMappingAuthenticationSection["enabled"] = true; return iisClientCertificateMappingAuthenticationSection; }
public override void Install(IDictionary stateSaver) { base.Install(stateSaver); string targetDir = Context.Parameters[Arguments.TargetDir].TrimEnd('\\'); string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config"); System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile); System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args) { return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll"))); }); UhuruSection section = (UhuruSection)config.GetSection("uhuru"); if (!string.IsNullOrEmpty(Context.Parameters[Arguments.BaseDir])) { section.DEA.BaseDir = Context.Parameters[Arguments.BaseDir]; } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.EnforceUlimit])) { section.DEA.EnforceUsageLimit = Convert.ToBoolean(Context.Parameters[Arguments.EnforceUlimit], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.FilerPort])) { int port = Convert.ToInt32(Context.Parameters[Arguments.FilerPort], CultureInfo.InvariantCulture); section.DEA.FilerPort = port; FirewallTools.OpenPort(port, "DEA FileServer"); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.StatusPort])) { int port = Convert.ToInt32(Context.Parameters[Arguments.StatusPort], CultureInfo.InvariantCulture); section.DEA.StatusPort = port; FirewallTools.OpenPort(port, "DEA Status"); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.ForceHttpSharing])) { section.DEA.ForceHttpSharing = Convert.ToBoolean(Context.Parameters[Arguments.ForceHttpSharing], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.HeartBeatInterval])) { section.DEA.HeartbeatInterval = Convert.ToInt32(Context.Parameters[Arguments.HeartBeatInterval], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.LocalRoute])) { section.DEA.LocalRoute = Context.Parameters[Arguments.LocalRoute]; } else { string ip = string.Empty; foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ip = address.ToString(); break; } } section.DEA.LocalRoute = ip; } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MaxMemory])) { section.DEA.MaxMemory = Convert.ToInt32(Context.Parameters[Arguments.MaxMemory], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MessageBus])) { section.DEA.MessageBus = Context.Parameters[Arguments.MessageBus]; } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MultiTenant])) { section.DEA.Multitenant = Convert.ToBoolean(Context.Parameters[Arguments.MultiTenant], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(Context.Parameters[Arguments.Secure])) { section.DEA.Secure = Convert.ToBoolean(Context.Parameters[Arguments.Secure], CultureInfo.InvariantCulture); } section.Service = null; config.Save(); using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration authenticationConfig = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = authenticationConfig.GetSection("system.webServer/security/authentication/anonymousAuthentication"); anonymousAuthenticationSection["enabled"] = true; anonymousAuthenticationSection["userName"] = string.Empty; anonymousAuthenticationSection["password"] = string.Empty; anonymousAuthenticationSection["logonMethod"] = @"ClearText"; serverManager.CommitChanges(); } }
/// <summary> /// Deploy fast-cgi settings /// </summary> protected void DeployFasctCgi() { var limits = this.Deployment.GetApplicationLimits(); using (ServerManager serverManager = new ServerManager()) { this.Logger.LogWarning(false, "Deploying fastCgi based applications causes IIS to internally reset to pick the new configuration because fastCgi is configured at the server level."); var phpRuntime = this.GetFastCgiExe(); var iniFilePath = this.GetIniFilePath(); var phpIniFile = this.GetIniFilePath(); string siteAlias = this.Deployment.getShortId(); // fastCgi settings in IIS can only be set at the HOSTS level // we found no way to set this at a web.config level. Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection section = config.GetSection("system.webServer/fastCgi"); ConfigurationElement cfs = null; // Each fastCgi in IIS is a unique combination of RUNTIME_PATH|ARGUMENTS, try to find // the current application. foreach (ConfigurationElement sec in section.GetCollection()) { // Cada aplicación se identifica de manera única por la combincación de atributo y path de ejecución. if (sec.HasValue("arguments", siteAlias) && sec.HasValue("fullPath", phpRuntime)) { cfs = sec; break; } } // We need to keep track if the element already existed // in the configuration, or it is new. bool addApplication = false; ConfigurationElementCollection elems = section.GetCollection(); if (cfs == null) { cfs = elems.CreateElement("application"); addApplication = true; } // In this deployment we are not really passing // any argments to PHP, simply use the site Alias to // isolate each PHP site. // OJO: PONER EL SITE ALIAS AQUÍ NO ES ALGO // GRATUITO. LUEGO EN EL WEB.CONFIG DE LA PROPIA // APLICACIÓN DEBE ESTAR EXACTAMENTE IGUAL. cfs.SetAttributeValue("arguments", siteAlias); // Set reasonable defaults, even if the user configuration says differently var instanceMaxRequests = this.PhpSettings.instanceMaxRequests > 200 ? this.PhpSettings.instanceMaxRequests : 10000; var maxInstances = this.PhpSettings.maxInstances > 3 ? this.PhpSettings.maxInstances : 10; var activityTimeout = this.PhpSettings.activityTimeout > 100 ? this.PhpSettings.activityTimeout : 600; var requestTimeout = this.PhpSettings.requestTimeout > 60 ? this.PhpSettings.requestTimeout : 300; // Ensure that all values are within the limits if (maxInstances > limits.FastCgiMaxInstances && limits.FastCgiMaxInstances > 0) { maxInstances = limits.FastCgiMaxInstances.Value; } // Runtime Path. cfs.SetAttributeValue("fullPath", phpRuntime); cfs.SetAttributeValue("maxInstances", maxInstances); cfs.SetAttributeValue("activityTimeout", activityTimeout); cfs.SetAttributeValue("requestTimeout", requestTimeout); cfs.SetAttributeValue("instanceMaxRequests", instanceMaxRequests); // Make sure that changes to PHP.ini are refreshed properly if (File.Exists(iniFilePath)) { cfs.SetAttributeValue("monitorChangesTo", iniFilePath); } // Este setting no sirve para nada según -E- de MS porque // la implementación de FastCGI está mal hecha en IIS. // Los eventos internos de señal no se llegan a ejecutar nunca, // lo único que consigues es demorar el cierre de instancias. cfs.SetAttributeValue("signalBeforeTerminateSeconds", 0); if (!File.Exists(phpIniFile)) { throw new Exception("PHP.ini file not found. This will break the IIS FastCgiModule when using monitorChangesTo feature."); } // Retrieve the environment variables. ConfigurationElement cfgEnvironment = cfs.GetChildElement("environmentVariables"); ConfigurationElementCollection a = cfgEnvironment.GetCollection(); // This is fastcgi specific. a.AddOrUpdateConfigurationElementInCollection("PHP_FCGI_MAX_REQUESTS", instanceMaxRequests.ToString()); // Add all the environment variables. var environmentVariables = this.GetEnvironmentVariables(); foreach (var p in environmentVariables) { a.AddOrUpdateConfigurationElementInCollection(p.Key, p.Value); } if (addApplication) { elems.Add(cfs); } // Cleanup any fastCgi applications that point to non-existent handlers // see the comments in FastCgiRemove() as to why this is here. var fastCgiHandlers = section.GetCollection(); foreach (ConfigurationElement sec in fastCgiHandlers.ToList()) { if (sec.RawAttributes.Keys.Contains("fullPath")) { string fullPath = sec.GetAttributeValue("fullPath").ToString(); if (!File.Exists(fullPath)) { this.Logger.LogInfo(true, "Removed stale fastCgi handler {0}", fullPath); fastCgiHandlers.Remove(sec); } } } UtilsIis.CommitChanges(serverManager); } }
private bool HasDelegationSection(Configuration adminConfig) { // try to get delegation section in config file (C:\Windows\system32\inetsrv\config\administration.config) try { adminConfig.GetSection("system.webServer/management/delegation"); } catch (Exception ex) { /* skip */ return false; } return true; }
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 static void ConfigureAccessSection(Configuration config, string siteName) { var accessSection = config.GetSection("system.webServer/security/access", siteName); accessSection["sslFlags"] = @"Ssl,SslNegotiateCert,SslRequireCert"; }
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); }
static List <IPSecurity> GetBlockedIP() { List <IPSecurity> sec = new List <IPSecurity>(); using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "BrandsMarketing"); ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection(); foreach (var ip in ipSecurityCollection) { if ((bool)ip["allowed"] == false) { sec.Add(new IPSecurity { IP = ip["ipAddress"].ToString() }); } } return(sec); } }
private static void SetAuthPropertiesForSite(Configuration config, ref Site site) { foreach (string authType in AuthTypes) { var authSection = config.GetSection(string.Format(AuthenticationSection, authType), site.SiteName); if ((bool)authSection[EnabledPropertyName]) { switch (authType) { case AnonymousAuth: site.EnabledAuthType = EnabledAuthenticationType.Anonymous; return; case WindowsAuth: site.EnabledAuthType = EnabledAuthenticationType.Windows; return; case BasicAuth: site.EnabledAuthType = EnabledAuthenticationType.Basic; return; case ClientServerAuth: site.EnabledAuthType = EnabledAuthenticationType.ClientCertificate; return; case IISClientServerMappingAuth: site.EnabledAuthType = EnabledAuthenticationType.IisClientCertificate; return; case DigestAuth: site.EnabledAuthType = EnabledAuthenticationType.Digest; return; } } } }
static void BlockIP(string IP) { using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "BrandsMarketing"); ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection(); ConfigurationElement addElement = ipSecurityCollection.CreateElement("add"); addElement["ipAddress"] = IP; addElement["allowed"] = false; ipSecurityCollection.Add(addElement); serverManager.CommitChanges(); } }
private void Initialize() { if (Initialized) { return; } Initialized = true; PreInitialize(); var machineConfig = Helper.IsRunningOnMono() ? "/Library/Frameworks/Mono.framework/Versions/Current/etc/mono/4.5/machine.config" : Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET", IntPtr.Size == 2 ? "Framework" : "Framework64", "v4.0.30319", "config", "machine.config"); var machine = new Configuration( new FileContext( this, machineConfig, null, null, false, true, true)); var webConfig = Helper.IsRunningOnMono() ? "/Library/Frameworks/Mono.framework/Versions/Current/etc/mono/4.5/web.config" : Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET", IntPtr.Size == 2 ? "Framework" : "Framework64", "v4.0.30319", "config", "web.config"); _web = new Configuration( new FileContext( this, webConfig, machine.FileContext, null, false, true, false)); _applicationHost = new Configuration( new FileContext(this, FileName, _web.FileContext, null, true, false, ReadOnly)); LoadCache(); var poolSection = _applicationHost.GetSection("system.applicationHost/applicationPools"); _applicationPoolDefaults = new ApplicationPoolDefaults(poolSection.GetChildElement("applicationPoolDefaults"), poolSection); ApplicationPoolCollection = new ApplicationPoolCollection(poolSection, this); var siteSection = _applicationHost.GetSection("system.applicationHost/sites"); _siteDefaults = new SiteDefaults(siteSection.GetChildElement("siteDefaults"), siteSection); _applicationDefaults = new ApplicationDefaults( siteSection.GetChildElement("applicationDefaults"), siteSection); _virtualDirectoryDefaults = new VirtualDirectoryDefaults(siteSection.GetChildElement("virtualDirectoryDefaults"), siteSection); SiteCollection = new SiteCollection(siteSection, this); PostInitialize(); }
private static void RegisterZooPhpHandlers(string siteId, string[] engineNames, Configuration appConfig) { // set up zoo php handler if php engine was enabled string enabledPhpEngine = string.Empty; foreach (string engineName in engineNames) { if (engineName.StartsWith("php", StringComparison.OrdinalIgnoreCase)) { enabledPhpEngine = engineName; } } if (!string.IsNullOrEmpty(enabledPhpEngine)) { ConfigurationSection handlers = appConfig.GetSection("system.webServer/handlers", siteId); ConfigurationElementCollection handlerCollection = handlers.GetCollection(); // remove native php handlers /* ConfigurationElement removePhp53 = handlerCollection.CreateElement("remove"); removePhp53.SetAttributeValue("name", "PHP53_via_FastCGI"); handlerCollection.Add(removePhp53); ConfigurationElement removePhp = handlerCollection.CreateElement("remove"); removePhp.SetAttributeValue("name", "PHP_via_FastCGI"); handlerCollection.Add(removePhp); */ // search native php handlers /* List<ConfigurationElement> elementsToRemove = new List<ConfigurationElement>(); foreach (ConfigurationElement el in handlerCollection) { string name = el.GetAttributeValue("name") as string; if (!string.IsNullOrEmpty(name)) { if (string.Equals(name, "PHP_via_FastCGI", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "PHP53_via_FastCGI", StringComparison.OrdinalIgnoreCase) ) { elementsToRemove.Add(el); } } } foreach (ConfigurationElement element in elementsToRemove) { //handlerCollection.Remove(element); } */ // check zoo handlers exists List<ConfigurationElement> zooPhpHandlersToRemove = new List<ConfigurationElement>(); foreach (ConfigurationElement el in handlerCollection) { string name = el.GetAttributeValue("name") as string; if (!string.IsNullOrEmpty(name)) { if (name.StartsWith("php.", StringComparison.OrdinalIgnoreCase)) { string scriptProcessor = el.GetAttributeValue("scriptProcessor") as string; if (!string.IsNullOrEmpty(scriptProcessor)) { zooPhpHandlersToRemove.Add(el); } } } } // remove existing zoo php handlers foreach (ConfigurationElement element in zooPhpHandlersToRemove) { handlerCollection.Remove(element); } // add zoo php handlers ConfigurationElement zooPhpX86 = handlerCollection.CreateElement(); zooPhpX86.SetAttributeValue("name", "php.pipe#x86"); zooPhpX86.SetAttributeValue("scriptProcessor", enabledPhpEngine); zooPhpX86.SetAttributeValue("path", "*.php"); zooPhpX86.SetAttributeValue("verb", "*"); zooPhpX86.SetAttributeValue("modules", "HeliconZoo_x86"); zooPhpX86.SetAttributeValue("preCondition", "bitness32"); zooPhpX86.SetAttributeValue("resourceType", "Unspecified"); zooPhpX86.SetAttributeValue("requireAccess", "Script"); handlerCollection.AddAt(0, zooPhpX86); ConfigurationElement zooPhpX64 = handlerCollection.CreateElement(); zooPhpX64.SetAttributeValue("name", "php.pipe#x64"); zooPhpX64.SetAttributeValue("scriptProcessor", enabledPhpEngine); zooPhpX64.SetAttributeValue("path", "*.php"); zooPhpX64.SetAttributeValue("verb", "*"); zooPhpX64.SetAttributeValue("modules", "HeliconZoo_x64"); zooPhpX64.SetAttributeValue("preCondition", "bitness64"); zooPhpX64.SetAttributeValue("resourceType", "Unspecified"); zooPhpX64.SetAttributeValue("requireAccess", "Script"); handlerCollection.AddAt(1, zooPhpX64); // process index.php as default document ConfigurationSection defaultDocument = appConfig.GetSection("system.webServer/defaultDocument", siteId); RegisterPhpDefaultDocument(defaultDocument); } }
static void AllowIP(string IP) { using (ServerManager serverManager = new ServerManager()) { Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration(); Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "BrandsMarketing"); ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection(); var ipAddress = ipSecurityCollection.Where(x => x["ipAddress"].ToString() == IP).SingleOrDefault(); ipSecurityCollection.Remove(ipAddress); serverManager.CommitChanges(); } }