Exemple #1
0
        private void OnError(object sender, ErrorEventArgs e)
        {
            Exception ex = e.GetException();

            TraceFactory.GetTracer().TraceError(ex.ToString());
            ResetWatcher();
        }
 internal CallContextAsyncResult(IDisposable cleanup, AsyncCallback callback, object extraData)
 {
     _cleanup   = cleanup;
     _callback  = callback ?? NoopAsyncCallback;
     AsyncState = extraData;
     _trace     = TraceFactory.Create(TraceName);
 }
Exemple #3
0
        public void SafeKillAllRunningJobInstances(IJobLogger logger)
        {
            try
            {
                Process[] processes = Process.GetProcesses();

                foreach (Process process in processes)
                {
                    StringDictionary processEnvironment;
                    bool             success = ProcessEnvironment.TryGetEnvironmentVariables(process, out processEnvironment);
                    if (success && processEnvironment.ContainsKey(GetJobEnvironmentKey()))
                    {
                        try
                        {
                            process.Kill(true, TraceFactory.GetTracer());
                        }
                        catch (Exception ex)
                        {
                            if (!process.HasExited)
                            {
                                logger.LogWarning("Failed to kill process - {0} for job - {1}\n{2}".FormatInvariant(process.ProcessName, JobName, ex));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex.ToString());
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            TraceFactory.AddTraceConsole();
            SplitArgs Args = new SplitArgs(args);

            string SourceDir = Args.GetValue("sourcedir", "");

            Trace.WriteLine($"Source directory = {SourceDir}");

            if (string.IsNullOrWhiteSpace(SourceDir) || !Directory.Exists(SourceDir))
            {
                Usage($"Missing source directory : directory is missing or access is denied");
            }

            InitTitle($"Processing {SourceDir}");

            EProcessStatus ProcessStatus = ProcessDirectory(new DirectoryInfo(SourceDir));

            if (ProcessStatus != EProcessStatus.Ok)
            {
                ConsoleExtension.Pause();
                Environment.Exit(1);
            }

            //ConsoleExtension.Pause();
            Environment.Exit(0);
        }
Exemple #5
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            SplitArgs Args = new SplitArgs(Environment.GetCommandLineArgs());

            TraceFactory.AddTraceDefaultLogFilename();

            ApplicationInfo.ApplicationStart();
        }
Exemple #6
0
        public void StartJobRun(TriggeredJob triggeredJob, JobSettings jobSettings, string trigger, Action <string, string> reportAction)
        {
            JobSettings = jobSettings;

            if (Settings.IsWebJobsStopped())
            {
                throw new WebJobsStoppedException();
            }

            if (!_lockFile.Lock())
            {
                throw new ConflictException();
            }

            TriggeredJobRunLogger logger = TriggeredJobRunLogger.LogNewRun(triggeredJob, trigger, Environment, TraceFactory, Settings);

            Debug.Assert(logger != null);

            try
            {
                if (_currentRunningJobWaitHandle != null)
                {
                    _currentRunningJobWaitHandle.Dispose();
                    _currentRunningJobWaitHandle = null;
                }

                _currentRunningJobWaitHandle = new ManualResetEvent(false);

                var tracer = TraceFactory.GetTracer();
                var step   = tracer.Step("Run {0} {1}", triggeredJob.JobType, triggeredJob.Name);
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    try
                    {
                        InitializeJobInstance(triggeredJob, logger);
                        RunJobInstance(triggeredJob, logger, logger.Id, trigger, tracer);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("WebJob run failed due to: " + ex);
                    }
                    finally
                    {
                        step.Dispose();
                        logger.ReportEndRun();
                        _lockFile.Release();
                        reportAction(triggeredJob.Name, logger.Id);
                        _currentRunningJobWaitHandle.Set();
                    }
                });
            }
            catch (Exception ex)
            {
                logger.LogError("Failed to start job due to: " + ex);
                _lockFile.Release();
                throw;
            }
        }
Exemple #7
0
 public OwinAppContext()
 {
     _trace  = TraceFactory.Create(TraceName);
     AppName = HostingEnvironment.SiteName + HostingEnvironment.ApplicationID;
     if (string.IsNullOrWhiteSpace(AppName))
     {
         AppName = Guid.NewGuid().ToString();
     }
 }
Exemple #8
0
        private void StartJob(ContinuousJob continuousJob)
        {
            // Do not go further if already started or job is disabled

            if (IsDisabled)
            {
                UpdateStatusIfChanged(ContinuousJobStatus.Stopped);
                return;
            }

            if (Interlocked.Exchange(ref _started, 1) == 1)
            {
                return;
            }

            _continuousJobLogger.ReportStatus(ContinuousJobStatus.Starting);

            _continuousJobThread = new Thread(() =>
            {
                try
                {
                    while (_started == 1 && !IsDisabled)
                    {
                        // Try getting the singleton lock if single is enabled
                        if (!TryGetLockIfSingleton())
                        {
                            // Wait 5 seconds and retry to take the lock
                            WaitForTimeOrStop(TimeSpan.FromSeconds(5));
                            continue;
                        }

                        _continuousJobLogger.StartingNewRun();

                        InitializeJobInstance(continuousJob, _continuousJobLogger);
                        RunJobInstance(continuousJob, _continuousJobLogger, String.Empty);

                        if (_started == 1 && !IsDisabled)
                        {
                            TimeSpan webJobsRestartTime = Settings.GetWebJobsRestartTime();
                            _continuousJobLogger.LogInformation("Process went down, waiting for {0} seconds".FormatInvariant(webJobsRestartTime.TotalSeconds));
                            _continuousJobLogger.ReportStatus(ContinuousJobStatus.PendingRestart);
                            WaitForTimeOrStop(webJobsRestartTime);
                        }
                    }
                }
                catch (Exception ex)
                {
                    TraceFactory.GetTracer().TraceError(ex);
                }
                finally
                {
                    ReleaseSingletonLock();
                }
            });

            _continuousJobThread.Start();
        }
Exemple #9
0
        private static void SetLoggingContext()
        {
            var manifest = GlobalDataStore.Manifest;

            if (manifest != null)
            {
                TraceFactory.SetThreadContextProperty("Dispatcher", manifest.Dispatcher, false);
                TraceFactory.SetSessionContext(manifest.SessionId);
            }
        }
Exemple #10
0
        protected void RunJobInstance(JobBase job, IJobLogger logger, string runId)
        {
            string scriptFileName      = Path.GetFileName(job.ScriptFilePath);
            string scriptFileExtension = Path.GetExtension(job.ScriptFilePath);

            logger.LogInformation("Run script '{0}' with script host - '{1}'".FormatCurrentCulture(scriptFileName, job.ScriptHost.GetType().Name));
            string siteMode = Settings.GetWebSitePolicy();

            _analytics.JobStarted(job.Name.Fuzz(), scriptFileExtension, job.JobType, siteMode);

            try
            {
                var exe = _externalCommandFactory.BuildCommandExecutable(job.ScriptHost.HostPath, WorkingDirectory, IdleTimeout, NullLogger.Instance);

                // Set environment variable to be able to identify all processes spawned for this job
                exe.EnvironmentVariables[GetJobEnvironmentKey()] = "true";
                exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsRootPath]     = WorkingDirectory;
                exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsName]         = job.Name;
                exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsType]         = job.JobType;
                exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsDataPath]     = JobDataPath;
                exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsRunId]        = runId;
                exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsExtraUrlPath] = JobsManagerBase.GetJobExtraInfoUrlFilePath(JobDataPath);

                UpdateStatus(logger, "Running");

                int exitCode =
                    exe.ExecuteReturnExitCode(
                        TraceFactory.GetTracer(),
                        logger.LogStandardOutput,
                        logger.LogStandardError,
                        job.ScriptHost.ArgumentsFormat,
                        job.RunCommand);

                if (exitCode != 0)
                {
                    logger.LogError("Job failed due to exit code " + exitCode);
                }
                else
                {
                    UpdateStatus(logger, "Success");
                }
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                {
                    // We kill the process when refreshing the job
                    logger.LogInformation("Job aborted");
                    UpdateStatus(logger, "Aborted");
                    return;
                }

                logger.LogError(ex.ToString());
            }
        }
