Ejemplo n.º 1
0
        /// <summary>Windows Azure診断(Windows Azure Diagnostics)関連の設定</summary>
        private void ConfigureDiagnostics()
        {
            // Windows Azure診断(Windows Azure Diagnostics)情報出力用のストレージ アカウント取得
            string wadConnectionString = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";

            //// ストレージ アカウントの初期化
            //CloudStorageAccount cloudStorageAccount =
            //  CloudStorageAccount.Parse(
            //    RoleEnvironment.GetConfigurationSettingValue(wadConnectionString));

            //// RoleInstance診断管理の初期化(ロールに対する診断の有効化)
            //RoleInstanceDiagnosticManager roleInstanceDiagnosticManager =
            //  cloudStorageAccount.CreateRoleInstanceDiagnosticManager(
            //    RoleEnvironment.DeploymentId,
            //    RoleEnvironment.CurrentRoleInstance.Role.Name,
            //    RoleEnvironment.CurrentRoleInstance.Id);
            var storageConnectionString = RoleEnvironment.GetConfigurationSettingValue(
                wadConnectionString);
            var deploymentDiagnosticManager = new DeploymentDiagnosticManager(
                storageConnectionString,
                RoleEnvironment.DeploymentId);
            RoleInstanceDiagnosticManager roleInstanceDiagnosticManager = deploymentDiagnosticManager.GetRoleInstanceDiagnosticManager(
                RoleEnvironment.CurrentRoleInstance.Role.Name,
                RoleEnvironment.CurrentRoleInstance.Id);

            // RoleInstance診断管理からコンフィグを取得する。
            // ・基本的にはデフォルト設定を利用する。
            // ・RoleEnvironment.Changedイベント ハンドラを仕掛ける場合はカレント設定を利用する。
            DiagnosticMonitorConfiguration config =
                DiagnosticMonitor.GetDefaultInitialConfiguration();

            // roleInstanceDiagnosticManager.GetCurrentConfiguration();

            #region Windows Azure診断(Windows Azure Diagnostics)APIを使用した設定開始

            #region インフラストラクチャ ログ(診断モニタ自体のログ)
            // 転送レベルおよび転送間隔を設定
            config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;       // 要検討
            config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = TimeSpan.FromSeconds(15); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADDiagnosticInfrastructureLogsTable

            #region イベント ログの設定
            // 取得するイベント ソースを設定
            config.WindowsEventLog.DataSources.Add("Application!*");
            config.WindowsEventLog.DataSources.Add("System!*");
            // 転送レベルおよび転送間隔を設定
            config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Undefined;       // 要検討
            config.WindowsEventLog.ScheduledTransferPeriod         = TimeSpan.FromMinutes(15); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADWindowsEventLogsTable

            #region パフォーマンス カウンタの転送設定
            // カウンタ、サンプリング レートの指定
            config.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                SampleRate       = TimeSpan.FromSeconds(10)
            });
            config.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Memory\Available Bytes",
                SampleRate       = TimeSpan.FromSeconds(10)
            });
            // 転送間隔を設定
            config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(15); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADPerformanceCountersTable

            #region クラッシュ ダンプ転送の有効化
            CrashDumps.EnableCollection(true);
            #endregion
            // 出力先のBlobストレージ コンテナ名:wad-crash-dumps

            #region IISログ、FREBログの転送設定(※ web.config への設定も必要)
            // IISログはデフォルトで取得が有効となっているため、Blobへの転送を指定するのみで収集が可能となる。
            // FREB(Failed Request Trace log)ログについてはweb.config への設定も必要
            #endregion
            // 出力先のBlobストレージ コンテナ名:wad-iis-logfiles、wad-iis-failedreqlogfiles

            #region トレース ログの設定(※ *.config への設定も必要)
            // 転送レベルおよび転送間隔を設定
            config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;      // 要検討
            config.Logs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADLogsTable

            #region カスタム ログ(ローカル ストレージへの出力の場合)

            // 出力先ディレクトリ設定
            DirectoryConfiguration dirConfig1 = new DirectoryConfiguration()
            {
                // 出力先Blobコンテナの指定
                Container = "my-custom-logfiles1",
                // クォーターの設定(実際に使う量)
                DirectoryQuotaInMB = 100,
            };

            // ローカル ストレージのパスを指定
            //(ローカル ストレージの設定自体は、Visual Studioを使用し*.csdefに設定可能)
            LocalResource ls = RoleEnvironment.GetLocalResource("LogStorage");
            dirConfig1.Path = ls.RootPath;

            // log4netに環境変数経由でパス情報(RootPath)を
            // 渡そうとしたがエミュレータ上でうまく動作せず断念。

            // ローカル ストレージを転送元コレクションに追加
            config.Directories.DataSources.Add(dirConfig1);
            // なお、ローカル ストレージのパスは、LocalResource.RootPathにて取得が可能である。

            #endregion
            // 出力先のBlobストレージ コンテナ名:my-custom-logfiles1

            #region カスタムログ(任意の出力先の場合)

            // 出力先ディレクトリ設定
            DirectoryConfiguration dirConfig2 = new DirectoryConfiguration()
            {
                // 出力先Blobコンテナの指定
                Container = "my-custom-logfiles2",
                // クォーターの設定(実際に使う量)
                DirectoryQuotaInMB = 100,
            };

            // 任意のディレクトリを指定
            string path = "c:\\logs";
            dirConfig2.Path = path;
            // ディレクトリを転送元コレクションに追加
            config.Directories.DataSources.Add(dirConfig2);

            // ディレクトリ セキュリティを取得
            DirectorySecurity ds = Directory.GetAccessControl(path);

            // Everyone FullControlのアクセス ルールの生成
            FileSystemAccessRule AccessRule = new FileSystemAccessRule(
                "Everyone",
                FileSystemRights.FullControl,
                InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            // ディレクトリ キュリティにアクセス ルールを追加
            ds.AddAccessRule(AccessRule);

            // ディレクトリにディレクトリ セキュリティを反映
            // ★ <Runtime executionContext="elevated"/>を「*.csdef」に記述。
            Directory.SetAccessControl(path, ds);

            #endregion
            // 出力先のBlobストレージ コンテナ名:my-custom-logfiles2

            // IISログ、カスタム ログ、クラッシュ ダンプなどで
            // 使用するディレクトリ バッファからBlobストレージへの転送間隔の指定
            config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(15);

            #endregion

            // RoleInstance診断管理にコンフィグを設定
            roleInstanceDiagnosticManager.SetCurrentConfiguration(config);

            // 診断の開始(エミュレータでは不要だが、実機では必要
            DiagnosticMonitor.Start(wadConnectionString, config);

            // ローカル ストレージへのログ出力テスト
            path = Path.Combine(ls.RootPath,
                                string.Format("test_{0}.txt", DateTime.Now.ToString("yyyyMMdd")));

            // StreamWriterを開き、ログを出力
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine("{0} : {1}", DateTime.UtcNow, "ローカル ストレージへのログ出力テスト");
                sw.Close();
            }
        }
