/// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="state">The task state.</param>
        public async void ExecuteAsync(object?state)
        {
            try
            {
                // First, stop the timer, we do not want tasks to execute in parallel
                _timer?.Change(Timeout.Infinite, 0);

                // Delegate work to method returning a task, that can be called and asserted in a unit test.
                // Without this there can be behaviour where tests pass, but an error within them causes the test
                // running process to crash.
                // Hat-tip: https://stackoverflow.com/a/14207615/489433
                await PerformExecuteAsync(state);
            }
            catch (Exception ex)
            {
                ILogger logger = _logger ?? StaticApplicationLogging.CreateLogger(GetType());
                logger.LogError(ex, "Unhandled exception in recurring hosted service.");
            }
            finally
            {
                // Resume now that the task is complete - Note we use period in both because we don't want to execute again after the delay.
                // So first execution is after _delay, and the we wait _period between each
                _timer?.Change((int)_period.TotalMilliseconds, (int)_period.TotalMilliseconds);
            }
        }
Exemple #2
0
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _components.Terminate();
            await _eventAggregator.PublishAsync(new UmbracoApplicationStoppingNotification(), cancellationToken);

            StaticApplicationLogging.Initialize(null);
        }
Exemple #3
0
        protected MicrosoftSqlSyntaxProviderBase()
        {
            _logger = StaticApplicationLogging.CreateLogger <TSyntax>();

            AutoIncrementDefinition = "IDENTITY(1,1)";
            GuidColumnDefinition    = "UniqueIdentifier";
            RealColumnDefinition    = "FLOAT";
            BoolColumnDefinition    = "BIT";
            DecimalColumnDefinition = "DECIMAL(38,6)";
            TimeColumnDefinition    = "TIME"; //SQLSERVER 2008+
            BlobColumnDefinition    = "VARBINARY(MAX)";
        }
    /// <summary>
    ///     Creates an <see cref="IUmbracoBuilder" /> and registers basic Umbraco services
    /// </summary>
    public static IUmbracoBuilder AddUmbraco(
        this IServiceCollection services,
        IWebHostEnvironment webHostEnvironment,
        IConfiguration config)
    {
        if (services is null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        if (config is null)
        {
            throw new ArgumentNullException(nameof(config));
        }

        // Setup static application logging ASAP (e.g. during configure services).
        // Will log to SilentLogger until Serilog.Log.Logger is setup.
        StaticApplicationLogging.Initialize(new SerilogLoggerFactory());

        // The DataDirectory is used to resolve database file paths (directly supported by SQL CE and manually replaced for LocalDB)
        AppDomain.CurrentDomain.SetData(
            "DataDirectory",
            webHostEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data));

        // Manually create and register the HttpContextAccessor. In theory this should not be registered
        // again by the user but if that is the case it's not the end of the world since HttpContextAccessor
        // is just based on AsyncLocal, see https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http/src/HttpContextAccessor.cs
        IHttpContextAccessor httpContextAccessor = new HttpContextAccessor();

        services.AddSingleton(httpContextAccessor);

        var requestCache = new HttpContextRequestAppCache(httpContextAccessor);
        var appCaches    = AppCaches.Create(requestCache);

        services.ConfigureOptions <ConfigureKestrelServerOptions>();
        services.ConfigureOptions <ConfigureFormOptions>();

        IProfiler profiler = GetWebProfiler(config);

        services.AddLogger(webHostEnvironment, config);

        ILoggerFactory loggerFactory = new SerilogLoggerFactory();

        TypeLoader typeLoader = services.AddTypeLoader(Assembly.GetEntryAssembly(), loggerFactory, config);

        IHostingEnvironment tempHostingEnvironment = GetTemporaryHostingEnvironment(webHostEnvironment, config);

        return(new UmbracoBuilder(services, config, typeLoader, loggerFactory, profiler, appCaches, tempHostingEnvironment));
    }
Exemple #5
0
 public SqlServerSyntaxProvider(IOptions <GlobalSettings> globalSettings)
     : this(globalSettings, StaticApplicationLogging.CreateLogger <SqlServerSyntaxProvider>())
 {
 }