Exemple #11
0
        public IEnumerable <string> GetUnsupportedFileNames()
        {
            if (Directory.Exists(dataDirectory.FullName))
            {
                IEnumerable <FileInfo> xmlFiles =
                    dataDirectory.EnumerateFiles("*.xml");
                foreach (FileInfo xmlFile in xmlFiles)
                {
                    // collecting unsupported graphical data
                    string csvFileName =
                        xmlFile.FullName.Replace(".xml", ".csv");
                    LexiaGraphSessionRawData data =
                        LexiaScanDataFactory.CreateWithCsv(
                            xmlFile.FullName, csvFileName);
                    foreach (LexiaChannelRawData lcrData in data.Channels)
                    {
                        if (LexiaChannelDataTypeMapper.
                            GetTypeEnum(lcrData.Header.Mnemocode) ==
                            LexiaChannelType.NOT_SUPPORTED)
                        {
                            yield return(xmlFile.FullName);

                            yield return(csvFileName);
                        }
                    }
                }
            }

            if (Directory.Exists(lexiaInstallationDisk + tracesDataDirectory))
            {
                LexiaPointTypeDataRetriever retr =
                    new LexiaPointTypeDataRetriever(
                        lexiaInstallationDisk + tracesDataDirectory);
                foreach (FileInfo traceFile in retr.GetTraceFiles())
                {
                    TraceFactory factory = new TraceFactory(traceFile);
                    LexiaTrace   trace   = factory.Create();
                    trace.SourceFilePath = traceFile.FullName;
                    if (trace.ParameterSets.Any(ps => ps.Parameters.
                                                Any(p => p.Type == PsaParameterType.Unsupported)) ||
                        trace.ParameterSets.
                        Any(ps => ps.Name == CodeBehindStringResolver.
                            Resolve("UnsupportedDataSet")))
                    {
                        yield return(traceFile.FullName);

                        foreach (string additionalFileName in
                                 retr.GetAdditionalTraceTxtData(traceFile.FullName))
                        {
                            yield return(additionalFileName);
                        }
                    }
                }
            }
        }
