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); }
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(); } }
/// <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); } }
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 async Task LoadAsync(Application application, string file, string appName, SortedDictionary <string, List <string> > variables) { if (variables == null) { if (Credentials == null) { var rows = File.ReadAllLines(file); variables = new SortedDictionary <string, List <string> >(); foreach (var line in rows) { var index = line.IndexOf('#'); var content = index == -1 ? line : line.Substring(0, index); var parts = content.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { continue; } var key = parts[0].Trim().ToLowerInvariant(); var value = parts[1].Trim(); if (variables.ContainsKey(key)) { variables[key].Add(value); continue; } variables.Add(key, new List <string> { value }); } } else { using (var client = GetClient()) { HttpResponseMessage response = await client.GetAsync(string.Format("api/app/get/{0}", appName)); if (response.IsSuccessStatusCode) { variables = (SortedDictionary <string, List <string> >) await response.Content.ReadAsAsync(typeof(SortedDictionary <string, List <string> >)); } } } } variables.Load(new List <string> { "false" }, "usehttps"); variables.Load(new List <string> { "*" }, "hosts", "host"); variables.Load(new List <string> { IPAddress.Any.ToString() }, "addr", "address"); variables.Load(new List <string> { "80" }, "port"); var root = variables.Load(new List <string> { "/ /var/www/default" }, "root")[0]; var split = root.IndexOf(' '); if (split == -1 || split == 0) { throw new ServerManagerException("invalid root mapping"); } var virtualDirectory = new VirtualDirectory(null, application.VirtualDirectories); virtualDirectory.Path = root.Substring(0, split); virtualDirectory.PhysicalPath = root.Substring(split + 1); application.VirtualDirectories.Add(virtualDirectory); var configuration = application.GetWebConfiguration(); var defaultDocument = configuration.GetSection("system.webServer/defaultDocument"); defaultDocument["enabled"] = true; var collection = defaultDocument.GetCollection("files"); collection.Clear(); var names = variables.Load(new List <string> { Constants.DefaultDocumentList }, "indexes", "indexs")[0]; var pageNames = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var name in pageNames) { var file1 = collection.CreateElement(); file1.Attributes["value"].Value = name; collection.Add(file1); } ConfigurationSection httpLoggingSection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/httpLogging", application.Location); var dontLog = Convert.ToBoolean(variables.Load(new List <string> { "false" }, "nolog")[0]); httpLoggingSection["dontLog"] = dontLog; var ipSecuritySection = application.Server.GetApplicationHostConfiguration().GetSection("system.webServer/security/ipSecurity", application.Location); ipSecuritySection["enableReverseDns"] = false; ipSecuritySection["allowUnlisted"] = true; ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection(); ipSecurityCollection.Clear(); var deny = variables.Load(new List <string>(), "denyfrom", "ip.deny"); foreach (var denyEntry in deny) { var denyItems = denyEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in denyItems) { ConfigurationElement addElement = ipSecurityCollection.CreateElement("add"); if (item.Contains("/")) { var parts = item.Split('/'); addElement["ipAddress"] = parts[0]; addElement["subnetMask"] = parts[1]; } else { addElement["ipAddress"] = item; } addElement["allowed"] = false; ipSecurityCollection.Add(addElement); } } var allow = variables.Load(new List <string>(), "allowfrom", "ip.allow"); foreach (var allowEntry in allow) { var allowItems = allowEntry.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in allowItems) { ConfigurationElement addElement = ipSecurityCollection.CreateElement("add"); if (item.Contains("/")) { var parts = item.Split('/'); addElement["ipAddress"] = parts[0]; addElement["subnetMask"] = parts[1]; } else { addElement["ipAddress"] = item; } addElement["allowed"] = true; ipSecurityCollection.Add(addElement); } } ConfigurationSection requestFilteringSection = configuration.GetSection("system.webServer/security/requestFiltering"); ConfigurationElement hiddenSegmentsElement = requestFilteringSection.ChildElements["hiddenSegments"]; ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection(); hiddenSegmentsCollection.Clear(); var hidden = variables.Load(new List <string> { string.Empty }, "denydirs")[0]; var hiddenItems = hidden.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in hiddenItems) { ConfigurationElement add = hiddenSegmentsCollection.CreateElement("add"); add["segment"] = item; hiddenSegmentsCollection.Add(add); } ConfigurationSection httpErrorsSection = configuration.GetSection("system.webServer/httpErrors"); ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection(); httpErrorsCollection.Clear(); Debug.Assert(variables != null, "variables != null"); if (variables.ContainsKey("nofile")) { var error = variables["nofile"][0]; ConfigurationElement errorElement = httpErrorsCollection.CreateElement("error"); errorElement["statusCode"] = 404; errorElement["subStatusCode"] = 0; errorElement["prefixLanguageFilePath"] = @"%SystemDrive%\inetpub\custerr"; errorElement["responseMode"] = "ExecuteURL"; errorElement["path"] = error; httpErrorsCollection.Add(errorElement); variables.Remove("nofile"); } var urlCompressionSection = configuration.GetSection("system.webServer/urlCompression"); urlCompressionSection["doStaticCompression"] = Convert.ToBoolean(variables.Load(new List <string> { "true" }, "usegzip")[0]); ConfigurationSection httpProtocolSection = configuration.GetSection("system.webServer/httpProtocol"); httpProtocolSection["allowKeepAlive"] = Convert.ToBoolean(variables.Load(new List <string> { "true" }, "keep_alive")[0]); ConfigurationSection rulesSection = configuration.GetSection("system.webServer/rewrite/rules"); ConfigurationElementCollection rulesCollection = rulesSection.GetCollection(); rulesCollection.Clear(); if (variables.ContainsKey("rewrite")) { var rules = variables["rewrite"]; for (int i = 0; i < rules.Count; i++) { var rule = rules[i]; ConfigurationElement ruleElement = rulesCollection.CreateElement("rule"); ruleElement["name"] = @"rule" + i; ruleElement["enabled"] = true; ruleElement["patternSyntax"] = 0; ruleElement["stopProcessing"] = false; var parts = rule.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); ConfigurationElement matchElement = ruleElement.GetChildElement("match"); matchElement["ignoreCase"] = parts[0].EndsWith("/i", StringComparison.Ordinal); matchElement["url"] = parts[0].EndsWith("/i", StringComparison.Ordinal) ? parts[0].Substring(0, parts[0].Length - 2) : parts[0]; ConfigurationElement actionElement = ruleElement.GetChildElement("action"); actionElement["type"] = 2; actionElement["url"] = parts[1]; actionElement["appendQueryString"] = true; rulesCollection.Add(ruleElement); } variables.Remove("rewrite"); } application.Extra = variables; }
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(); } } }