/// <summary> /// Create the web site. /// </summary> /// <param name="appPoolName">Name of the application pool.</param> /// <param name="name">The name.</param> /// <param name="protocol">The protocol.</param> /// <param name="ip">The ip.</param> /// <param name="domains">The domains.</param> /// <param name="port">The port.</param> /// <param name="physicalPath">The physical path.</param> public static void CreateWebSite(string appPoolName, string name, string protocol, string ip, string[] domains, string port, string physicalPath) { var iisManager = new ServerManager(); var site = GetSite(iisManager, name, false); if (site != null) { site.Stop(); } if (site == null) { var mainDomain = domains[0]; string bindingInfo = string.Format(@"{0}:{1}:{2}", ip, port, mainDomain); iisManager.Sites.Add(name, "http", bindingInfo, physicalPath); iisManager.CommitChanges(); site = iisManager.Sites.First(s => s.Name == name); site.ServerAutoStart = true; site.Applications.First().ApplicationPoolName = appPoolName; } //add bindings // AddBindings(site, domains.Select(d => string.Format(@"{0}:{1}:{2}", ip, port, d)).ToArray(), protocol); //change application pool // AddApplicationPools(appPoolName, site); //save changes // iisManager.CommitChanges(); Thread.Sleep(1000); site.Start(); }
public override bool OnStart() { try { Trace.Listeners.Add(new DiagnosticMonitorTraceListener()); Trace.TraceInformation("Starting Gateway"); // Enable IIS Reverse Proxy using (ServerManager server = new ServerManager()) { var proxySection = server.GetApplicationHostConfiguration().GetSection("system.webServer/proxy"); proxySection.SetAttributeValue("enabled", true); server.CommitChanges(); Trace.TraceInformation("Enabled Reverse Proxy"); // Patch web.config rewrite rules string serviceStem = RoleEnvironment.GetConfigurationSettingValue("Gateway.ServiceStem"); if (!String.Equals(serviceStem, "nuget.org", StringComparison.OrdinalIgnoreCase)) { RewriteStem(server, serviceStem); } server.CommitChanges(); } return base.OnStart(); } catch (Exception ex) { Trace.TraceError("Error starting gateway: {0}", ex.ToString()); throw; } }
public void DeleteSite(string applicationName) { var iis = new IIS.ServerManager(); // Get the app pool for this application string appPoolName = GetAppPool(applicationName); IIS.ApplicationPool kuduPool = iis.ApplicationPools[appPoolName]; // Make sure the acls are gone RemoveAcls(applicationName, appPoolName); if (kuduPool == null) { // If there's no app pool then do nothing return; } DeleteSite(iis, GetLiveSite(applicationName)); DeleteSite(iis, GetDevSite(applicationName)); // Don't delete the physical files for the service site DeleteSite(iis, GetServiceSite(applicationName), deletePhysicalFiles: false); iis.CommitChanges(); string appPath = _pathResolver.GetApplicationPath(applicationName); var sitePath = _pathResolver.GetLiveSitePath(applicationName); var devPath = _pathResolver.GetDeveloperApplicationPath(applicationName); try { kuduPool.StopAndWait(); DeleteSafe(sitePath); DeleteSafe(devPath); DeleteSafe(appPath); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { // Remove the app pool and commit changes iis.ApplicationPools.Remove(iis.ApplicationPools[appPoolName]); iis.CommitChanges(); // Clear out the app pool user profile directory if it exists string userDir = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile).TrimEnd(Path.DirectorySeparatorChar)); string appPoolDirectory = Path.Combine(userDir, appPoolName); DeleteSafe(appPoolDirectory); } }
public static void CreateIISWebSite(string siteName, string siteAddress, string physicalPath) { ServerManager iisManager = new ServerManager(); Site site = iisManager.Sites[siteName]; if (site != null) { iisManager.Sites.Remove(iisManager.Sites[siteName]); iisManager.CommitChanges(); } iisManager.Sites.Add(siteName, "http", string.Concat("*:80:", siteAddress), physicalPath); iisManager.CommitChanges(); iisManager.Dispose(); }
public void DeleteSite(string applicationName) { var iis = new IIS.ServerManager(); // Get the app pool for this application string appPoolName = GetAppPool(applicationName); IIS.ApplicationPool kuduPool = iis.ApplicationPools[appPoolName]; // Make sure the acls are gone RemoveAcls(applicationName, appPoolName); if (kuduPool == null) { // If there's no app pool then do nothing return; } DeleteSite(iis, GetLiveSite(applicationName)); DeleteSite(iis, GetDevSite(applicationName)); // Don't delete the physical files for the service site DeleteSite(iis, GetServiceSite(applicationName), deletePhysicalFiles: false); iis.CommitChanges(); string appPath = _pathResolver.GetApplicationPath(applicationName); var sitePath = _pathResolver.GetLiveSitePath(applicationName); var devPath = _pathResolver.GetDeveloperApplicationPath(applicationName); try { kuduPool.StopAndWait(); DeleteSafe(sitePath); DeleteSafe(devPath); DeleteSafe(appPath); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { // Remove the app pool and commit changes iis.ApplicationPools.Remove(iis.ApplicationPools[appPoolName]); iis.CommitChanges(); } }
/// <summary> /// 创建应用程序池 /// </summary> /// <param name="appPoolName"></param> /// <param name="version"></param> /// <param name="isClassic"></param> public static void CreateAppPool(string appPoolName, string version, bool isClassic) { if (!DoesExistAppPool(appPoolName)) { try { DirectoryEntry newpool; DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"); newpool = appPools.Children.Add(appPoolName, "IIsApplicationPool"); newpool.CommitChanges(); } catch { ServerManager iisManager = new ServerManager(); ApplicationPool appPool = iisManager.ApplicationPools.Add(appPoolName); appPool.AutoStart = true; appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated; appPool.ManagedRuntimeVersion = "v2.0"; iisManager.CommitChanges(); } } ServerManager manager = new ServerManager(); manager.ApplicationPools[appPoolName].ManagedRuntimeVersion = version; manager.ApplicationPools[appPoolName].ManagedPipelineMode = isClassic ? ManagedPipelineMode.Classic : ManagedPipelineMode.Integrated; manager.ApplicationPools[appPoolName].ProcessModel.IdentityType = ProcessModelIdentityType.LocalSystem; manager.CommitChanges(); }
public static void DeleteApplicationPool(string poolName) { ServerManager iisManager = new ServerManager(); ApplicationPool appPool = iisManager.ApplicationPools[poolName]; iisManager.ApplicationPools.Remove(appPool); iisManager.CommitChanges(); }
public static void CreateApplication(string applicationPath, string folderPath, string applicationPoolName) { ServerManager iisManager = new ServerManager(); iisManager.Sites[0].Applications.Add(applicationPath, folderPath); iisManager.Sites[0].Applications[applicationPath].ApplicationPoolName = applicationPoolName; iisManager.CommitChanges(); }
private static void AddHttpsBinding(Session session, string installPath, X509Certificate2 cert, string certExportPath) { using (var mgr = new ServerManager()) { session.Log("Searching for site in IIS."); var site = mgr.Sites.FirstOrDefault(s => s.Applications.Any(app => app.VirtualDirectories.Any(x => AreSameDirectory(x.PhysicalPath, installPath)))); if(site == null) { session.Log("Site not found. This could be caused by the presence of IIS Express."); throw new Exception("Could not find site. This could be caused by the presence of IIS Express."); } session.Log("Site found ({0}), checking for https bindings.", site.Name); var httpsBinding = site.Bindings.FirstOrDefault(x => x.Protocol == "https" && x.BindingInformation.StartsWith("*:443")); if (httpsBinding != null) { session.Log("Binding already present ({0}), it will not be changed.", httpsBinding.BindingInformation); session.Log("Certificate sha1 fingerprint={0};", ToHex(httpsBinding.CertificateHash)); ExportPublicKey(session, certExportPath, httpsBinding.CertificateHash, httpsBinding.CertificateStoreName); return; } session.Log("Usable https binding was not found, adding new one."); var storeName = new X509Store(StoreName.My, StoreLocation.LocalMachine).Name; site.Bindings.Add("*:443:", cert.GetCertHash(), storeName); ExportPublicKey(session, certExportPath, cert.GetCertHash(), storeName); session.Log("Certificate sha1 fingerprint={0};", ToHex(cert.GetCertHash())); mgr.CommitChanges(); session.Log("Binding added."); } }
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 bool TryCreateDeveloperSite(string applicationName, out string siteUrl) { var iis = new IIS.ServerManager(); string devSiteName = GetDevSite(applicationName); IIS.Site site = iis.Sites[devSiteName]; if (site == null) { // Get the path to the dev site string siteRoot = _pathResolver.GetDeveloperApplicationPath(applicationName); string webRoot = Path.Combine(siteRoot, Constants.WebRoot); int sitePort = CreateSite(iis, applicationName, devSiteName, webRoot); // Ensure the directory is created FileSystemHelpers.EnsureDirectory(webRoot); // Map a path called app to the site root under the service site MapServiceSitePath(iis, applicationName, Constants.MappedDevSite, siteRoot); iis.CommitChanges(); siteUrl = String.Format("http://localhost:{0}/", sitePort); return(true); } siteUrl = String.Format("http://localhost:{0}/", site.Bindings[0].EndPoint.Port); return(false); }
public void CreateWebDavRule(string organizationId, string folder, WebDavFolderRule rule) { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection authoringRulesSection = config.GetSection("system.webServer/webdav/authoringRules", string.Format("{0}/{1}/{2}", _Setting.Domain, organizationId, folder)); ConfigurationElementCollection authoringRulesCollection = authoringRulesSection.GetCollection(); ConfigurationElement addElement = authoringRulesCollection.CreateElement("add"); if (rule.Users.Any()) { addElement["users"] = string.Join(", ", rule.Users.Select(x => x.ToString()).ToArray()); } if (rule.Roles.Any()) { addElement["roles"] = string.Join(", ", rule.Roles.Select(x => x.ToString()).ToArray()); } if (rule.Pathes.Any()) { addElement["path"] = string.Join(", ", rule.Pathes.ToArray()); } addElement["access"] = rule.AccessRights; authoringRulesCollection.Add(addElement); serverManager.CommitChanges(); } }
public void AddBindings(string siteName, IEnumerable<Binding> bindings) { using (ServerManager manager = new ServerManager(_applicationHostPath)) { Site site = manager.Sites.SingleOrDefault(s => s.Name == siteName); if (site == null) { throw new InvalidOperationException("Site does not exist: " + siteName); } bool configurationChanged = false; foreach (Binding binding in bindings) { bool bindingChanged = binding.AddTo(site.Bindings); if (bindingChanged) { configurationChanged = true; } } if (configurationChanged) { manager.CommitChanges(); } } }
public void Stuff() { var sv = new ServerManager(); Site existing = sv.Sites["Test"]; if (existing != null) { sv.Sites.Remove(existing); } Site s = sv.Sites.Add("Test", @"c:\Users\Public\Documents\Development\LondonTyrant\LondonTyrant", 5000); foreach (var attr in s.Attributes) { Console.WriteLine("{0}: {1}", attr.Name, attr.Value); } foreach (var app in s.Applications) { foreach (var vd in app.VirtualDirectories) { Console.WriteLine(vd.Path); Console.WriteLine(vd.PhysicalPath); } } foreach (var b in s.Bindings) { Console.WriteLine(b.BindingInformation); } sv.CommitChanges(); }
public bool AddBinding(string username, string fqdn) { var result = false; using (var serverManager = new ServerManager()) { var bindingInformation = string.Format("*:80:{0}", fqdn); const string bindingProtocol = "http"; foreach (var site in serverManager.Sites) { var app = site.Applications.FirstOrDefault(); if (app == null || string.IsNullOrWhiteSpace(app.ApplicationPoolName)) continue; var pool = serverManager.ApplicationPools.FirstOrDefault(x => x.Name == app.ApplicationPoolName && x.ProcessModel.UserName == username); if (pool == null) continue; var binding = site.Bindings.FirstOrDefault(x => x.BindingInformation == bindingInformation && x.Protocol == bindingProtocol); if (binding == null) { site.Bindings.Add(bindingInformation, bindingProtocol); result = true; } } serverManager.CommitChanges(); } return result; }
public static void CreateSite(SiteDTO siteDto) { var mgr = new ServerManager(); var sites = mgr.Sites; CreateSiteInIIS(sites, siteDto); mgr.CommitChanges(); }
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 override void Build(IBounce bounce) { var iisServer = new ServerManager(); var existingSite = iisServer.Sites[Name.Value]; if (!SiteUpToDate(existingSite)) { bounce.Log.Info("installing IIS website at: " + Directory.Value); RemoveWebSiteIfExtant(iisServer); var site = iisServer.Sites.Add(Name.Value, Directory.Value, Port.Value); if (Bindings != null && Bindings.Value != null) { site.Bindings.Clear(); foreach (var binding in Bindings.Value) { site.Bindings.Add(binding.Information.Value, binding.Protocol.Value); } } if (ApplicationPoolNameIfSet != null) { site.ApplicationDefaults.ApplicationPoolName = ApplicationPoolNameIfSet; } iisServer.CommitChanges(); } else { bounce.Log.Info("IIS website already installed"); } }
private static void CreateWebSiteIfNotExists() { var manager = new ServerManager(); if (!manager.ApplicationPoolExists(Configuration.SiteName)) { var pool = manager.ApplicationPools.Add(Configuration.SiteName); pool.ManagedRuntimeVersion = "v4.0"; manager.CommitChanges(); } else { ConsoleHelper.WriteLine(ConsoleColor.Yellow, string.Format("ApplicationPool {0} already exists, creation skiped", Configuration.SiteName)); } if (!manager.SiteExists(Configuration.SiteName)) { var site = manager.Sites.Add(Configuration.SiteName, Configuration.DeploymentPath, Configuration.SitePort); site.ApplicationDefaults.ApplicationPoolName = Configuration.SiteName; manager.CommitChanges(); } else { ConsoleHelper.WriteLine(ConsoleColor.Yellow, string.Format("Site {0} already exists, creation skiped", Configuration.SiteName)); } }
public static void AddServers(string farmName, IPEndPoint[] endpoints) { using (var serverManager = new ServerManager()) { var config = serverManager.GetApplicationHostConfiguration(); var webFarmsSection = config.GetSection("webFarms"); var webFarmsCollection = webFarmsSection.GetCollection(); var webFarmElement = FindElement(webFarmsCollection, "webFarm", "name", farmName); if (webFarmElement == null) throw new InvalidOperationException("Element not found!"); var webFarmCollection = webFarmElement.GetCollection(); foreach (var endpoint in endpoints) { var server = FindElement(webFarmCollection, "server", "address", endpoint.Address.ToString()); if (null != server) { // server already exists continue; } var serverElement = webFarmCollection.CreateElement("server"); serverElement["address"] = endpoint.Address.ToString(); var applicationRequestRoutingElement = serverElement.GetChildElement("applicationRequestRouting"); applicationRequestRoutingElement["httpPort"] = endpoint.Port; webFarmCollection.Add(serverElement); } serverManager.CommitChanges(); } }
/// <summary> /// Executes this instance. /// </summary> /// <returns>A value indicating whether the task completed successfully.</returns> public override bool Execute() { var serverManager = new ServerManager(); // Find the root web site that this web application will be created under. var site = serverManager.Sites.FirstOrDefault(s => string.Equals(s.Name, this.WebSiteName, StringComparison.OrdinalIgnoreCase)); if (site == null) { Log.LogMessage(MessageImportance.Low, TaskStrings.NoMatchingWebSiteFound, this.WebSiteName); return true; } if (this.VirtualPaths.Length == 0) { // Nothing to do. return true; } foreach (ITaskItem path in this.VirtualPaths) { var app = site.Applications.FirstOrDefault(a => string.Equals(a.Path, path.ItemSpec, StringComparison.OrdinalIgnoreCase)); if (app != null) { site.Applications.Remove(app); Log.LogMessage(MessageImportance.Normal, TaskStrings.DeletedWebApplication, app.Path); } else { Log.LogMessage(MessageImportance.Low, TaskStrings.WebApplicationNotFoundSoNotDeleted, path.ItemSpec); } } serverManager.CommitChanges(); return true; }
public static void AddUIModuleProvider(string name, string type) { using (ServerManager mgr = new ServerManager()) { // First register the Module Provider Configuration adminConfig = mgr.GetAdministrationConfiguration(); ConfigurationSection moduleProvidersSection = adminConfig.GetSection("moduleProviders"); ConfigurationElementCollection moduleProviders = moduleProvidersSection.GetCollection(); if (FindByAttribute(moduleProviders, "name", name) == null) { ConfigurationElement moduleProvider = moduleProviders.CreateElement(); moduleProvider.SetAttributeValue("name", name); moduleProvider.SetAttributeValue("type", type); moduleProviders.Add(moduleProvider); } // Now register it so that all Sites have access to this module ConfigurationSection modulesSection = adminConfig.GetSection("modules"); ConfigurationElementCollection modules = modulesSection.GetCollection(); if (FindByAttribute(modules, "name", name) == null) { ConfigurationElement module = modules.CreateElement(); module.SetAttributeValue("name", name); modules.Add(module); } mgr.CommitChanges(); } }
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 backgroundAssociatedSiteHttpRedirect_DoWork(object sender, DoWorkEventArgs e) { IEnumerable<TreeNode> selectedNoneWwwSiteNodes = e.Argument as IEnumerable<TreeNode>; int i = 1; int totalCount = selectedNoneWwwSiteNodes.Count(); foreach (TreeNode siteNode in selectedNoneWwwSiteNodes) { if (!backgroundAssociatedSiteHttpRedirect.CancellationPending) { Node site = (Node)siteNode.Tag; bool enableChecked = true; string destination = string.Format("http://www.{0}", siteNode.Text); bool enableExactDestination = false; bool enableChildOnly = false; string httpResponseStatus = "永久(301)"; try { using (ServerManager serverManager = new ServerManager()) { Configuration config = serverManager.GetWebConfiguration(site.Site.Name); SetHttpRedirectElement(enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus, config); string log = DateTime.Now.ToString() + ":" + string.Format("为站点 {0} 添加Http重定向,启用:{1},重定向目标:{2},定向到确切目标:{3},定向到非子目录中的内容:{4},状态代码:{5}", siteNode.Text, enableChecked, destination, enableExactDestination, enableChildOnly, httpResponseStatus); backgroundAssociatedSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); serverManager.CommitChanges(); } } catch (Exception exception) { string log = DateTime.Now.ToString() + ":" + string.Format("为站点 {0} 添加Http重定向失败,错误详情如下", siteNode.Name) + exception.ToString(); backgroundSiteHttpRedirect.ReportProgress(i * 100 / totalCount, log); } i++; } } }
public static void PurgeAllSites() { using (var serverManager = new ServerManager()) { var applications = serverManager.ApplicationPools.ToList(); if (!applications.Any()) { // There is nothing to do. return; } foreach (var appPool in applications) { appPool.Stop(); // Find all site & applications using this pool. var sites = serverManager.Sites .Where(site => site.Applications.Any(x => x.ApplicationPoolName == appPool.Name)).ToList(); foreach (var site in sites) { serverManager.Sites[site.Name].Stop(); serverManager.Sites.Remove(site); } serverManager.ApplicationPools.Remove(appPool); } serverManager.CommitChanges(); } }
public static void AddSite(string siteName, string hostName = null) { using (var sm = new ServerManager()) { var invalidChars = SiteCollection.InvalidSiteNameCharacters(); if (siteName.IndexOfAny(invalidChars) > -1) { throw new Exception("Invalid Site Name: {0}".Fmt(siteName)); } var appPool = AddAppPool(sm, siteName, "v4.0", ManagedPipelineMode.Integrated); if (sm.Sites[siteName] != null) { return; } string path = "C:\\inetpub\\wwwroot\\{0}".Fmt(siteName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Set HostName info for binding var site = hostName != null ? sm.Sites.Add(siteName, "http", "*:80:{0}".Fmt(hostName), path) : sm.Sites.Add(siteName, path, 80); site.ServerAutoStart = true; site.ApplicationDefaults.ApplicationPoolName = appPool.Name; sm.CommitChanges(); AddMsDeployAccessToSite(sm, siteName, "CISetupWizard"); } }
/// <summary> /// This method iterates over the used application pools of the Azure Cloud Services Web role and changes the application pool account from NETWORK to SYSTEM. This is /// needed to make to code work with the Microsoft Online Services Sign In Assistant /// </summary> private void SetAppPoolIdentity() { Action<string> iis7fix = (appPoolName) => { bool committed = false; while (!committed) { try { using (ServerManager sm = new ServerManager()) { var applicationPool = sm.ApplicationPools[appPoolName]; applicationPool.ProcessModel.IdentityType = ProcessModelIdentityType.LocalSystem; sm.CommitChanges(); committed = true; } } catch (FileLoadException fle) { Trace.TraceError("Trying again because: " + fle.Message); } } }; var sitename = RoleEnvironment.CurrentRoleInstance.Id + "_Web"; var appPoolNames = new ServerManager().Sites[sitename].Applications.Select(app => app.ApplicationPoolName).ToList(); appPoolNames.ForEach(iis7fix); }
public static ConfigurationElement GetOrCreateFarm(string farmName) { using (var serverManager = new ServerManager()) { var config = serverManager.GetApplicationHostConfiguration(); var webFarmsSection = config.GetSection("webFarms"); var webFarmsCollection = webFarmsSection.GetCollection(); var el = FindElement(webFarmsCollection, "webFarm", "name", farmName); if (null != el) { return el; } var webFarmElement = webFarmsCollection.CreateElement("webFarm"); webFarmElement["name"] = farmName; webFarmsCollection.Add(webFarmElement); var applicationRequestRoutingElement = webFarmElement.GetChildElement("applicationRequestRouting"); var affinityElement = applicationRequestRoutingElement.GetChildElement("affinity"); affinityElement["useCookie"] = true; serverManager.CommitChanges(); CreateReWriteRule(farmName); return webFarmElement; } }
public static void iis7_create_site(string siteName, string applicationPoolName, string path, int port) { if (string.IsNullOrEmpty(siteName)) throw new StringIsNullOrEmptyException("siteName"); if (string.IsNullOrEmpty(applicationPoolName)) throw new StringIsNullOrEmptyException("applicationPoolName"); if (string.IsNullOrEmpty(path)) throw new StringIsNullOrEmptyException("path"); using (var iisManager = new ServerManager()) { if (iisManager.Sites[siteName] != null) throw new SiteAlreadyExistsException(siteName); iisManager.Sites.Add(siteName, new DirectoryInfo(path.Replace('\\', '/')).FullName, port); ApplicationPool applicationPool = iisManager.ApplicationPools[applicationPoolName]; if (applicationPool == null) iisManager.ApplicationPools.Add(applicationPoolName); iisManager.Sites[siteName].Applications[0].ApplicationPoolName = applicationPoolName; iisManager.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(); } }
private static void DeployApi(DeployCommandOptions deployCommandOptions) { var iisManager = new ServerManager(); const string name = "speedymailer.api"; var exists = iisManager.Sites.Any(x => x.Name == name); var apiPreReleasePath = Path.Combine(deployCommandOptions.BaseDirectory, "Release", "Api"); var apiPath = Path.Combine(deployCommandOptions.BaseDirectory, "Api"); if (exists) { var site = iisManager.Sites[name]; site.Stop(); iisManager.CommitChanges(); DeleteAppFolder(apiPath, apiPreReleasePath); site.Start(); iisManager.CommitChanges(); } else { DeleteAppFolder(apiPath, apiPreReleasePath); var hasPool = iisManager.ApplicationPools.Any(x => x.Name == name); if (!hasPool) { iisManager.ApplicationPools.Add(name); iisManager.CommitChanges(); var pool = iisManager.ApplicationPools[name]; pool.ManagedRuntimeVersion = "v4.0"; iisManager.CommitChanges(); } iisManager.Sites.Add(name, "http", string.Format("*:80:api.{0}", deployCommandOptions.BaseUrl), apiPath); var site = iisManager.Sites[name]; var app = site.Applications["/"]; app.ApplicationPoolName = name; iisManager.CommitChanges(); } }
public void Save() { var iis = new ServerManager(); var site = iis.Sites[SiteName]; site.Applications.Add(Path, Directory); iis.CommitChanges(); }
private void configurePhysicalPath(string configFilePath, string applicationPath) { using (var serverManager = new ServerManager(configFilePath)) { serverManager.Sites[0].Applications[0].VirtualDirectories[0].PhysicalPath = applicationPath; serverManager.CommitChanges(); } }
public Site CreateSite(string applicationName) { var iis = new IIS.ServerManager(); try { // Create the service site for this site string serviceSiteName = GetServiceSite(applicationName); int serviceSitePort = CreateSite(iis, applicationName, serviceSiteName, _pathResolver.ServiceSitePath); // Create the main site string siteName = GetLiveSite(applicationName); string siteRoot = _pathResolver.GetLiveSitePath(applicationName); string webRoot = Path.Combine(siteRoot, Constants.WebRoot); FileSystemHelpers.EnsureDirectory(webRoot); File.WriteAllText(Path.Combine(webRoot, "index.html"), @"<html> <head> <title>The web site is under construction</title> <style type=""text/css""> BODY { color: #444444; background-color: #E5F2FF; font-family: verdana; margin: 0px; text-align: center; margin-top: 100px; } H1 { font-size: 16pt; margin-bottom: 4px; } </style> </head> <body> <h1>The web site is under construction</h1><br/> </body> </html>"); int sitePort = CreateSite(iis, applicationName, siteName, webRoot); // Map a path called app to the site root under the service site MapServiceSitePath(iis, applicationName, Constants.MappedLiveSite, siteRoot); // Commit the changes to iis iis.CommitChanges(); // Give IIS some time to create the site and map the path // REVIEW: Should we poll the site's state? Thread.Sleep(1000); return(new Site { ServiceUrl = String.Format("http://localhost:{0}/", serviceSitePort), SiteUrl = String.Format("http://localhost:{0}/", sitePort), }); } catch { DeleteSite(applicationName); throw; } }
private static void EnsureDefaultDocument(IIS.ServerManager iis) { Configuration applicationHostConfiguration = iis.GetApplicationHostConfiguration(); ConfigurationSection defaultDocumentSection = applicationHostConfiguration.GetSection("system.webServer/defaultDocument"); ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files"); if (!filesCollection.Any(ConfigurationElementContainsHostingStart)) { ConfigurationElement addElement = filesCollection.CreateElement("add"); addElement["value"] = HostingStartHtml; filesCollection.Add(addElement); iis.CommitChanges(); } }
public bool AddSiteBinding(string applicationName, string siteBinding, SiteType siteType) { IIS.Site site; if (!siteBinding.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { siteBinding = "http://" + siteBinding; } var uri = new Uri(siteBinding); try { using (var iis = new IIS.ServerManager()) { if (!IsAvailable(uri.Host, uri.Port, iis)) { return(false); } if (siteType == SiteType.Live) { site = iis.Sites[GetLiveSite(applicationName)]; } else { site = iis.Sites[GetServiceSite(applicationName)]; } if (site != null) { site.Bindings.Add("*:" + uri.Port + ":" + uri.Host, "http"); iis.CommitChanges(); Thread.Sleep(1000); } } return(true); } catch { return(false); } }
private static async Task <IIS.ApplicationPool> EnsureAppPool(IIS.ServerManager iis, string appName) { string appPoolName = GetAppPool(appName); var kuduAppPool = iis.ApplicationPools[appPoolName]; if (kuduAppPool == null) { iis.ApplicationPools.Add(appPoolName); iis.CommitChanges(); kuduAppPool = iis.ApplicationPools[appPoolName]; kuduAppPool.ManagedPipelineMode = IIS.ManagedPipelineMode.Integrated; kuduAppPool.ManagedRuntimeVersion = "v4.0"; kuduAppPool.AutoStart = true; kuduAppPool.ProcessModel.LoadUserProfile = true; await kuduAppPool.WaitForState(IIS.ObjectState.Started); } return(kuduAppPool); }
public void SetSiteWebRoot(string applicationName, string siteRoot) { var iis = new IIS.ServerManager(); string siteName = GetDevSite(applicationName); IIS.Site site = iis.Sites[siteName]; if (site != null) { string sitePath = _pathResolver.GetLiveSitePath(applicationName); string webRoot = Path.Combine(sitePath, Constants.WebRoot, siteRoot); // Change the web root site.Applications[0].VirtualDirectories[0].PhysicalPath = webRoot; iis.CommitChanges(); Thread.Sleep(1000); } }
private static IIS.ApplicationPool EnsureAppPool(IIS.ServerManager iis, string appName) { string appPoolName = GetAppPool(appName); var kuduAppPool = iis.ApplicationPools[appPoolName]; if (kuduAppPool == null) { iis.ApplicationPools.Add(appPoolName); iis.CommitChanges(); kuduAppPool = iis.ApplicationPools[appPoolName]; kuduAppPool.ManagedPipelineMode = IIS.ManagedPipelineMode.Integrated; kuduAppPool.ManagedRuntimeVersion = "v4.0"; kuduAppPool.AutoStart = true; kuduAppPool.ProcessModel.LoadUserProfile = true; } EnsureDefaultDocument(iis); return(kuduAppPool); }
public bool RemoveSiteBinding(string applicationName, string siteBinding, SiteType siteType) { IIS.Site site; try { using (var iis = new IIS.ServerManager()) { if (siteType == SiteType.Live) { site = iis.Sites[GetLiveSite(applicationName)]; } else { site = iis.Sites[GetServiceSite(applicationName)]; } if (site != null) { var uri = new Uri(siteBinding); var binding = site.Bindings.FirstOrDefault(x => x.Host.Equals(uri.Host) && x.EndPoint.Port.Equals(uri.Port) && x.Protocol.Equals(uri.Scheme)); if (binding != null) { site.Bindings.Remove(binding); iis.CommitChanges(); Thread.Sleep(1000); } } } return(true); } catch { return(false); } }
private IIS.ApplicationPool EnsureAppPool(IIS.ServerManager iis, string appName) { string appPoolName = GetAppPool(appName); var kuduAppPool = iis.ApplicationPools[appPoolName]; if (kuduAppPool == null) { iis.ApplicationPools.Add(appPoolName); iis.CommitChanges(); kuduAppPool = iis.ApplicationPools[appPoolName]; kuduAppPool.Enable32BitAppOnWin64 = true; kuduAppPool.ManagedPipelineMode = IIS.ManagedPipelineMode.Integrated; kuduAppPool.ManagedRuntimeVersion = "v4.0"; kuduAppPool.AutoStart = true; kuduAppPool.ProcessModel.LoadUserProfile = false; kuduAppPool.WaitForState(IIS.ObjectState.Started); SetupAcls(appName, appPoolName); } return(kuduAppPool); }
public async Task <Site> CreateSiteAsync(string applicationName) { using (var iis = new IIS.ServerManager()) { try { // Determine the host header values List <string> siteBindings = GetDefaultBindings(applicationName, _settingsResolver.SitesBaseUrl); List <string> serviceSiteBindings = GetDefaultBindings(applicationName, _settingsResolver.ServiceSitesBaseUrl); // Create the service site for this site string serviceSiteName = GetServiceSite(applicationName); var serviceSite = await CreateSiteAsync(iis, applicationName, serviceSiteName, _pathResolver.ServiceSitePath, serviceSiteBindings); // Create the main site string siteName = GetLiveSite(applicationName); string root = _pathResolver.GetApplicationPath(applicationName); string siteRoot = _pathResolver.GetLiveSitePath(applicationName); string webRoot = Path.Combine(siteRoot, Constants.WebRoot); FileSystemHelpers.EnsureDirectory(webRoot); File.WriteAllText(Path.Combine(webRoot, HostingStartHtml), @"<html> <head> <title>This web site has been successfully created</title> <style type=""text/css""> BODY { color: #444444; background-color: #E5F2FF; font-family: verdana; margin: 0px; text-align: center; margin-top: 100px; } H1 { font-size: 16pt; margin-bottom: 4px; } </style> </head> <body> <h1>This web site has been successfully created</h1><br/> </body> </html>"); var site = await CreateSiteAsync(iis, applicationName, siteName, webRoot, siteBindings); // Map a path called _app to the site root under the service site MapServiceSitePath(iis, applicationName, Constants.MappedSite, root); // Commit the changes to iis iis.CommitChanges(); // Wait for the site to start await site.WaitForState(ObjectState.Started); var serviceUrls = new List <string>(); foreach (var url in serviceSite.Bindings) { serviceUrls.Add(String.Format("http://{0}:{1}/", String.IsNullOrEmpty(url.Host) ? "localhost" : url.Host, url.EndPoint.Port)); } // Set initial ScmType state to LocalGit var settings = new RemoteDeploymentSettingsManager(serviceUrls.First() + "settings"); await settings.SetValue(SettingsKeys.ScmType, ScmType.LocalGit); var siteUrls = new List <string>(); foreach (var url in site.Bindings) { siteUrls.Add(String.Format("http://{0}:{1}/", String.IsNullOrEmpty(url.Host) ? "localhost" : url.Host, url.EndPoint.Port)); } return(new Site { ServiceUrls = serviceUrls, SiteUrls = siteUrls }); } catch { try { DeleteSiteAsync(applicationName).Wait(); } catch { // Don't let it throw if we're unable to delete a failed creation. } throw; } } }
public Site CreateSite(string applicationName) { var iis = new IIS.ServerManager(); try { // Determine the host header values List <string> siteBindings = GetDefaultBindings(applicationName, _settingsResolver.SitesBaseUrl); List <string> serviceSiteBindings = GetDefaultBindings(applicationName, _settingsResolver.ServiceSitesBaseUrl); // Create the service site for this site string serviceSiteName = GetServiceSite(applicationName); var serviceSite = CreateSite(iis, applicationName, serviceSiteName, _pathResolver.ServiceSitePath, serviceSiteBindings); IIS.Binding serviceSiteBinding = EnsureBinding(serviceSite.Bindings); int serviceSitePort = serviceSiteBinding.EndPoint.Port; // Create the main site string siteName = GetLiveSite(applicationName); string siteRoot = _pathResolver.GetLiveSitePath(applicationName); string webRoot = Path.Combine(siteRoot, Constants.WebRoot); FileSystemHelpers.EnsureDirectory(webRoot); File.WriteAllText(Path.Combine(webRoot, "index.html"), @"<html> <head> <title>The web site is under construction</title> <style type=""text/css""> BODY { color: #444444; background-color: #E5F2FF; font-family: verdana; margin: 0px; text-align: center; margin-top: 100px; } H1 { font-size: 16pt; margin-bottom: 4px; } </style> </head> <body> <h1>The web site is under construction</h1><br/> </body> </html>"); var site = CreateSite(iis, applicationName, siteName, webRoot, siteBindings); IIS.Binding iisBinding = EnsureBinding(site.Bindings); int sitePort = iisBinding.EndPoint.Port; // Map a path called app to the site root under the service site MapServiceSitePath(iis, applicationName, Constants.MappedSite, siteRoot); // Commit the changes to iis iis.CommitChanges(); // Give IIS some time to create the site and map the path // REVIEW: Should we poll the site's state? Thread.Sleep(1000); var siteUrls = new List <string>(); foreach (var url in site.Bindings) { siteUrls.Add(String.Format("http://{0}:{1}/", String.IsNullOrEmpty(url.Host) ? "localhost" : url.Host, url.EndPoint.Port)); } return(new Site { ServiceUrl = String.Format("http://localhost:{0}/", serviceSitePort), SiteUrls = siteUrls }); } catch { DeleteSite(applicationName); throw; } }
public override bool OnStart() { try { using (var server = new ServerManager()) { const string site = "Web"; var siteName = string.Format("{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, site); var config = server.GetApplicationHostConfiguration(); ConfigureAccessSection(config, siteName); var iisClientCertificateMappingAuthenticationSection = EnableIisClientCertificateMappingAuthentication(config, siteName); ConfigureManyToOneMappings(iisClientCertificateMappingAuthenticationSection); ConfigureOneToOneMappings(iisClientCertificateMappingAuthenticationSection); server.CommitChanges(); } } catch (Exception e) { Debug.WriteLine(e); // handle error here } return base.OnStart(); }