Exemple #12
0
        private static void Main(string[] args)
        {
            UnhandledExceptionHandler.Attach();
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            Thread.CurrentThread.SetName("Main");

            VirtualClientController clientController = null;

            try
            {
                TraceFactory.Logger.Debug("Args: {0}".FormatWith(string.Join(" ", args)));
                int    startIndex = 0;
                string sessionId  = string.Empty;
                switch (args.Length)
                {
                case 2:
                    sessionId = args[1];
                    break;

                case 3:
                    sessionId  = args[1];
                    startIndex = int.Parse(args[2], CultureInfo.InvariantCulture);
                    break;

                default:
                    TraceFactory.Logger.Fatal("Invalid number of arguments.  Arguments passed in: {0}".FormatWith(args.Length));
                    TraceFactory.Logger.Fatal("Usage: {0} <Dispatcher Fully Qualified Domain Name> <Session Id> <Start Index for Software Installer>".FormatWith(AppDomain.CurrentDomain.FriendlyName));
                    Environment.Exit(1);
                    break;
                }

                // Set the logging context
                var dispatcher = args[0].Split('.')[0];
                TraceFactory.SetSessionContext(sessionId);
                TraceFactory.SetThreadContextProperty("Dispatcher", dispatcher, false);
                using (var officeWorkerStream =
                           File.Create(Path.Combine(Environment.CurrentDirectory, "OfficeWorkerBootStrapper.exe")))
                {
                    officeWorkerStream.Write(Properties.Resources.OfficeWorkerBootStrapper, 0,
                                             Properties.Resources.OfficeWorkerBootStrapper.Length);
                    officeWorkerStream.Flush(true);
                }


                clientController = new VirtualClientController(dispatcher, startIndex);
                clientController.Start(sessionId);
                TraceFactory.Logger.Debug("Client controller started.  Press Enter to terminate.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                TraceFactory.Logger.Error(ex);
            }
        }
Exemple #13
0
        /// <summary>
        /// args[0] = VirtualResourceId
        /// args[1] = Host Name
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            Thread.CurrentThread.SetName("PerfMoncollectorMain");
            TraceFactory.SetThreadContextProperty("ResourceName", "PerfMonCounter_" + DateTime.Now.ToString("ddMMyyy", CultureInfo.InvariantCulture));

            UnhandledExceptionHandler.Attach();

            using (Program program = new Program(args[0]))
            {
                Console.ReadLine();
            }
        }