Ejemplo n.º 2
0
        public override bool OnStart()
        {
            DiagnosticMonitorConfiguration diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

            var perfCounters = 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"
            };

            // Add perf counters to configuration
            foreach (var counter in perfCounters)
            {
                var counterConfig = new PerformanceCounterConfiguration
                {
                    CounterSpecifier = counter,
                    SampleRate       = TimeSpan.FromSeconds(1.0)
                };

                diagConfig.PerformanceCounters.DataSources.Add(counterConfig);
            }

            diagConfig.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromSeconds(20.0);

            //Windows Event Logs
            diagConfig.WindowsEventLog.DataSources.Add("System!*");
            diagConfig.WindowsEventLog.DataSources.Add("Application!*");
            diagConfig.WindowsEventLog.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1.0);
            diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning;

            //Azure Trace Logs
            diagConfig.Logs.ScheduledTransferPeriod         = TimeSpan.FromSeconds(20.0);
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Warning;
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
            //  diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Error;
            //Crash Dumps
            CrashDumps.EnableCollection(true);

            //IIS Logs
            diagConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

            DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagConfig);

            Trace.TraceInformation(RoleEnvironment.Roles.Count.ToString());
            Trace.TraceInformation("Instance {0} started.", RoleEnvironment.CurrentRoleInstance.Id);

            RoleEnvironment.Changing += new EventHandler <RoleEnvironmentChangingEventArgs>(RoleEnvironment_Changing);

            // CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
            // account.
            //    RoleEnvironment.GetConfigurationSettingValue("CacheServiceRole");

            RoleEnvironment.Changed += new EventHandler <RoleEnvironmentChangedEventArgs>(RoleEnvironment_Changed);


            //if (RoleEnvironment.IsEmulated)
            //{
            //    var traceSource = CreateTraceSource();
            //    traceSource.TraceInformation("Instance {0} started.", RoleEnvironment.CurrentRoleInstance.Id);
            //}
            return(base.OnStart());
            //// To enable the AzureLocalStorageTraceListner, uncomment relevent section in the web.config
            //DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
            //diagnosticConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
            //diagnosticConfig.Directories.DataSources.Add(AzureLocalStorageTraceListener.GetLogDirectory());

            //// For information on handling configuration changes
            //// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            //return base.OnStart();
        }
