public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. //var settingAsString = RoleEnvironment.GetConfigurationSettingValue("Full.Setting.Path"); // skip role setup when emulating azure if (!RoleEnvironment.IsEmulated) { #region Machine Key Reconfiguration // http://msdn.microsoft.com/en-us/library/gg494983.aspx _logger = new WebRoleLogger(); _logger.Log("RoleEntryPoint.OnStart() has been invoked."); try { // locate the encrypted web.config file var webConfigPath = GetEncryptedWebConfigFilePath(); var webConfigFileExists = File.Exists(webConfigPath); if (!webConfigFileExists) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate web.config file at '{0}'.", webConfigPath); // get web.config file contents var webConfigContent = File.ReadAllText(webConfigPath); // construct an XML configuration document var webConfigXmlDocument = new ConfigXmlDocument { InnerXml = webConfigContent, }; if (webConfigXmlDocument.DocumentElement == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file."); // find the configProtectedData node var configProtectedDataNode = webConfigXmlDocument.DocumentElement.ChildNodes.Cast<XmlNode>() .SingleOrDefault(x => x.Name == "configProtectedData"); if (configProtectedDataNode == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file."); // find the configProtectedData/provider child node var configProtectionProviderNode = configProtectedDataNode; while (configProtectionProviderNode != null && configProtectionProviderNode.Attributes != null && (configProtectionProviderNode.Attributes["name"] == null || configProtectionProviderNode.Attributes["thumbprint"] == null)) { configProtectionProviderNode = configProtectionProviderNode.ChildNodes.Cast<XmlNode>().FirstOrDefault(); } if (configProtectionProviderNode == null || configProtectionProviderNode.Attributes == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData/provider child node in web.config file."); // get the configProtectedData/provider node attributes (name & thumbprint) var configProtectionProviderName = configProtectionProviderNode.Attributes["name"].Value; var configProtectionProviderThumbprint = configProtectionProviderNode.Attributes["thumbprint"].Value; // construct & initialize a ProtectedConfigurationProvider var configProtectionProviderAssembly = Assembly.Load("Pkcs12ProtectedConfigurationProvider"); var configProtectionProviderType = configProtectionProviderAssembly.GetTypes() .First(t => typeof(ProtectedConfigurationProvider).IsAssignableFrom(t)); var protectedConfigurationProvider = Activator.CreateInstance(configProtectionProviderType) as ProtectedConfigurationProvider; if (protectedConfigurationProvider == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to construct a ProtectedConfigurationProvider."); protectedConfigurationProvider.Initialize(configProtectionProviderName, new NameValueCollection { { "thumbprint", configProtectionProviderThumbprint }, }); // get encrypted appSettings XML node var encryptedAppSettingsNode = webConfigXmlDocument.DocumentElement.ChildNodes .Cast<XmlNode>().SingleOrDefault(x => x.Name == "appSettings"); if (encryptedAppSettingsNode == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate encrypted appSettings node."); // decrypt appSettings XML var decryptedAppSettingsNode = protectedConfigurationProvider.Decrypt(encryptedAppSettingsNode).ChildNodes .Cast<XmlNode>().SingleOrDefault(x => x.Name == "appSettings"); if (decryptedAppSettingsNode == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate decrypted appSettings node."); // extract machineConfig values from decrypted appSettings XML var validationKey = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationKey"); var validationAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationAlgorithm"); var decryptionKey = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionKey"); var decryptionAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionAlgorithm"); if (string.IsNullOrWhiteSpace(validationKey) || string.IsNullOrWhiteSpace(validationAlgorithm) || string.IsNullOrWhiteSpace(decryptionKey) || string.IsNullOrWhiteSpace(decryptionAlgorithm)) return FailBecauseMachineConfigCannotBeReconfigured("A machineKey attribute value could not be found in decrypted appSettings."); _logger.Log("Found deployment validation key '{0}'.", validationKey); _logger.Log("Found deployment decryption key '{0}'.", decryptionKey); using (var server = new ServerManager()) { // load IIS site's web configuration var siteName = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id); var site = RoleEnvironment.IsEmulated ? server.Sites.First() : server.Sites[siteName]; if (site == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate site '{0}'.", siteName); var siteWebConfiguration = site.GetWebConfiguration(); if (siteWebConfiguration == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to load web configuration for site '{0}'.", siteName); var machineKeySection = siteWebConfiguration.GetSection("system.web/machineKey"); if (machineKeySection == null) return FailBecauseMachineConfigCannotBeReconfigured("Unable to locate machineConfig section in site '{0}' web configuration.", siteName); // overwrite machineKey values machineKeySection.SetAttributeValue("validationKey", validationKey); machineKeySection.SetAttributeValue("validation", validationAlgorithm); machineKeySection.SetAttributeValue("decryptionKey", decryptionKey); machineKeySection.SetAttributeValue("decryption", decryptionAlgorithm); server.CommitChanges(); _logger.Log("Machine key has been reconfigured."); } } catch (Exception ex) { if (ex.Message == FailBecauseMachineConfigCannotBeReconfiguredMessage) throw; _logger.Log("A(n) {0} exception was encountered while trying to set the machineConfig.", ex.GetType().Name); _logger.Log(ex.Message); _logger.Log(ex.StackTrace); _logger.Log(ex.Source); } _logger.Dispose(); #endregion //#region Diagnostics Trace Logging //var config = DiagnosticMonitor.GetDefaultInitialConfiguration(); //// Change the polling interval for all logs. //config.ConfigurationChangePollInterval = TimeSpan.FromSeconds(30.0); //// Set the transfer interval for all logs. //config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0); //// Add performance counter monitoring for configured counters //var counters = new List<string> //{ // @"\Processor(_Total)\% Processor Time", // @"\Memory\Available Mbytes", // @"\TCPv4\Connections Established", // @"\ASP.NET Applications(__Total__)\Requests/Sec", // @"\Network Interface(*)\Bytes Received/sec", // @"\Network Interface(*)\Bytes Sent/sec" //}; //foreach (var counterConfig in counters.Select(counter => // new PerformanceCounterConfiguration // { // CounterSpecifier = counter, // SampleRate = TimeSpan.FromMinutes(1) // }) //) //{ // config.PerformanceCounters.DataSources.Add(counterConfig); //} //config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); ////Diagnostics Infrastructure logs //config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); //config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;//.error ////Windows Event Logs //config.WindowsEventLog.DataSources.Add("System!*"); //config.WindowsEventLog.DataSources.Add("Application!*"); //config.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); //config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning; ////Azure Trace Logs //config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); //config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose; ////Crash Dumps //CrashDumps.EnableCollection(true); ////IIS Logs //config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); //// start the diagnostics monitor //DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config); //#endregion #region IIS Domain Binding // NOTE: This is here to prevent random errors where requests for another domain's resource // are accidentally routed to this deployment server. It's weird, but it happened before this code! // By default, the website name is "[ Current Role Instance id]_Web" var siteName1 = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id); // In future, if you need add more endpoint(HTTP or HTTPS), // please create new bindingEntry and append to the cmd string, // separate with ','. For how to use AppCmd to config IIS site, // please refer to this article // http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe // NOTE: the above is accomplished in the GetAppCmdBindings method in this class var command = string.Format("set site \"{0}\" /bindings:{1}", siteName1, GetAppCmdBindings()); const string appCmdPath = @"d:\Windows\System32\inetsrv\appcmd.exe"; try { Process.Start(new ProcessStartInfo(appCmdPath, command)); Trace.TraceInformation("Initialize IIS binding succeed."); } catch (Exception ex) { Trace.TraceError(ex.Message); throw; } #endregion } var baseOnStart = base.OnStart(); return baseOnStart; }
public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. //var settingAsString = RoleEnvironment.GetConfigurationSettingValue("Full.Setting.Path"); if (!RoleEnvironment.IsEmulated) { #region Machine Key Reconfiguration // http://msdn.microsoft.com/en-us/library/gg494983.aspx _logger = new WebRoleLogger(); _logger.Log("RoleEntryPoint.OnStart() has been invoked."); try { // locate the encrypted web.config file var webConfigPath = GetEncryptedWebConfigFilePath(); var webConfigFileExists = File.Exists(webConfigPath); if (!webConfigFileExists) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate web.config file at '{0}'.", webConfigPath)); } // get web.config file contents var webConfigContent = File.ReadAllText(webConfigPath); // construct an XML configuration document var webConfigXmlDocument = new ConfigXmlDocument { InnerXml = webConfigContent, }; if (webConfigXmlDocument.DocumentElement == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file.")); } // find the configProtectedData node var configProtectedDataNode = webConfigXmlDocument.DocumentElement.ChildNodes.Cast <XmlNode>() .SingleOrDefault(x => x.Name == "configProtectedData"); if (configProtectedDataNode == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file.")); } // find the configProtectedData/provider child node var configProtectionProviderNode = configProtectedDataNode; while (configProtectionProviderNode != null && configProtectionProviderNode.Attributes != null && (configProtectionProviderNode.Attributes["name"] == null || configProtectionProviderNode.Attributes["thumbprint"] == null)) { configProtectionProviderNode = configProtectionProviderNode.ChildNodes.Cast <XmlNode>().FirstOrDefault(); } if (configProtectionProviderNode == null || configProtectionProviderNode.Attributes == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData/provider child node in web.config file.")); } // get the configProtectedData/provider node attributes (name & thumbprint) var configProtectionProviderName = configProtectionProviderNode.Attributes["name"].Value; var configProtectionProviderThumbprint = configProtectionProviderNode.Attributes["thumbprint"].Value; // construct & initialize a ProtectedConfigurationProvider var configProtectionProviderAssembly = Assembly.Load("Pkcs12ProtectedConfigurationProvider"); var configProtectionProviderType = configProtectionProviderAssembly.GetTypes() .First(t => typeof(ProtectedConfigurationProvider).IsAssignableFrom(t)); var protectedConfigurationProvider = Activator.CreateInstance(configProtectionProviderType) as ProtectedConfigurationProvider; if (protectedConfigurationProvider == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to construct a ProtectedConfigurationProvider.")); } protectedConfigurationProvider.Initialize(configProtectionProviderName, new NameValueCollection { { "thumbprint", configProtectionProviderThumbprint }, }); // get encrypted appSettings XML node var encryptedAppSettingsNode = webConfigXmlDocument.DocumentElement.ChildNodes .Cast <XmlNode>().SingleOrDefault(x => x.Name == "appSettings"); if (encryptedAppSettingsNode == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate encrypted appSettings node.")); } // decrypt appSettings XML var decryptedAppSettingsNode = protectedConfigurationProvider.Decrypt(encryptedAppSettingsNode).ChildNodes .Cast <XmlNode>().SingleOrDefault(x => x.Name == "appSettings"); if (decryptedAppSettingsNode == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate decrypted appSettings node.")); } // extract machineConfig values from decrypted appSettings XML var validationKey = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationKey"); var validationAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationAlgorithm"); var decryptionKey = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionKey"); var decryptionAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionAlgorithm"); if (string.IsNullOrWhiteSpace(validationKey) || string.IsNullOrWhiteSpace(validationAlgorithm) || string.IsNullOrWhiteSpace(decryptionKey) || string.IsNullOrWhiteSpace(decryptionAlgorithm)) { return(FailBecauseMachineConfigCannotBeReconfigured("A machineKey attribute value could not be found in decrypted appSettings.")); } using (var server = new ServerManager()) { // load IIS site's web configuration var siteName = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id); var site = RoleEnvironment.IsEmulated ? server.Sites.First() : server.Sites[siteName]; if (site == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate site '{0}'.", siteName)); } var siteWebConfiguration = site.GetWebConfiguration(); if (siteWebConfiguration == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to load web configuration for site '{0}'.", siteName)); } var machineKeySection = siteWebConfiguration.GetSection("system.web/machineKey"); if (machineKeySection == null) { return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate machineConfig section in site '{0}' web configuration.", siteName)); } // overwrite machineKey values machineKeySection.SetAttributeValue("validationKey", validationKey); machineKeySection.SetAttributeValue("validation", validationAlgorithm); machineKeySection.SetAttributeValue("decryptionKey", decryptionKey); machineKeySection.SetAttributeValue("decryption", decryptionAlgorithm); server.CommitChanges(); } } catch (Exception ex) { if (ex.Message == FailBecauseMachineConfigCannotBeReconfiguredMessage) { throw; } _logger.Log("A(n) {0} exception was encountered while trying to set the machineConfig.", ex.GetType().Name); _logger.Log(ex.Message); _logger.Log(ex.StackTrace); _logger.Log(ex.Source); } _logger.Dispose(); #endregion #region Diagnostics Trace Logging var config = DiagnosticMonitor.GetDefaultInitialConfiguration(); // Change the polling interval for all logs. config.ConfigurationChangePollInterval = TimeSpan.FromSeconds(30.0); // Set the transfer interval for all logs. config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0); // Add performance counter monitoring for configured counters var counters = new List <string> { @"\Processor(_Total)\% Processor Time", @"\Memory\Available Mbytes", @"\TCPv4\Connections Established", @"\ASP.NET Applications(__Total__)\Requests/Sec", @"\Network Interface(*)\Bytes Received/sec", @"\Network Interface(*)\Bytes Sent/sec" }; foreach (var counterConfig in counters.Select(counter => new PerformanceCounterConfiguration { CounterSpecifier = counter, SampleRate = TimeSpan.FromMinutes(1) }) ) { config.PerformanceCounters.DataSources.Add(counterConfig); } config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); //Diagnostics Infrastructure logs config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;//.error //Windows Event Logs config.WindowsEventLog.DataSources.Add("System!*"); config.WindowsEventLog.DataSources.Add("Application!*"); config.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning; //Azure Trace Logs config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose; //Crash Dumps CrashDumps.EnableCollection(true); //IIS Logs config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); // start the diagnostics monitor DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config); #endregion #region IIS Domain Binding // By default, the website name is "[ Current Role Instance id]_Web" var siteName1 = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id); // In future, if you need add more endpoint(HTTP or HTTPS), // please create new bindingEntry and append to the cmd string, // separate with ','. For how to use AppCmd to config IIS site, // please refer to this article // http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe var command = string.Format("set site \"{0}\" /bindings:{1}", siteName1, GetAppCmdBindings()); const string appCmdPath = @"d:\Windows\System32\inetsrv\appcmd.exe"; try { Process.Start(new ProcessStartInfo(appCmdPath, command)); Trace.TraceInformation("Initialize IIS binding succeed."); } catch (Exception ex) { Trace.TraceError(ex.Message); throw; } #endregion } var baseOnStart = base.OnStart(); return(baseOnStart); }