Exemple #14
0
 protected void NotifyShutdownJob()
 {
     try
     {
         FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(_shutdownNotificationFilePath));
         OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(_shutdownNotificationFilePath, DateTime.UtcNow.ToString()));
     }
     catch (Exception ex)
     {
         TraceFactory.GetTracer().TraceError(ex);
         _analytics.UnexpectedException(ex);
     }
 }
Exemple #15
0
        internal SharedTimer(TimeSpan interval)
        {
            Contract.Assert(interval > TimeSpan.Zero);
            _trace = TraceFactory.Create(TraceName);

            _interval         = interval;
            _processLock      = new object();
            _addLock          = new object();
            _registrations    = new LinkedList <TimerRegistration>();
            _newRegistrations = new LinkedList <TimerRegistration>();
            _emptyList        = new LinkedList <TimerRegistration>();
            _timer            = new Timer(ProcessTimers, null, _interval, _interval);
        }
        private void SetSessionContext(SessionMapElement element)
        {
            string sessionId = null;
            string elementId = null;

            if (element != null)
            {
                sessionId = element.SessionId;
                elementId = element.Id.ToString();
            }
            TraceFactory.SetSessionContext(sessionId);
            TraceFactory.SetThreadContextProperty("SessionMapElementId", elementId, false);
        }
 public void ResetLockedStatusFile()
 {
     try
     {
         FileStream newLockedStatusFile = File.Open(GetStatusFilePath(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
         OperationManager.SafeExecute(() => _lockedStatusFile?.Dispose());
         _lockedStatusFile = newLockedStatusFile;
     }
     catch (Exception ex)
     {
         TraceFactory.GetTracer().TraceError(ex);
         throw;
     }
 }
Exemple #18
0
        static void Main(string[] args)
        {
            SplitArgs Args = new SplitArgs(args);

            //TraceFactory.AddTraceConsole();
            TraceFactory.AddTraceDefaultLogFilename();

            ApplicationInfo.ApplicationStart();

            Test();

            ConsoleExtension.Pause();
            ApplicationInfo.ApplicationStop();
        }
Exemple #19
0
 public static void Initialize()
 {
     try
     {
         if (OwinBuilder.IsAutomaticAppStartupEnabled)
         {
             HttpApplication.RegisterModule(typeof(OwinHttpModule));
         }
     }
     catch (Exception ex)
     {
         ITrace trace = TraceFactory.Create(TraceName);
         trace.WriteError(Resources.Trace_RegisterModuleException, ex);
         throw;
     }
 }
Exemple #20
0
 protected void ReportStatus <TJobStatus>(TJobStatus status, bool logStatus) where TJobStatus : class, IJobStatus
 {
     try
     {
         string content = JsonConvert.SerializeObject(status, JsonSerializerSettings);
         SafeLogToFile(GetStatusFilePath(), content, isAppend: false);
         if (logStatus)
         {
             LogInformation("Status changed to " + status.Status);
         }
     }
     catch (Exception ex)
     {
         TraceFactory.GetTracer().TraceError(ex);
     }
 }
Exemple #21
0
        protected override void ReportStatus <TJobStatus>(TJobStatus status, bool logStatus)
        {
            try
            {
                if (!FileSystemHelpers.FileExists(GetStatusFilePath()))
                {
                    ResetLockedStatusFile();
                }
            }
            catch (Exception ex)
            {
                TraceFactory.GetTracer().TraceError(ex);
            }

            base.ReportStatus(status, logStatus);
        }
Exemple #22
0
        private void ResetLockedStatusFile()
        {
            try
            {
                if (_lockedStatusFile != null)
                {
                    _lockedStatusFile.Dispose();
                }
            }
            catch (Exception ex)
            {
                TraceFactory.GetTracer().TraceError(ex);
            }

            _lockedStatusFile = File.Open(GetStatusFilePath(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
        }
        internal OwinWebSocketWrapper(WebSocketContext context)
        {
            Contract.Assert(context != null);
            _trace   = TraceFactory.Create(TraceName);
            _context = context;
            _cancellationTokenSource = new CancellationTokenSource();

            _environment = new ConcurrentDictionary <string, object>();
            _environment[WebSocketConstants.WebSocketSendAsyncKey]     = new WebSocketSendAsync(SendAsync);
            _environment[WebSocketConstants.WebSocketReceiveAyncKey]   = new WebSocketReceiveAsync(ReceiveAsync);
            _environment[WebSocketConstants.WebSocketCloseAsyncKey]    = new WebSocketCloseAsync(CloseAsync);
            _environment[WebSocketConstants.WebSocketCallCancelledKey] = _cancellationTokenSource.Token;
            _environment[WebSocketConstants.WebSocketVersionKey]       = WebSocketConstants.WebSocketVersion;

            _environment[typeof(WebSocketContext).FullName] = _context;
        }
Exemple #24
0
 public static void Initialize()
 {
     try
     {
         if (OwinBuilder.IsAutomaticAppStartupEnabled)
         {
             Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(OwinHttpModule));
         }
     }
     catch (Exception ex)
     {
         ITrace trace = TraceFactory.Create(TraceName);
         trace.WriteError(Resources.Trace_RegisterModuleException, ex);
         throw;
     }
 }
Exemple #25
0
        static void Main(string[] args)
        {
            var database = args[0];
            _sessionId = args[1];
            var proxyServiceUri = new Uri(args[2]);

            TraceFactory.SetThreadContextProperty("PID", Process.GetCurrentProcess().Id.ToString());
            TraceFactory.SetSessionContext(_sessionId);
            TraceFactory.Logger.Debug(string.Join(", ", args));

            UnhandledExceptionHandler.Attach();

            GlobalSettings.Load(database);
            FrameworkServicesInitializer.InitializeExecution();

            try
            {
                using (var sessionProxy = new SessionProxy(_sessionId))
                {
                    sessionProxy.OnExit += _sessionProxy_OnExit;
                    sessionProxy.StartFrontendService(proxyServiceUri);
                    sessionProxy.StartBackendService();

                    TraceFactory.Logger.Debug("Notify Dispatcher process is up...");
                    Retry.WhileThrowing
                        (
                            () =>
                            {
                                using (var connection = SessionDispatcherConnection.Create("localhost"))
                                {
                                    connection.Channel.NotifyProxyStarted(_sessionId);
                                }
                            },
                            10,
                            TimeSpan.FromSeconds(2),
                            new List<Type>() { typeof(EndpointNotFoundException) }
                        );
                    TraceFactory.Logger.Debug("Notify Dispatcher process is up...Done");

                    _mainThreadBlock.WaitOne();
                }
            }
            catch (Exception ex)
            {
                TraceFactory.Logger.Error(ex);
            }
        }
Exemple #26
0
        private void UpdateAppConfig(string configFilePath)
        {
            try
            {
                var settings = SettingsProcessor.Instance;

                bool updateXml = false;

                // Read app.config
                string        exeFilePath = configFilePath.Substring(0, configFilePath.Length - ".config".Length);
                Configuration config      = ConfigurationManager.OpenExeConfiguration(exeFilePath);

                foreach (var appSetting in settings.AppSettings)
                {
                    config.AppSettings.Settings.Remove(appSetting.Key);
                    config.AppSettings.Settings.Add(appSetting.Key, appSetting.Value);
                    updateXml = true;
                }

                foreach (ConnectionStringSettings connectionString in settings.ConnectionStrings)
                {
                    ConnectionStringSettings currentConnectionString = config.ConnectionStrings.ConnectionStrings[connectionString.Name];
                    if (currentConnectionString != null)
                    {
                        // Update provider name if connection string already exists and provider name is null (custom type)
                        connectionString.ProviderName = connectionString.ProviderName ?? currentConnectionString.ProviderName;
                    }

                    config.ConnectionStrings.ConnectionStrings.Remove(connectionString.Name);
                    config.ConnectionStrings.ConnectionStrings.Add(connectionString);

                    updateXml = true;
                }

                if (updateXml)
                {
                    // Write updated app.config
                    config.Save();
                }
            }
            catch (Exception ex)
            {
                TraceFactory.GetTracer().TraceError(ex);
                _analytics.UnexpectedException(ex);
            }
        }
 /// <summary>
 /// Registers the OWIN request processing module.
 /// </summary>
 public static void Initialize()
 {
     try
     {
         if (OwinBuilder.IsAutomaticAppStartupEnabled)
         {
             HttpApplication.RegisterModule(typeof(OwinHttpModule));
         }
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         ITrace    trace     = TraceFactory.Create("Microsoft.Owin.Host.SystemWeb.PreApplicationStart");
         trace.WriteError(Resources.Trace_RegisterModuleException, exception);
         throw;
     }
 }
Exemple #28
0
        /// <summary>
        /// Updates the app.config using XML directly for injecting trace providers.
        /// </summary>
        private void UpdateAppConfigAddTraceListeners(string configFilePath)
        {
            try
            {
                var xmlConfig = XDocument.Load(configFilePath);

                // Make sure the trace listeners section available otherwise create it
                var configurationElement     = GetOrCreateElement(xmlConfig, "configuration");
                var systemDiagnosticsElement = GetOrCreateElement(configurationElement, "system.diagnostics");
                var traceElement             = GetOrCreateElement(systemDiagnosticsElement, "trace");
                var listenersElement         = GetOrCreateElement(traceElement, "listeners");

                // Inject existing trace providers to the target app.config
                foreach (TraceListener listener in Trace.Listeners)
                {
                    // Ignore the default trace provider
                    if (String.Equals(listener.Name, "default", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    // Do not add a trace provider if it already exists (by name)
                    XElement listenerElement = listenersElement.Elements().FirstOrDefault(xElement =>
                    {
                        XAttribute nameAttribute = xElement.Attribute("name");
                        return(nameAttribute != null && String.Equals(nameAttribute.Value, listener.Name, StringComparison.OrdinalIgnoreCase));
                    });

                    if (listenerElement == null)
                    {
                        var addElement = new XElement("add");
                        addElement.Add(new XAttribute("name", listener.Name));
                        addElement.Add(new XAttribute("type", listener.GetType().AssemblyQualifiedName));
                        listenersElement.AddFirst(addElement);
                    }
                }

                FileSystemHelpers.WriteAllText(configFilePath, xmlConfig.ToString());
            }
            catch (Exception ex)
            {
                TraceFactory.GetTracer().TraceError(ex);
                _analytics.UnexpectedException(ex);
            }
        }
Exemple #29
0
 protected void SafeLogToFile(string path, string content, bool isAppend = true)
 {
     try
     {
         if (isAppend)
         {
             OperationManager.Attempt(() => FileSystemHelpers.AppendAllTextToFile(path, content));
         }
         else
         {
             OperationManager.Attempt(() => FileSystemHelpers.WriteAllTextToFile(path, content));
         }
     }
     catch (Exception ex)
     {
         TraceFactory.GetTracer().TraceError(ex);
     }
 }
Exemple #30
0
 public static void Initialize()
 {
     try
     {
         string autoAppStartup = ConfigurationManager.AppSettings[Constants.OwinAutomaticAppStartup];
         if (autoAppStartup == null ||
             string.Equals("true", autoAppStartup, StringComparison.OrdinalIgnoreCase))
         {
             DynamicModuleUtility.RegisterModule(typeof(OwinHttpModule));
         }
     }
     catch (Exception ex)
     {
         ITrace trace = TraceFactory.Create(TraceName);
         trace.WriteError(Resources.Trace_RegisterModuleException, ex);
         throw;
     }
 }