Exemple #6
0
        /// <inheritdoc/>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _cancellationToken = cancellationToken;
            StaticApplicationLogging.Initialize(_loggerFactory);
            StaticServiceProvider.Instance = _serviceProvider;

            AppDomain.CurrentDomain.UnhandledException += (_, args) =>
            {
                var exception     = (Exception)args.ExceptionObject;
                var isTerminating = args.IsTerminating; // always true?

                var msg = "Unhandled exception in AppDomain";

                if (isTerminating)
                {
                    msg += " (terminating)";
                }

                msg += ".";

                _logger.LogError(exception, msg);
            };

            // acquire the main domain - if this fails then anything that should be registered with MainDom will not operate
            AcquireMainDom();

            await _eventAggregator.PublishAsync(new UmbracoApplicationMainDomAcquiredNotification(), cancellationToken);

            // notify for unattended install
            await _eventAggregator.PublishAsync(new RuntimeUnattendedInstallNotification());

            DetermineRuntimeLevel();

            if (!State.UmbracoCanBoot())
            {
                return; // The exception will be rethrown by BootFailedMiddelware
            }

            IApplicationShutdownRegistry hostingEnvironmentLifetime = _applicationShutdownRegistry;

            if (hostingEnvironmentLifetime == null)
            {
                throw new InvalidOperationException($"An instance of {typeof(IApplicationShutdownRegistry)} could not be resolved from the container, ensure that one if registered in your runtime before calling {nameof(IRuntime)}.{nameof(StartAsync)}");
            }

            // if level is Run and reason is UpgradeMigrations, that means we need to perform an unattended upgrade
            var unattendedUpgradeNotification = new RuntimeUnattendedUpgradeNotification();
            await _eventAggregator.PublishAsync(unattendedUpgradeNotification);

            switch (unattendedUpgradeNotification.UnattendedUpgradeResult)
            {
            case RuntimeUnattendedUpgradeNotification.UpgradeResult.HasErrors:
                if (State.BootFailedException == null)
                {
                    throw new InvalidOperationException($"Unattended upgrade result was {RuntimeUnattendedUpgradeNotification.UpgradeResult.HasErrors} but no {nameof(BootFailedException)} was registered");
                }
                // we cannot continue here, the exception will be rethrown by BootFailedMiddelware
                return;

            case RuntimeUnattendedUpgradeNotification.UpgradeResult.CoreUpgradeComplete:
            case RuntimeUnattendedUpgradeNotification.UpgradeResult.PackageMigrationComplete:
                // upgrade is done, set reason to Run
                DetermineRuntimeLevel();
                break;

            case RuntimeUnattendedUpgradeNotification.UpgradeResult.NotRequired:
                break;
            }

            await _eventAggregator.PublishAsync(new UmbracoApplicationComponentsInstallingNotification(State.Level), cancellationToken);

            // create & initialize the components
            _components.Initialize();

            await _eventAggregator.PublishAsync(new UmbracoApplicationStartingNotification(State.Level), cancellationToken);
        }
Exemple #7
0
        private async Task StartAsync(CancellationToken cancellationToken, bool isRestarting)
        {
            // Store token, so we can re-use this during restart
            _cancellationToken = cancellationToken;

            if (isRestarting == false)
            {
                StaticApplicationLogging.Initialize(_loggerFactory);
                StaticServiceProvider.Instance = _serviceProvider;

                AppDomain.CurrentDomain.UnhandledException += (_, args)
                                                              => _logger.LogError(args.ExceptionObject as Exception, $"Unhandled exception in AppDomain{(args.IsTerminating ? " (terminating)" : null)}.");
            }

            // Acquire the main domain - if this fails then anything that should be registered with MainDom will not operate
            AcquireMainDom();

            // TODO (V10): Remove this obsoleted notification publish.
            await _eventAggregator.PublishAsync(new UmbracoApplicationMainDomAcquiredNotification(), cancellationToken);

            // Notify for unattended install
            await _eventAggregator.PublishAsync(new RuntimeUnattendedInstallNotification(), cancellationToken);

            DetermineRuntimeLevel();

            if (!State.UmbracoCanBoot())
            {
                // We cannot continue here, the exception will be rethrown by BootFailedMiddelware
                return;
            }

            IApplicationShutdownRegistry hostingEnvironmentLifetime = _applicationShutdownRegistry;

            if (hostingEnvironmentLifetime == null)
            {
                throw new InvalidOperationException($"An instance of {typeof(IApplicationShutdownRegistry)} could not be resolved from the container, ensure that one if registered in your runtime before calling {nameof(IRuntime)}.{nameof(StartAsync)}");
            }

            // If level is Run and reason is UpgradeMigrations, that means we need to perform an unattended upgrade
            var unattendedUpgradeNotification = new RuntimeUnattendedUpgradeNotification();
            await _eventAggregator.PublishAsync(unattendedUpgradeNotification, cancellationToken);

            switch (unattendedUpgradeNotification.UnattendedUpgradeResult)
            {
            case RuntimeUnattendedUpgradeNotification.UpgradeResult.HasErrors:
                if (State.BootFailedException == null)
                {
                    throw new InvalidOperationException($"Unattended upgrade result was {RuntimeUnattendedUpgradeNotification.UpgradeResult.HasErrors} but no {nameof(BootFailedException)} was registered");
                }

                // We cannot continue here, the exception will be rethrown by BootFailedMiddelware
                return;

            case RuntimeUnattendedUpgradeNotification.UpgradeResult.CoreUpgradeComplete:
            case RuntimeUnattendedUpgradeNotification.UpgradeResult.PackageMigrationComplete:
                // Upgrade is done, set reason to Run
                DetermineRuntimeLevel();
                break;

            case RuntimeUnattendedUpgradeNotification.UpgradeResult.NotRequired:
                break;
            }

            // TODO (V10): Remove this obsoleted notification publish
            await _eventAggregator.PublishAsync(new UmbracoApplicationComponentsInstallingNotification(State.Level), cancellationToken);

            // Initialize the components
            _components.Initialize();

            await _eventAggregator.PublishAsync(new UmbracoApplicationStartingNotification(State.Level, isRestarting), cancellationToken);

            if (isRestarting == false)
            {
                // Add application started and stopped notifications last (to ensure they're always published after starting)
                _hostApplicationLifetime.ApplicationStarted.Register(() => _eventAggregator.Publish(new UmbracoApplicationStartedNotification(false)));
                _hostApplicationLifetime.ApplicationStopped.Register(() => _eventAggregator.Publish(new UmbracoApplicationStoppedNotification(false)));
            }
        }