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(); } }
public static ActionResult EnumerateIISWebSitesAndAppPools(Session session) { if (session == null) { throw new ArgumentNullException("session"); } session.Log("EnumerateIISWebSitesAndAppPools: Begin"); // Check if running with admin rights and if not, log a message to let them know why it's failing. if (!HasAdminRights()) { session.Log("EnumerateIISWebSitesAndAppPools: ATTEMPTING TO RUN WITHOUT ADMIN RIGHTS"); return ActionResult.Failure; } session.Log("EnumerateIISWebSitesAndAppPools: Getting the IIS 7 management object"); ActionResult result; using (var iisManager = new ServerManager()) { result = EnumSitesIntoComboBox(session, iisManager); if (result == ActionResult.Success) { result = EnumAppPoolsIntoComboBox(session, iisManager); } } session.Log("EnumerateIISWebSitesAndAppPools: End"); return result; }
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(); }
private void RewriteStem(ServerManager server, string serviceStem) { // Get the site config const string siteBaseName = "Web"; // From the CSDEF file string siteName = RoleEnvironment.CurrentRoleInstance.Id + "_" + siteBaseName; var config = server.Sites[siteName].GetWebConfiguration(); var rewriteSection = config.GetSection("system.webServer/rewrite"); if (rewriteSection == null) { var rewriteRules = rewriteSection.GetChildElement("rules"); if (rewriteRules != null) { foreach (var rewriteRule in rewriteRules.ChildElements) { var action = rewriteRules.GetChildElement("action"); if (action != null) { string url = action.GetAttributeValue("url"); string rewritten = url.Replace("nuget.org", serviceStem); if (!String.Equals(url, rewritten, StringComparison.Ordinal)) { action.SetAttributeValue("url", rewritten); } } } } } }
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; } }
/// <summary> /// Stops an AppPool on the local system. /// </summary> /// <param name="name">Name of the AppPool to stop.</param> public override void StopAppPool(string name) { using (var manager = new ServerManager()) { var pool = manager.ApplicationPools[name]; if (pool == null) throw new IISException("Application pool not found.", MessageLevel.Warning); try { pool.Stop(); } catch (COMException ex) { if ((uint) ex.ErrorCode == 0x80070426) throw new IISException("Application pool is already stopped.", ex, MessageLevel.Information); else throw new IISException("Could not stop application pool: " + ex.Message); } catch (Exception ex) { throw new IISException("Could not stop application pool: " + ex.Message); } } }
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 ApplicationInstanceStatus GetStatus(string applicationInstanceName) { ApplicationInstanceStatus rv = ApplicationInstanceStatus.Unknown; try { using (var manager = new ServerManager()) { ApplicationPool applicationPool = GetApplicationPool(manager, applicationInstanceName); Site applicationSite = GetSite(manager, applicationInstanceName); if (applicationSite.State == ObjectState.Stopped || applicationPool.State == ObjectState.Stopped) { rv = ApplicationInstanceStatus.Stopped; } else if (applicationSite.State == ObjectState.Stopping || applicationPool.State == ObjectState.Stopping) { rv = ApplicationInstanceStatus.Stopping; } else if (applicationSite.State == ObjectState.Starting || applicationPool.State == ObjectState.Starting) { rv = ApplicationInstanceStatus.Starting; } else if (applicationSite.State == ObjectState.Started || applicationPool.State == ObjectState.Started) { rv = ApplicationInstanceStatus.Started; } } } catch (Exception ex) { log.Error(ex); } return rv; }
protected override void DoProcessing() { using (ServerManager serverManager = new ServerManager()) { ServerManagerWrapper serverManagerWrapper = new ServerManagerWrapper(serverManager, this.SiteName, this.VirtualPath); PHPConfigHelper configHelper = new PHPConfigHelper(serverManagerWrapper); PHPIniFile phpIniFile = configHelper.GetPHPIniFile(); PHPIniSetting setting = Helper.FindSetting(phpIniFile.Settings, Name); if (setting == null) { if (ShouldProcess(Name)) { RemoteObjectCollection<PHPIniSetting> settings = new RemoteObjectCollection<PHPIniSetting>(); settings.Add(new PHPIniSetting(Name, Value, Section)); configHelper.AddOrUpdatePHPIniSettings(settings); } } else { ArgumentException ex = new ArgumentException(String.Format(Resources.SettingAlreadyExistsError, Name)); ReportNonTerminatingError(ex, "InvalidArgument", ErrorCategory.InvalidArgument); } } }
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 void Validate(string webSiteName, string hostName, string portNumber) { if (string.IsNullOrEmpty(webSiteName)) throw new ArgumentNullException("webSiteName"); ValidateHostName(hostName); ValidatePortNumber(portNumber); using (var serverManager = new ServerManager()) { int portNumberValue = Convert.ToInt32(portNumber); foreach (var site in serverManager.Sites.Where(s => !string.Equals(s.Name, webSiteName, StringComparison.Ordinal) && s.State == ObjectState.Started)) { foreach (var binding in site.Bindings.Where(i => i.Protocol.Equals("http") || i.Protocol.Equals("https"))) { if (binding.EndPoint.Port != portNumberValue) continue; if (string.IsNullOrEmpty(hostName) && string.IsNullOrEmpty(binding.Host)) { throw new Exception(string.Format("The specified port number '{0}' already used by '{1}' site.", binding.EndPoint.Port, site.Name)); } else if (string.Equals(binding.Host, hostName, StringComparison.Ordinal)) { throw new Exception(string.Format("The specified host name '{0}' and port Number '{1}' already used by '{2}' site.", binding.Host, binding.EndPoint.Port, site.Name)); } } } } }
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 Microsoft.Web.Administration.Site GetIisSiteById(int iisId) { using (var manager = new ServerManager()) { return manager.Sites.SingleOrDefault(x => x.Id == iisId); } }
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(); } }
private void RemoveWebSiteIfExtant(ServerManager server) { var site = server.Sites[Name.Value]; if (site != null) { server.Sites.Remove(site); } }
private static void DeployApp(DeployCommandOptions deployCommandOptions) { var iisManager = new ServerManager(); const string name = "speedymailer.app"; var exists = iisManager.Sites.Any(x => x.Name == name); var appPreReleasePath = Path.Combine(deployCommandOptions.BaseDirectory, "Release", "App"); var appPath = Path.Combine(deployCommandOptions.BaseDirectory, "App"); if (exists) { var site = iisManager.Sites[name]; site.Stop(); iisManager.CommitChanges(); DeleteAppFolder(appPath, appPreReleasePath); site.Start(); iisManager.CommitChanges(); } else { DeleteAppFolder(appPath, appPreReleasePath); iisManager.Sites.Add(name, "http", string.Format("*:80:app.{0}", deployCommandOptions.BaseUrl), appPath); var site = iisManager.Sites[name]; iisManager.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 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"); } }
/// <summary> /// When overridden in a derived class, executes the task. /// </summary> protected override void InternalExecute() { try { this.iisServerManager = System.Environment.MachineName != this.MachineName ? ServerManager.OpenRemote(this.MachineName) : new ServerManager(); if (!this.SiteExists()) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The website: {0} was not found on: {1}", this.Website, this.MachineName)); return; } switch (this.TaskAction) { case DeleteTaskAction: this.Delete(); break; case CheckExistsTaskAction: this.CheckExists(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } finally { if (this.iisServerManager != null) { this.iisServerManager.Dispose(); } } }
/// <summary> /// Removes the specified UI Module by name /// </summary> public static void RemoveUIModuleProvider(string name) { using (ServerManager mgr = new ServerManager()) { // First remove it from the sites Configuration adminConfig = mgr.GetAdministrationConfiguration(); ConfigurationSection modulesSection = adminConfig.GetSection("modules"); ConfigurationElementCollection modules = modulesSection.GetCollection(); ConfigurationElement module = FindByAttribute(modules, "name", name); if (module != null) { modules.Remove(module); } // now remove the ModuleProvider ConfigurationSection moduleProvidersSection = adminConfig.GetSection("moduleProviders"); ConfigurationElementCollection moduleProviders = moduleProvidersSection.GetCollection(); ConfigurationElement moduleProvider = FindByAttribute(moduleProviders, "name", name); if (moduleProvider != null) { moduleProviders.Remove(moduleProvider); } mgr.CommitChanges(); } }
public static void CreateSite(SiteDTO siteDto) { var mgr = new ServerManager(); var sites = mgr.Sites; CreateSiteInIIS(sites, siteDto); mgr.CommitChanges(); }
public static string GetVirtualDirPath(string name) { if (isLocal) { return localDeploymentsPaths[name]; } try { using (ServerManager serverManager = new ServerManager()) { var paths = serverManager.Sites .Where(s => s.Name.EndsWith("_" + name)) .SelectMany(site => site.Applications .SelectMany(ar => ar.VirtualDirectories .Select(vr => vr.PhysicalPath))) .FirstOrDefault(); var result = paths ?? VirtualDirPath; // logger.Info("GetVirtualDirPath: Path before return {0}", result); return result; } } catch { ;} return VirtualDirPath; }
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"); } }
public static IEnumerable<ServiceInstanceInfo> GetServiceInstances() { var serviceInstances = new List<ServiceInstanceInfo>(); var tcpPort = GetPortForProtocol("net.tcp"); var httpPort = GetPortForProtocol("http"); var httpsPort = GetPortForProtocol("https"); using (ServerManager serverManager = new ServerManager()) { var site = serverManager.Sites.FirstOrDefault(s => s.Name == WebApplicationName); foreach (var app in site.Applications.Where(a => a.Path != "/" && a.VirtualDirectories.Count > 0)) { var servicesName = app.Path.TrimStart('/'); var physicalPath = app.VirtualDirectories[0].PhysicalPath; var serviceInstanceInfo = new ServiceInstanceInfo() { ServicesName = servicesName, ServicesHost = Environment.MachineName.ToLowerInvariant(), PhysicalPath = physicalPath, ProductVersion = BusinessServiceConfiguration.GetProductVersion(physicalPath), TcpPort = tcpPort, HttpPort = httpPort, HttpsPort = httpsPort }; serviceInstances.Add(serviceInstanceInfo); } } return serviceInstances; }
protected override void DoProcessing() { using (var serverManager = new ServerManager()) { var serverManagerWrapper = new ServerManagerWrapper(serverManager, SiteName, VirtualPath); var configHelper = new PHPConfigHelper(serverManagerWrapper); var phpIniFile = configHelper.GetPHPIniFile(); WildcardPattern wildcard = PrepareWildcardPattern(Name); foreach (var extension in phpIniFile.Extensions) { if (!wildcard.IsMatch(extension.Name)) { continue; } if (Status == PHPExtensionStatus.Disabled && extension.Enabled) { continue; } if (Status == PHPExtensionStatus.Enabled && !extension.Enabled) { continue; } var extensionItem = new PHPExtensionItem(extension); WriteObject(extensionItem); } } }
public static ApplicationPool GetAppPoolForApp(string serviceInstancePath) { using (ServerManager serverManager = new ServerManager()) { return GetAppPoolForApp(serverManager, serviceInstancePath); } }
/// <summary> /// Initializes a new instance of the <see cref="IisWebSite"/> class. /// </summary> /// <param name="siteName"> /// The site Name. /// </param> /// <param name="sitePhysicalPath"> /// The site Physical Path. /// </param> /// <param name="sitePort"> /// The site Port. /// </param> /// <param name="pool"> /// The pool. /// </param> public IisWebSite(string siteName, string sitePhysicalPath, int sitePort, IisApplicationPool pool) { try { this.serverManager = new ServerManager(); string relativePath = Path.Combine(Environment.CurrentDirectory, sitePhysicalPath); string absolutePath = Path.GetFullPath(relativePath); this.Port = sitePort; this.Name = siteName; if (this.serverManager.Sites[siteName] != null) { // if site exists we need to remove it because it may contain wrong physical path. this.Remove(); } this.site = this.serverManager.Sites.Add(siteName, absolutePath, sitePort); this.site.ServerAutoStart = true; this.site.Applications[0].ApplicationPoolName = pool.Name; this.currentPool = pool; this.serverManager.CommitChanges(); Trace.TraceInformation( "IISWebSite {0} deployed successfully.", siteName); } catch (Exception ex) { Trace.TraceError("Exception occured while deploying IIS Website: {0}. The exception thrown was {1}", siteName, ex.Message); throw; } }
public bool AddWebSite(string username, string password, string fqdn, string homeDirectory, string bindingProtocol, string bindingInformation) { using (var serverManager = new ServerManager()) { var pool = serverManager.ApplicationPools.Add(ReverseFqdn(fqdn)); pool.ManagedRuntimeVersion = "v4.0"; if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { pool.ProcessModel.IdentityType = ProcessModelIdentityType.ApplicationPoolIdentity; } else { pool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser; pool.ProcessModel.UserName = username; pool.ProcessModel.Password = password; } var site = serverManager.Sites.Add(ReverseFqdn(fqdn), bindingProtocol, bindingInformation, homeDirectory); var app = site.Applications.FirstOrDefault(); app.ApplicationPoolName = pool.Name; serverManager.CommitChanges(); } AddIndexFile(homeDirectory, fqdn); return true; }
protected override void DoProcessing() { using (var serverManager = new ServerManager()) { var serverManagerWrapper = new ServerManagerWrapper(serverManager, SiteName, VirtualPath); var configHelper = new PHPConfigHelper(serverManagerWrapper); var phpIniFile = configHelper.GetPHPIniFile(); var nameWildcard = PrepareWildcardPattern(Name); var sectionWildcard = PrepareWildcardPattern(Section); foreach (var setting in phpIniFile.Settings) { if (!nameWildcard.IsMatch(setting.Name)) { continue; } if (!sectionWildcard.IsMatch(setting.Section)) { continue; } var settingItem = new PHPSettingItem(setting); WriteObject(settingItem); } } }
public void RunDeploy(String[] args) { if (args.Length < 3) { Console.Error.WriteLine("rdfWebDeploy: Error: 3 Arguments are required in order to use the -deploy mode, type rdfWebDeploy -help to see usage summary"); return; } if (args.Length > 3) { if (!this.SetOptions(args.Skip(3).ToArray())) { Console.Error.WriteLine("rdfWebDeploy: Deployment aborted since one/more options were not valid"); return; } } if (this._noLocalIIS) { Console.WriteLine("rdfWebDeploy: No Local IIS Server available so switching to -xmldeploy mode"); XmlDeploy xdeploy = new XmlDeploy(); xdeploy.RunXmlDeploy(args); return; } //Define the Server Manager object Admin.ServerManager manager = null; try { //Connect to the Server Manager if (!this._noIntegratedRegistration) { manager = new Admin.ServerManager(); } //Open the Configuration File System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(args[1], this._site); Console.Out.WriteLine("rdfWebDeploy: Opened the Web.config file for the specified Web Application"); //Detect Folders String appFolder = Path.GetDirectoryName(config.FilePath); String binFolder = Path.Combine(appFolder, "bin\\"); String appDataFolder = Path.Combine(appFolder, "App_Data\\"); if (!Directory.Exists(binFolder)) { Directory.CreateDirectory(binFolder); Console.WriteLine("rdfWebDeploy: Created a bin\\ directory for the web application"); } if (!Directory.Exists(appDataFolder)) { Directory.CreateDirectory(appDataFolder); Console.WriteLine("rdfWebDeploy: Created an App_Data\\ directory for the web application"); } //Deploy dotNetRDF and required DLLs to the bin directory of the application String sourceFolder = RdfWebDeployHelper.ExecutablePath; IEnumerable <String> dlls = RdfWebDeployHelper.RequiredDLLs; if (this._sql) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredSqlDLLs); } if (this._virtuoso) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredVirtuosoDLLs); } if (this._fulltext) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredFullTextDLLs); } foreach (String dll in dlls) { if (File.Exists(Path.Combine(sourceFolder, dll))) { File.Copy(Path.Combine(sourceFolder, dll), Path.Combine(binFolder, dll), true); Console.WriteLine("rdfWebDeploy: Deployed " + dll + " to the web applications bin directory"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Required DLL " + dll + " which needs deploying to the web applications bin directory could not be found"); return; } } //Deploy the configuration file to the App_Data directory if (File.Exists(args[2])) { File.Copy(args[2], Path.Combine(appDataFolder, args[2]), true); Console.WriteLine("rdfWebDeploy: Deployed the configuration file to the web applications App_Data directory"); } else if (!File.Exists(Path.Combine(appDataFolder, args[2]))) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to continue deployment as the configuration file " + args[2] + " could not be found either locally for deployment to the App_Data folder or already present in the App_Data folder"); return; } //Set the AppSetting for the configuration file config.AppSettings.Settings.Remove("dotNetRDFConfig"); config.AppSettings.Settings.Add("dotNetRDFConfig", "~/App_Data/" + Path.GetFileName(args[2])); Console.WriteLine("rdfWebDeploy: Set the \"dotNetRDFConfig\" appSetting to \"~/App_Data/" + Path.GetFileName(args[2]) + "\""); //Now load the Configuration Graph from the App_Data folder Graph g = new Graph(); FileLoader.Load(g, Path.Combine(appDataFolder, args[2])); Console.WriteLine("rdfWebDeploy: Successfully deployed required DLLs and appSettings"); Console.WriteLine(); //Get the sections of the Configuration File we want to edit HttpHandlersSection handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection; if (handlersSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Handlers section of the web applications Web.Config file"); return; } //Detect Handlers from the Configution Graph and deploy IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); IUriNode dnrType = g.CreateUriNode(new Uri(ConfigurationLoader.PropertyType)); IUriNode httpHandler = g.CreateUriNode(new Uri(ConfigurationLoader.ClassHttpHandler)); //Deploy for IIS Classic Mode if (!this._noClassicRegistration) { Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Classic Mode"); foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject)) { if (n.NodeType == NodeType.Uri) { String handlerPath = ((IUriNode)n).Uri.AbsolutePath; INode type = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault(); if (type == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified"); continue; } if (type.NodeType == NodeType.Literal) { String handlerType = ((ILiteralNode)type).Value; //First remove any existing registration handlersSection.Handlers.Remove("*", handlerPath); //Then add the new registration handlersSection.Handlers.Add(new HttpHandlerAction(handlerPath, handlerType, "*")); Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal"); continue; } } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node"); } } //Deploy Negotiate by File Extension if appropriate if (this._negotiate) { HttpModulesSection modulesSection = config.GetSection("system.web/httpModules") as HttpModulesSection; if (modulesSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file"); return; } modulesSection.Modules.Remove("NegotiateByExtension"); modulesSection.Modules.Add(new HttpModuleAction("NegotiateByExtension", "VDS.RDF.Web.NegotiateByFileExtension")); Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module"); } Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Classic Mode"); } //Save the completed Configuration File config.Save(ConfigurationSaveMode.Minimal); Console.WriteLine(); //Deploy for IIS Integrated Mode if (!this._noIntegratedRegistration) { Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Integrated Mode"); Admin.Configuration adminConfig = manager.GetWebConfiguration(this._site, args[1]); Admin.ConfigurationSection newHandlersSection = adminConfig.GetSection("system.webServer/handlers"); Admin.ConfigurationElementCollection newHandlers = newHandlersSection.GetCollection(); foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject)) { if (n.NodeType == NodeType.Uri) { String handlerPath = ((IUriNode)n).Uri.AbsolutePath; INode type = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault(); if (type == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified"); continue; } if (type.NodeType == NodeType.Literal) { String handlerType = ((ILiteralNode)type).Value; //First remove any existing registration foreach (Admin.ConfigurationElement oldReg in newHandlers.Where(el => el.GetAttributeValue("name").Equals(handlerPath)).ToList()) { newHandlers.Remove(oldReg); } //Then add the new registration Admin.ConfigurationElement reg = newHandlers.CreateElement("add"); reg["name"] = handlerPath; reg["path"] = handlerPath; reg["verb"] = "*"; reg["type"] = handlerType; newHandlers.AddAt(0, reg); Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal"); continue; } } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node"); } //Deploy Negotiate by File Extension if appropriate if (this._negotiate) { Admin.ConfigurationSection newModulesSection = adminConfig.GetSection("system.webServer/modules"); if (newModulesSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file"); return; } //First remove the Old Module Admin.ConfigurationElementCollection newModules = newModulesSection.GetCollection(); foreach (Admin.ConfigurationElement oldReg in newModules.Where(el => el.GetAttribute("name").Equals("NegotiateByExtension")).ToList()) { newModules.Remove(oldReg); } //Then add the new Module Admin.ConfigurationElement reg = newModules.CreateElement("add"); reg["name"] = "NegotiateByExtension"; reg["type"] = "VDS.RDF.Web.NegotiateByFileExtension"; newModules.AddAt(0, reg); Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module"); } } manager.CommitChanges(); Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Integrated Mode"); } } catch (ConfigurationException configEx) { Console.Error.WriteLine("rdfWebDeploy: Configuration Error: " + configEx.Message); } catch (Exception ex) { Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message); Console.Error.WriteLine(ex.StackTrace); } finally { if (manager != null) { manager.Dispose(); } } }
public 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; } } }
private List <IISAppPoolStateInfo> AppPoolStatesIIS7Plus(string hostName) { List <IISAppPoolStateInfo> appPools = new List <IISAppPoolStateInfo>(); try { if (UsePerfCounter && System.Diagnostics.PerformanceCounterCategory.Exists("APP_POOL_WAS", hostName)) { //Try performance counters System.Diagnostics.PerformanceCounterCategory pcCat = new System.Diagnostics.PerformanceCounterCategory("APP_POOL_WAS", hostName); //getting instance names string[] instances = pcCat.GetInstanceNames(); foreach (string instanceName in instances) { if (instanceName != "_Total") { System.Diagnostics.PerformanceCounter pc = (from pcCacheEntry in pcCatCache where pcCacheEntry.InstanceName == instanceName select pcCacheEntry).FirstOrDefault(); if (pc == null) { pc = new System.Diagnostics.PerformanceCounter("APP_POOL_WAS", "Current Application Pool State", instanceName, hostName); pcCatCache.Add(pc); } float value = pc.NextValue(); IISAppPoolStateInfo appPool = new IISAppPoolStateInfo() { DisplayName = instanceName }; appPool.Status = ReadAppPoolStateFromPCValue(value); appPools.Add(appPool); } } } else { using (WebAdmin.ServerManager serverManager = WebAdmin.ServerManager.OpenRemote(hostName)) { foreach (var pool in serverManager.ApplicationPools) { IISAppPoolStateInfo appPool = new IISAppPoolStateInfo() { DisplayName = pool.Name }; appPool.Status = (AppPoolStatus)pool.State; appPools.Add(appPool); } } } } //catch (UnauthorizedAccessException unauthEx) //{ // appPools = new List<IISAppPoolStateInfo>(); // //Try performance counters // System.Diagnostics.PerformanceCounterCategory pcCat = new System.Diagnostics.PerformanceCounterCategory("APP_POOL_WAS", hostName); // //getting instance names // string[] instances = pcCat.GetInstanceNames(); // foreach (string instanceName in instances) // { // System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("APP_POOL_WAS", "Current Application Pool State", instanceName, hostName); // float value = pc.NextValue(); // IISAppPoolStateInfo appPool = new IISAppPoolStateInfo() { DisplayName = instanceName }; // appPool.Status = ReadAppPoolStateFromPCValue(value); // appPools.Add(appPool); // } //} catch (Exception ex) { if (ex is UnauthorizedAccessException) { throw new Exception("Using ServiceManager class on local machine requires elevated rights. Please run this collector in a process that runs in 'Admin mode'"); } else if (ex.Message.Contains("80040154")) { throw new Exception(string.Format("ServiceManager class not supported on {0}", hostName)); } else if (ex.Message.Contains("800706ba")) { throw new Exception("Firewall blocking ServiceManager call. Please add OAB exception"); } else { throw; } } return(appPools); }
public Site CreateSite(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 = 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, 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 = CreateSite(iis, applicationName, siteName, webRoot, siteBindings); // 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); // Set initial ScmType state to LocalGit var serviceUrl = String.Format("http://localhost:{0}/", serviceSitePort); var settings = new RemoteDeploymentSettingsManager(serviceUrl + "settings"); settings.SetValue(SettingsKeys.ScmType, ScmType.LocalGit).Wait(); 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 = serviceUrl, SiteUrls = siteUrls }); } catch { DeleteSite(applicationName); throw; } } }
public static DotNetNukeWebAppInfo Load(string iisWebSiteName) { using (var serverManager = new Microsoft.Web.Administration.ServerManager()) { var site = serverManager.Sites.FirstOrDefault(w => w.Name.ToLower() == iisWebSiteName.ToLower()); if (site == null) { throw new ArgumentOutOfRangeException("Could not find IIS website named: " + iisWebSiteName); } var defaultBinding = site.Bindings.FirstOrDefault(); if (defaultBinding == null) { throw new ArgumentOutOfRangeException("The IIS website named: " + iisWebSiteName + " does not appear to have any Bindings. Please set up a binding for it."); } int port = 80; string protocol = "http"; string host = "localhost"; if (defaultBinding.EndPoint != null) { port = defaultBinding.EndPoint.Port; } if (!string.IsNullOrEmpty(defaultBinding.Protocol)) { protocol = defaultBinding.Protocol; } if (!string.IsNullOrEmpty(defaultBinding.Host)) { host = defaultBinding.Host; } DotNetNukeWebAppInfo info = new DotNetNukeWebAppInfo(); info.Name = site.Name; info.Port = port; info.Protocol = protocol; info.Host = host; if (site.Applications == null || site.Applications.Count() == 0) { throw new ArgumentOutOfRangeException("The IIS website named: " + iisWebSiteName + " does not appear to be set up as a web application."); } var siteApp = site.Applications["/"]; if (siteApp == null) { throw new ArgumentOutOfRangeException("The IIS website named: " + iisWebSiteName + " does not appear to be set up as a web application."); } info.AppPoolName = siteApp.ApplicationPoolName; if (siteApp.VirtualDirectories == null || siteApp.VirtualDirectories.Count() == 0) { throw new ArgumentOutOfRangeException("The IIS website named: " + iisWebSiteName + " does not appear to have a virtual directory configured."); } var siteVirtualDir = siteApp.VirtualDirectories["/"]; string websitePhysicalPath = siteVirtualDir.PhysicalPath; info.PhysicalPath = websitePhysicalPath; return(info); } }
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(); }