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 Microsoft.Web.Administration.ConfigurationElement FindElement(Microsoft.Web.Administration.ConfigurationElementCollection collection, string elementTagName, params string[] keyValues) { foreach (Microsoft.Web.Administration.ConfigurationElement element in collection) { if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase)) { bool matches = true; for (int i = 0; i < keyValues.Length; i += 2) { object o = element.GetAttributeValue(keyValues[i]); string value = null; if (o != null) { value = o.ToString(); } if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase)) { matches = false; break; } } if (matches) { return(element); } } } return(null); }
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); }
/// <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 ConfigurationElementCollection GetCollection(string collectionName) { var child = ChildElements[collectionName]; if (child != null) { return(child.GetCollection()); } var schema = Schema.ChildElementSchemas[collectionName]; if (schema == null) { return(null); } var result = new ConfigurationElementCollection(collectionName, schema, this, this.InnerEntity, null); ChildElements.Add(result); return(result.GetCollection()); }
private void CheckName(string name) { bool isAttribute = (_lockType & ConfigurationLockType.Attribute) == ConfigurationLockType.Attribute; if (_valid_name_hash == null) { _valid_name_hash = new Hashtable(); foreach (ConfigurationAttributeSchema prop in _element.Schema.AttributeSchemas) { _valid_name_hash.Add(prop.Name, true); } /* add the add/remove/clear names of the * default collection if there is one */ if (!isAttribute) { ConfigurationElementCollection c = _element.GetCollection(); foreach (var addName in _element.Schema.CollectionSchema.AddElementNames.Split(',')) { _valid_name_hash.Add(addName, true); } _valid_name_hash.Add(c.Schema.CollectionSchema.ClearElementName, true); _valid_name_hash.Add(c.Schema.CollectionSchema.RemoveElementName, true); } string[] valid_name_array = new string[_valid_name_hash.Keys.Count]; _valid_name_hash.Keys.CopyTo(valid_name_array, 0); _valid_names = String.Join(",", valid_name_array); } if (_valid_name_hash[name] == null) { throw new ServerManagerException( String.Format("The {2} '{0}' is not valid in the locked list for this section. The following {3} can be locked: '{1}'", name, _valid_names, isAttribute ? "attribute" : "element", isAttribute ? "attributes" : "elements")); } }
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); }
private void CheckName(string name) { bool isAttribute = (_lockType & ConfigurationLockType.Attribute) == ConfigurationLockType.Attribute; if (_valid_name_hash == null) { _valid_name_hash = new Hashtable(); foreach (ConfigurationAttributeSchema prop in _element.Schema.AttributeSchemas) { _valid_name_hash.Add(prop.Name, true); } /* add the add/remove/clear names of the * default collection if there is one */ if (!isAttribute) { ConfigurationElementCollection c = _element.GetCollection(); foreach (var addName in _element.Schema.CollectionSchema.AddElementNames.Split(',')) { _valid_name_hash.Add(addName, true); } _valid_name_hash.Add(c.Schema.CollectionSchema.ClearElementName, true); _valid_name_hash.Add(c.Schema.CollectionSchema.RemoveElementName, true); } string[] valid_name_array = new string[_valid_name_hash.Keys.Count]; _valid_name_hash.Keys.CopyTo(valid_name_array, 0); _valid_names = String.Join(",", valid_name_array); } if (_valid_name_hash[name] == null) { throw new ArgumentException($"lockAttributes contains unknown attribute '{name}'"); } }
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> { string.Format("{0} {1}", 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 = new StringBuilder(); foreach (ConfigurationElement item in filesCollection) { indexes.AppendFormat("{0},", item.RawAttributes["value"]); } if (indexes.Length > 0) { indexes.Length--; } variables.Add("indexes", new List <string> { indexes.ToString() }); 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"] : string.Format("{0}/{1}", 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 = new StringBuilder(); foreach (ConfigurationElement item in hiddenSegmentsCollection) { segments.AppendFormat("{0},", item["segment"]); } if (segments.Length > 0) { segments.Length--; } variables.Add("denydirs", new List <string> { segments.ToString() }); 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(string.Format("{0}={1}", item.Key, line)); } } var fileName = Path.Combine("siteconf", application.ToFileName()); File.WriteAllLines(fileName, rows); } else { using (var client = GetClient()) { HttpResponseMessage response = await client.PutAsJsonAsync(string.Format("api/site/{0}", application.ToFileName()), variables); if (response.IsSuccessStatusCode) { } } } }
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; }
private void context_EndRequest(object sender, EventArgs e) { HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; // // Check for the X-Send headers // bool remove = false; // we check for temp first, so any software that wants to use it can, as a fallback, // also set the regular x-sendfile header in case on that system this version of the // dll is not deployed string filePath = response.Headers.Get("X-Sendfile-Temporary"); if (filePath == null) { filePath = response.Headers.Get("X-Sendfile"); } else { remove = true; } if (filePath == null) { filePath = response.Headers.Get("X-Accel-Redirect"); } if (filePath != null) { // // Determine the file path and ready the response // if (ConfigurationManager.AppSettings["XSendDir"] != null) { filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath); // if there is a base path set (file will be located above this) } else if (ConfigurationManager.AppSettings["XAccelLocation"] != null) { filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]); } response.Clear(); // Clears output buffer response.Headers.Remove("X-Sendfile"); // Remove unwanted headers response.Headers.Remove("X-Sendfile-Temporary"); response.Headers.Remove("X-Accel-Redirect"); // // Set the cache policy // if (ConfigurationManager.AppSettings["XSendCache"] == null) { response.Cache.SetCacheability(HttpCacheability.NoCache); } else if (ConfigurationManager.AppSettings["XSendCache"] == "Public") { response.Cache.SetCacheability(HttpCacheability.Public); } else { response.Cache.SetCacheability(HttpCacheability.Private); } // // Get the file information and set headers appropriately // FileInfo file = new FileInfo(filePath); if (!file.Exists) { throw new HttpException(404, "File_does_not_exist"); } if (filePath[filePath.Length - 1] == '.') { throw new HttpException(404, "File_does_not_exist"); } response.Cache.SetLastModified(file.LastWriteTimeUtc); response.Headers.Remove("Content-Length"); if (!String.IsNullOrEmpty(request.ServerVariables["HTTP_RANGE"])) { //request for chunk RangeDownload(file.FullName, HttpContext.Current); } else { response.AddHeader("Content-Length", file.Length.ToString()); response.AppendHeader("Accept-Ranges", "bytes"); // // Check if we want to detect the mime type of the current content // if (ConfigurationManager.AppSettings["XSendMime"] == null) { Microsoft.Web.Administration.ConfigurationSection staticContentSection = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent"); Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); var mt = staticContentCollection.Where( a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower() ).FirstOrDefault(); if (mt != null) { response.ContentType = mt.GetAttributeValue("mimeType").ToString(); } else { response.ContentType = "application/octet-stream"; } } // // Set a content disposition if it is not already set by the application // if (response.Headers["Content-Disposition"] == null) { response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name); } // // Send the file without loading it into memory // response.TransmitFile(file.FullName); if (remove) { // note that the little Flush below causes the full file to load into // IIS memory but we need that be able to delete it // Note that on many concurrent requests, that means each request // will load the full output into memory, which wil remain there for // a while because the client needs time to download. Unfortunately // I found no way to dispose of the file once the last byte has been // sent response.Flush(); File.Delete(file.FullName); } } } }
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(); } } }
private void context_EndRequest(object sender, EventArgs e) { HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; // // Check for the X-Send headers // string filePath = response.Headers.Get("X-Sendfile"); if (filePath == null) { filePath = response.Headers.Get("X-Accel-Redirect"); } if (filePath != null) { // // Determine the file path and ready the response // if (ConfigurationManager.AppSettings["XSendDir"] != null) { filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath); // if there is a base path set (file will be located above this) } else if (ConfigurationManager.AppSettings["XAccelLocation"] != null) { filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]); } response.Clear(); // Clears output buffer response.Headers.Remove("X-Sendfile"); // Remove unwanted headers response.Headers.Remove("X-Accel-Redirect"); // // Set the cache policy // if (ConfigurationManager.AppSettings["XSendCache"] == null) { response.Cache.SetCacheability(HttpCacheability.NoCache); } else if (ConfigurationManager.AppSettings["XSendCache"] == "Public") { response.Cache.SetCacheability(HttpCacheability.Public); } else { response.Cache.SetCacheability(HttpCacheability.Private); } // // Get the file information and set headers appropriately // FileInfo file = new FileInfo(filePath); if (!file.Exists) { throw new HttpException(404, "File_does_not_exist"); } if (filePath[filePath.Length - 1] == '.') { throw new HttpException(404, "File_does_not_exist"); } response.Cache.SetLastModified(file.LastWriteTimeUtc); response.Headers.Remove("Content-Length"); if (!String.IsNullOrEmpty(request.ServerVariables["HTTP_RANGE"])) { //request for chunk RangeDownload(file.FullName, HttpContext.Current); } else { response.AddHeader("Content-Length", file.Length.ToString()); response.AppendHeader("Accept-Ranges", "bytes"); // // Check if we want to detect the mime type of the current content // if (ConfigurationManager.AppSettings["XSendMime"] == null) { Microsoft.Web.Administration.ConfigurationSection staticContentSection = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent"); Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); var mt = staticContentCollection.Where( a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower() ).FirstOrDefault(); if (mt != null) { response.ContentType = mt.GetAttributeValue("mimeType").ToString(); } else { response.ContentType = "application/octet-stream"; } } // // Set a content disposition if it is not already set by the application // if (response.Headers["Content-Disposition"] == null) { response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name); } // // Send the file without loading it into memory // response.TransmitFile(file.FullName); } } }
private void context_EndRequest(object sender, EventArgs e) { HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; // // Check for the X-Send headers // string filePath = response.Headers.Get("X-Sendfile"); if (filePath == null) { filePath = response.Headers.Get("X-Accel-Redirect"); } if (filePath != null) { // // Determine the file path and ready the response // if (ConfigurationManager.AppSettings["XSendDir"] != null) { filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath); // if there is a base path set (file will be located above this) } else if (ConfigurationManager.AppSettings["XAccelLocation"] != null) { filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]); } response.Clear(); // Clears output buffer response.Headers.Remove("X-Sendfile"); // Remove unwanted headers response.Headers.Remove("X-Accel-Redirect"); // // Set the cache policy // if (ConfigurationManager.AppSettings["XSendCache"] == null) { response.Cache.SetCacheability(HttpCacheability.NoCache); } else if (ConfigurationManager.AppSettings["XSendCache"] == "Public") { response.Cache.SetCacheability(HttpCacheability.Public); } else { response.Cache.SetCacheability(HttpCacheability.Private); } // // Get the file information and set headers appropriately // if (!FileUtil.FileExists(filePath)) { throw new HttpException(404, "File_does_not_exist"); } if (filePath[filePath.Length - 1] == '.') { throw new HttpException(404, "File_does_not_exist"); } FileInfo file = new FileInfo(filePath); response.Cache.SetLastModified(file.LastWriteTimeUtc); response.Headers.Remove("Content-Length"); DateTime dateTime = new DateTime(file.LastWriteTime.Year, file.LastWriteTime.Month, file.LastWriteTime.Day, file.LastWriteTime.Hour, file.LastWriteTime.Minute, file.LastWriteTime.Second, 0); DateTime now = DateTime.Now; string range = request.Headers["Range"]; // // Call into .net static file handler to do the heavy lifting for us // Massive hacks. Should work for all version of .net // // http://dotnetinside.com/framework/v2.0.50727/System.Web/StaticFileHandler // http://typedescriptor.net/browse/types/7243-System.Web.StaticFileHandler // http://stackoverflow.com/questions/7829478/how-to-execute-a-private-static-method-with-optional-parameters-via-reflection // // var genEtag = typeof(System.Web.StaticFileHandler).GetMethod("GenerateETag", BindingFlags.Static | BindingFlags.NonPublic); string etag = genEtag.Invoke(obj: null, parameters: new object[] { HttpContext.Current, dateTime, now }); var rangeRequest = typeof(System.Web.StaticFileHandler).GetMethod("ProcessRangeRequest", BindingFlags.Static | BindingFlags.NonPublic); if (StringUtil.StringStartsWithIgnoreCase(range, "bytes") && rangeRequest.Invoke(obj: null, parameters: new object[] { HttpContext.Current, filePath, file.Length, range, etag, dateTime })) { return; } response.AddHeader("Content-Length", file.Length.ToString()); response.AppendHeader("Accept-Ranges", "bytes"); response.Cache.SetIgnoreRangeRequests(); // // Check if we want to detect the mime type of the current content // if (ConfigurationManager.AppSettings["XSendMime"] == null) { Microsoft.Web.Administration.ConfigurationSection staticContentSection = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent"); Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); var mt = staticContentCollection.Where( a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower() ).FirstOrDefault(); if (mt != null) { response.ContentType = mt.GetAttributeValue("mimeType").ToString(); } else { response.ContentType = "application/octet-stream"; } } // // Set a content disposition if it is not already set by the application // if (response.Headers["Content-Disposition"] == null) { response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name); } // // Send the file without loading it into memory // response.TransmitFile(file.FullName); } }