Ejemplo n.º 3
0
        private void SetupDiagnostics()
        {
            Trace.WriteLine("Setting up diagnostics", "Information");

            DiagnosticMonitorConfiguration diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

            string logLevel = RoleEnvironment.GetConfigurationSettingValue("LogLevel");


            if (logLevel == "debug")
            {
                diagConfig.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
                diagConfig.Logs.ScheduledTransferLogLevelFilter            = LogLevel.Verbose;
                diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
            }

            else if (logLevel == "info")
            {
                diagConfig.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Information;
                diagConfig.Logs.ScheduledTransferLogLevelFilter            = LogLevel.Information;
                diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Information;
            }
            else if (logLevel == "error")
            {
                diagConfig.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Error;
                diagConfig.Logs.ScheduledTransferLogLevelFilter            = LogLevel.Error;
                diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Error;
            }

            // Add performance counter monitoring for configured counters
            // Run typeperf.exe /q to query the counter list
            string perfCounterString = RoleEnvironment.GetConfigurationSettingValue("PerformanceCounters");

            if (!string.IsNullOrEmpty(perfCounterString))
            {
                IList <string> perfCounters = perfCounterString.Split(',').ToList();

                // Setup each counter specified in comma delimitered string
                foreach (string perfCounter in perfCounters)
                {
                    diagConfig.PerformanceCounters.DataSources.Add(
                        new PerformanceCounterConfiguration
                    {
                        CounterSpecifier = perfCounter,
                        SampleRate       = TimeSpan.FromSeconds(DefaultSampleRate)
                    }
                        );
                }

                // Update counter information in Azure every 30 seconds
                diagConfig.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(0.5);
            }

            diagConfig.ConfigurationChangePollInterval = TimeSpan.FromMinutes(5);
            diagConfig.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(0.5);
            // Set scheduled transfer interval for user's Windows Azure Logs to 1 minute
            diagConfig.Logs.ScheduledTransferPeriod        = TimeSpan.FromMinutes(1);
            diagConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);

            Microsoft.WindowsAzure.Diagnostics.CrashDumps.EnableCollection(true);


            //Event Logs
            // Add event collection from the Windows Event Log
            diagConfig.WindowsEventLog.DataSources.Add("System!*");
            diagConfig.WindowsEventLog.DataSources.Add("Application!*");
            diagConfig.WindowsEventLog.DataSources.Add("Security!*");


            // Start the diagnostic monitor with this custom configuration
            DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagConfig);
        }
Ejemplo n.º 4
0
        public override bool OnStart()
        {
            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            TimeSpan transferPeriod;

            if (!TimeSpan.TryParse(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.ScheduledTransferPeriod"), out transferPeriod))
            {
                transferPeriod = TimeSpan.FromMinutes(1);
            }

            TimeSpan sampleRate;

            if (!TimeSpan.TryParse(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.PerformanceCounterSampleRate"), out sampleRate))
            {
                sampleRate = TimeSpan.FromSeconds(30);
            }

            LogLevel logLevel;

            if (!Enum.TryParse <LogLevel>(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.LogLevelFilter"), out logLevel))
            {
                logLevel = LogLevel.Verbose;
            }

            // Setup performance counters
            //config.PerformanceCounters.DataSources.Add(
            //    new PerformanceCounterConfiguration
            //    {
            //        CounterSpecifier = @"\Processor(_Total)\% Processor Time",
            //        SampleRate = sampleRate
            //    });
            //config.PerformanceCounters.ScheduledTransferPeriod = transferPeriod;
#if !LOCAL
            foreach (var counterName in
                     new[]
            {
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.CurrentEventPublishersCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.EventPublishingRequestsPerSecondCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.EventsPublishedPerSecondCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.TotalEventsPublishedCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.TotalEventsPublishingRequestsCounterName,
            })
            {
                //config.PerformanceCounters.DataSources.Add(
                //    new PerformanceCounterConfiguration
                //    {
                //        CounterSpecifier = @"\" + Infrastructure.Azure.Instrumentation.Constants.EventPublishersPerformanceCountersCategory + @"(*)\" + counterName,
                //        SampleRate = sampleRate
                //    });
            }
#endif

            // Setup logs
            //config.Logs.ScheduledTransferPeriod = transferPeriod;
            //config.Logs.ScheduledTransferLogLevelFilter = logLevel;

            //DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config);

            return(base.OnStart());
        }
Ejemplo n.º 5
0
        public override bool OnStart()
        {
            RoleEnvironment.Changing += (sender, e) =>
            {
                if (e.Changes
                    .OfType <RoleEnvironmentConfigurationSettingChange>()
                    .Any(x => x.ConfigurationSettingName != MaintenanceMode.MaintenanceModeSettingName))
                {
                    Trace.TraceInformation("Recycling worker role because of configuration change");
                    e.Cancel = true;
                }
            };
            RoleEnvironment.Changed += (sender, e) =>
            {
                if (e.Changes
                    .OfType <RoleEnvironmentConfigurationSettingChange>()
                    .Any(x => x.ConfigurationSettingName == MaintenanceMode.MaintenanceModeSettingName))
                {
                    Trace.TraceInformation("Refreshing maintenance mode because of configuration change");
                    MaintenanceMode.RefreshIsInMaintainanceMode();
                }
            };
            MaintenanceMode.RefreshIsInMaintainanceMode();

            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            var cloudStorageAccount =
                CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"));

            TimeSpan transferPeriod;

            if (!TimeSpan.TryParse(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.ScheduledTransferPeriod"), out transferPeriod))
            {
                transferPeriod = TimeSpan.FromMinutes(1);
            }

            TimeSpan sampleRate;

            if (!TimeSpan.TryParse(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.PerformanceCounterSampleRate"), out sampleRate))
            {
                sampleRate = TimeSpan.FromSeconds(30);
            }

            LogLevel logLevel;

            if (!Enum.TryParse <LogLevel>(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.LogLevelFilter"), out logLevel))
            {
                logLevel = LogLevel.Verbose;
            }

            // Setup performance counters
            config.PerformanceCounters.DataSources.Add(
                new PerformanceCounterConfiguration
            {
                CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                SampleRate       = sampleRate
            });

#if !LOCAL
            foreach (var counterName in
                     new[]
            {
                Infrastructure.Azure.Instrumentation.SessionSubscriptionReceiverInstrumentation.TotalSessionsCounterName,
                Infrastructure.Azure.Instrumentation.SessionSubscriptionReceiverInstrumentation.CurrentSessionsCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.TotalMessagesCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.TotalMessagesSuccessfullyProcessedCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.TotalMessagesUnsuccessfullyProcessedCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.TotalMessagesCompletedCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.TotalMessagesNotCompletedCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.MessagesReceivedPerSecondCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.AverageMessageProcessingTimeCounterName,
                Infrastructure.Azure.Instrumentation.SubscriptionReceiverInstrumentation.CurrentMessagesInProcessCounterName,
            })
            {
                config.PerformanceCounters.DataSources.Add(
                    new PerformanceCounterConfiguration
                {
                    CounterSpecifier = @"\" + Infrastructure.Azure.Instrumentation.Constants.ReceiversPerformanceCountersCategory + @"(*)\" + counterName,
                    SampleRate       = sampleRate
                });
            }

            foreach (var counterName in
                     new[]
            {
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.CurrentEventPublishersCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.EventPublishingRequestsPerSecondCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.EventsPublishedPerSecondCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.TotalEventsPublishedCounterName,
                Infrastructure.Azure.Instrumentation.EventStoreBusPublisherInstrumentation.TotalEventsPublishingRequestsCounterName,
            })
            {
                config.PerformanceCounters.DataSources.Add(
                    new PerformanceCounterConfiguration
                {
                    CounterSpecifier = @"\" + Infrastructure.Azure.Instrumentation.Constants.EventPublishersPerformanceCountersCategory + @"(*)\" + counterName,
                    SampleRate       = sampleRate
                });
            }
#endif

            config.PerformanceCounters.ScheduledTransferPeriod = transferPeriod;

            // Setup logs
            config.Logs.ScheduledTransferPeriod         = transferPeriod;
            config.Logs.ScheduledTransferLogLevelFilter = logLevel;

            DiagnosticMonitor.Start(cloudStorageAccount, config);

            Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
            Trace.AutoFlush = true;

            Database.DefaultConnectionFactory = new ServiceConfigurationSettingConnectionFactory(Database.DefaultConnectionFactory);

            return(base.OnStart());
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            string configXmlDir = Environment.CurrentDirectory;

            if (args.Length == 1)
            {
                configXmlDir = args[0];
            }
            string configXmlPath = Path.Combine(configXmlDir, "DiagnosticsConfiguration.xml");

            if (!File.Exists(configXmlPath))
            {
                throw new InvalidOperationException(string.Format("Unable to find diagnostics configuration xml @ {0}", configXmlPath));
            }

            XmlSerializer     serializer = new XmlSerializer(typeof(DiagnosticsConfig));
            DiagnosticsConfig diagConfig = null;

            using (Stream fs = File.OpenRead(configXmlPath))
            {
                diagConfig = serializer.Deserialize(fs) as DiagnosticsConfig;
            }

            DiagnosticMonitorConfiguration config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            config.OverallQuotaInMB = diagConfig.OverallQuotaInMB;

            if (diagConfig.Directories.Directory != null)
            {
                foreach (DiagnosticsConfigDirectoriesDirectory dir in diagConfig.Directories.Directory)
                {
                    DirectoryConfiguration directoryConfig = new DirectoryConfiguration();
                    directoryConfig.Container = dir.ContainerName;
                    if (dir.IsLocalPathRelative)
                    {
                        directoryConfig.Path = Path.Combine(Environment.CurrentDirectory, dir.LocalPath);
                    }
                    else
                    {
                        directoryConfig.Path = dir.LocalPath;
                    }
                    directoryConfig.DirectoryQuotaInMB = dir.DirectoryQuotaInMB;
                    config.Directories.DataSources.Add(directoryConfig);
                }
                config.Directories.ScheduledTransferPeriod = TimeSpan.FromSeconds(diagConfig.Directories.ScheduledTransferPeriodInSeconds);
            }

            if (diagConfig.PerformanceCounters.PerformanceCounter != null)
            {
                foreach (DiagnosticsConfigPerformanceCountersPerformanceCounter perf in diagConfig.PerformanceCounters.PerformanceCounter)
                {
                    PerformanceCounterConfiguration perfConfig = new PerformanceCounterConfiguration();
                    perfConfig.CounterSpecifier = perf.CounterName;
                    perfConfig.SampleRate       = TimeSpan.FromSeconds(perf.SamplingRateInSeconds);
                    config.PerformanceCounters.DataSources.Add(perfConfig);
                }
                config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromSeconds(diagConfig.PerformanceCounters.ScheduledTransferPeriodInSeconds);
            }

            DiagnosticMonitor.Start(CloudStorageAccount.Parse(diagConfig.StorageAccountConnectionString), config);

            Trace.WriteLine("ConfigureAzureDiagnostics Started.", "Information");

            Console.ReadLine();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Notifies this extension component that it has been registered in the owner's collection of extensions.
        /// </summary>
        /// <param name="owner">The extensible owner object that aggregates this extension.</param>
        public void Attach(IExtensibleCloudServiceComponent owner)
        {
            IRoleConfigurationSettingsExtension roleConfigExtension = owner.Extensions.Find <IRoleConfigurationSettingsExtension>();

            if (roleConfigExtension != null && CloudEnvironment.IsAvailable)
            {
                ApplicationDiagnosticSettings       diagnosticSettings = roleConfigExtension.GetSection <ApplicationDiagnosticSettings>(ApplicationDiagnosticSettings.SectionName);
                StorageAccountConfigurationSettings storageSettings    = roleConfigExtension.GetSection <StorageAccountConfigurationSettings>(StorageAccountConfigurationSettings.SectionName);

                if (diagnosticSettings != null)
                {
                    if (diagnosticSettings.DiagnosticEnabled)
                    {
                        DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

                        // Configure the scheduled transfer period for all logs.
                        diagnosticConfig.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = diagnosticSettings.DiagnosticLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.Directories.ScheduledTransferPeriod         = diagnosticSettings.FileLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.Logs.ScheduledTransferPeriod                = diagnosticSettings.TraceLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.PerformanceCounters.ScheduledTransferPeriod = diagnosticSettings.PerformanceCountersTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.WindowsEventLog.ScheduledTransferPeriod     = diagnosticSettings.EventLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);

                        // Configure the logs levels for scheduled transfers.
                        diagnosticConfig.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = FromTraceSourceLevel(diagnosticSettings.DiagnosticLogsTransferFilter);
                        diagnosticConfig.Logs.ScheduledTransferLogLevelFilter            = FromTraceSourceLevel(diagnosticSettings.TraceLogsTransferFilter);
                        diagnosticConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = FromTraceSourceLevel(diagnosticSettings.EventLogsTransferFilter);

                        // Configure the Windows Event Log data sources.
                        foreach (string logName in diagnosticSettings.EventLogDataSources.AllKeys)
                        {
                            diagnosticConfig.WindowsEventLog.DataSources.Add(logName);
                        }

                        // Configure the data sources for file-based logs.
                        foreach (string containerName in diagnosticSettings.FileLogDirectories.AllKeys)
                        {
                            diagnosticConfig.Directories.DataSources.Add(new DirectoryConfiguration()
                            {
                                Container = containerName, Path = diagnosticSettings.FileLogDirectories[containerName].Value
                            });
                        }

                        // Configure the data sources for performance counter data
                        foreach (string counterName in diagnosticSettings.PerformanceCountersDataSources.AllKeys)
                        {
                            diagnosticConfig.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
                            {
                                CounterSpecifier = counterName, SampleRate = TimeSpan.Parse(diagnosticSettings.PerformanceCountersDataSources[counterName].Value)
                            });
                        }

                        // Configure crash dumps collection.
                        if (diagnosticSettings.CrashDumpCollectionEnabled)
                        {
                            CrashDumps.EnableCollection(true);
                        }

                        // Look up for the storage account definition.
                        StorageAccountInfo storageAccountInfo = storageSettings.Accounts.Get(diagnosticSettings.DiagnosticStorageAccount);

                        if (storageAccountInfo != null)
                        {
                            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(storageAccountInfo.AccountName, storageAccountInfo.AccountKey), true);
                            RetryPolicy         retryPolicy    = roleConfigExtension.StorageRetryPolicy;

                            // Start the Azure Diagnostic Monitor using a retryable scope.
                            this.diagnosticMonitor = retryPolicy.ExecuteAction <DiagnosticMonitor>(() => { return(DiagnosticMonitor.Start(storageAccount, diagnosticConfig)); });
                        }
                    }
                    else
                    {
                        // Do not proceed any further since diagnostic is not enabled in the application configuration.
                        return;
                    }
                }
            }

            if (null == this.diagnosticMonitor)
            {
                // Configuration extension is not available by some reasons, let try and see if DiagnosticsConnectionString property is set in the configuration.
                string diagConnectionString = CloudEnvironment.GetConfigurationSettingValue(Resources.DiagnosticsConnectionStringSettingName);

                // If DiagnosticsConnectionString is defined, start a Diagnostic Monitor using the storage account configuration specified in the setting.
                if (!String.IsNullOrEmpty(diagConnectionString))
                {
                    this.diagnosticMonitor = DiagnosticMonitor.Start(diagConnectionString, GetDiagnosticMonitorDefaultConfiguration());
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This is where we get the role instance configured and ready to begin processing
        /// STAHC jobs
        /// </summary>
        /// <returns>True if succesfully configured. False otherwise</returns>
        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 64;

            DiagnosticMonitorConfiguration config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            config.PerformanceCounters.DataSources.Add(
                new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                SampleRate       = TimeSpan.FromSeconds(30)
            });

            config.PerformanceCounters.DataSources.Add(
                new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Network Interface(*)\Bytes Total/sec",
                SampleRate       = TimeSpan.FromSeconds(30)
            });

            config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = System.TimeSpan.FromMinutes(5);
            config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Error;
            config.Logs.ScheduledTransferPeriod                = System.TimeSpan.FromMinutes(5);
            config.Logs.ScheduledTransferLogLevelFilter        = LogLevel.Verbose;
            config.PerformanceCounters.ScheduledTransferPeriod = System.TimeSpan.FromMinutes(1);
            config.WindowsEventLog.ScheduledTransferPeriod     = System.TimeSpan.FromMinutes(5);

            DiagnosticMonitor.Start("DiagnosticsConnectionString", config);

            // restart the role upon all configuration changes
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            // read storage account configuration settings
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

            // get the scratch path
            scratchPath = RoleEnvironment.GetLocalResource(Constants.AzureScratchName).RootPath;

            // get the time to sleep between runs of the queue monitoring loop
            queueSleepTime = int.Parse(
                RoleEnvironment.GetConfigurationSettingValue("QueueSleepTime"),
                CultureInfo.InvariantCulture);

            // get the max time (seconds) that the server should take to process a queue job
            maxJobLength = int.Parse(
                RoleEnvironment.GetConfigurationSettingValue("MaxJobLength"),
                CultureInfo.InvariantCulture);

            // get the storage container to be used for processing job data
            jobContainer = RoleEnvironment.GetConfigurationSettingValue("JobContainer");

            // get queue data/configuration
            storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            // get the name of the queue used for this job set
            var queueName = RoleEnvironment.GetConfigurationSettingValue("StachQueueName");

            // get the queues
            CloudQueueClient queueStorage = storageAccount.CreateCloudQueueClient();

            queueStorage.RetryPolicy = RetryPolicies.RetryExponential(3, TimeSpan.FromSeconds(10));

            stahcJobQueue = queueStorage.GetQueueReference(queueName);
            stahcJobQueue.CreateIfNotExist();

            // report on read values
            Trace.WriteLine(string.Format("QueueSleepTime: '{0}'",
                                          queueSleepTime.ToString(CultureInfo.InvariantCulture)), "Verbose");
            Trace.WriteLine(string.Format("MaxJobLength: '{0}'",
                                          maxJobLength.ToString(CultureInfo.InvariantCulture)), "Verbose");
            Trace.WriteLine(string.Format("JobContainer: '{0}'", jobContainer), "Verbose");
            Trace.WriteLine(string.Format("StachQueueName: '{0}'", queueName), "Verbose");

            // read-in/download all source files
            DownloadStagingFiles();

            // loop through and execute each of the actions (if any) provided in the staging file
            var stagingControlFile = Path.Combine(
                scratchPath,
                Constants.StagingActionsFileName);

            if (File.Exists(stagingControlFile))
            {
                var sucessful = RunStagingActions(stagingControlFile);

                if (!sucessful)
                {
                    Trace.TraceError(
                        "Unable to complete staging actions. Review logs for more detail.");
                    return(sucessful);
                }
            }

            return(base.OnStart());
        }
Ejemplo n.º 9
0
        //*********************************************************************
        ///
        /// <summary>
        ///
        /// </summary>
        /// <param name="eLog"></param>
        /// <param name="diagnosticsConnectionString"></param>
        ///
        //*********************************************************************

        public static void Init(EventLog eLog, string diagnosticsConnectionString)
        {
            try
            {
                /*
                 * commented out when migrated from Microsoft.WindowsAzure.Diagnostics 2.3 to 2.5
                 */


                // Fetch a copy of the existing config
                var diagConfig =
                    DiagnosticMonitor.GetDefaultInitialConfiguration();

                //***********************************************************
                //*** Event Logs ********************************************
                //***********************************************************

                diagConfig.Logs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(5);
                diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

                //diagConfig.WindowsEventLog.DataSources.Add("System!*");
                diagConfig.WindowsEventLog.DataSources.Add("Application!*");

                //Specify the scheduled transfer
                diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
                diagConfig.WindowsEventLog.ScheduledTransferPeriod         = System.TimeSpan.FromMinutes(1);

                //***********************************************************
                //*** Perf Counters *****************************************
                //***********************************************************

                diagConfig.PerformanceCounters.DataSources.Add(
                    new PerformanceCounterConfiguration()
                {
                    CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                    SampleRate       = TimeSpan.FromSeconds(60)
                });

                diagConfig.PerformanceCounters.DataSources.Add(
                    new PerformanceCounterConfiguration()
                {
                    CounterSpecifier = @"\Memory\Available Bytes",
                    SampleRate       = TimeSpan.FromSeconds(60)
                });

                diagConfig.PerformanceCounters.DataSources.Add(
                    new PerformanceCounterConfiguration()
                {
                    CounterSpecifier = @"\ASP.NET\Applications Running",
                    SampleRate       = TimeSpan.FromSeconds(60)
                });

                diagConfig.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);

                //***********************************************************
                //*** Infrastructure Logs ***********************************
                //***********************************************************

                diagConfig.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
                diagConfig.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(5);

                //***********************************************************
                //*** Trace *************************************************
                //***********************************************************

                var tmpListener = new DiagnosticMonitorTraceListener();
                System.Diagnostics.Trace.Listeners.Add(tmpListener);

                //***********************************************************
                //*** Startup ***********************************************
                //***********************************************************

                // Start diagnostics with this custom local buffering configuration
                DiagnosticMonitor.Start(diagnosticsConnectionString, diagConfig);

                Trace.TraceInformation("Trace: Initialized OK");
                eLog.WriteEntry("Event: Initialized OK", EventLogEntryType.Information, 1, 1);
            }
            catch (Exception ex)
            {
                DiagnosticsUtils.WriteExceptionToBlobStorage(ex, "Exception in Initialization");
            }
        }
Ejemplo n.º 10
0
        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);
        }