示例#1
0
        public TestHelper()
            : base(typeof(TestHelper).Assembly)
        {
            var httpContext = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = IPAddress.Parse("127.0.0.1");
            _httpContextAccessor = Mock.Of <IHttpContextAccessor>(x => x.HttpContext == httpContext);
            _ipResolver          = new AspNetCoreIpResolver(_httpContextAccessor);

            string contentRoot = Assembly.GetExecutingAssembly().GetRootDirectorySafe();

            // The mock for IWebHostEnvironment has caused a good few issues.
            // We can UseContentRoot, UseWebRoot etc on the host builder instead.
            // possibly going down rabbit holes though as would need to cleanup all usages of
            // GetHostingEnvironment & GetWebHostEnvironment.
            var hostEnvironment = new Mock <IWebHostEnvironment>();

            // This must be the assembly name for the WebApplicationFactory to work.
            hostEnvironment.Setup(x => x.ApplicationName).Returns(GetType().Assembly.GetName().Name);
            hostEnvironment.Setup(x => x.ContentRootPath).Returns(() => contentRoot);
            hostEnvironment.Setup(x => x.ContentRootFileProvider).Returns(() => new PhysicalFileProvider(contentRoot));
            hostEnvironment.Setup(x => x.WebRootPath).Returns(() => WorkingDirectory);
            hostEnvironment.Setup(x => x.WebRootFileProvider).Returns(() => new PhysicalFileProvider(WorkingDirectory));
            hostEnvironment.Setup(x => x.EnvironmentName).Returns("Tests");

            // We also need to expose it as the obsolete interface since netcore's WebApplicationFactory casts it.
            hostEnvironment.As <Microsoft.AspNetCore.Hosting.IHostingEnvironment>();

            _hostEnvironment = hostEnvironment.Object;

            _hostingLifetime     = new AspNetCoreApplicationShutdownRegistry(Mock.Of <IHostApplicationLifetime>());
            ConsoleLoggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ProfilingLogger      = new ProfilingLogger(ConsoleLoggerFactory.CreateLogger <ProfilingLogger>(), Profiler);
        }
示例#2
0
 public CoreRuntime(
     ILoggerFactory loggerFactory,
     IRuntimeState state,
     ComponentCollection components,
     IApplicationShutdownRegistry applicationShutdownRegistry,
     IProfilingLogger profilingLogger,
     IMainDom mainDom,
     IUmbracoDatabaseFactory databaseFactory,
     IEventAggregator eventAggregator,
     IHostingEnvironment hostingEnvironment,
     IUmbracoVersion umbracoVersion,
     IServiceProvider?serviceProvider)
     : this(
         state,
         loggerFactory,
         components,
         applicationShutdownRegistry,
         profilingLogger,
         mainDom,
         databaseFactory,
         eventAggregator,
         hostingEnvironment,
         umbracoVersion,
         serviceProvider,
         serviceProvider?.GetRequiredService <IHostApplicationLifetime>())
 {
 }
 // used in WebBootManager + tests
 public XmlPublishedSnapshotService(
     ServiceContext serviceContext,
     IPublishedContentTypeFactory publishedContentTypeFactory,
     IScopeProvider scopeProvider,
     IAppCache requestCache,
     IPublishedSnapshotAccessor publishedSnapshotAccessor,
     IVariationContextAccessor variationContextAccessor,
     IUmbracoContextAccessor umbracoContextAccessor,
     IDocumentRepository documentRepository,
     IMediaRepository mediaRepository,
     IMemberRepository memberRepository,
     IDefaultCultureAccessor defaultCultureAccessor,
     ILoggerFactory loggerFactory,
     GlobalSettings globalSettings,
     IHostingEnvironment hostingEnvironment,
     IApplicationShutdownRegistry hostingLifetime,
     IShortStringHelper shortStringHelper,
     IEntityXmlSerializer entitySerializer,
     MainDom mainDom,
     bool testing = false,
     bool enableRepositoryEvents = true)
     : this(serviceContext, publishedContentTypeFactory, scopeProvider, requestCache,
            publishedSnapshotAccessor, variationContextAccessor, umbracoContextAccessor,
            documentRepository, mediaRepository, memberRepository,
            defaultCultureAccessor,
            loggerFactory, globalSettings, hostingEnvironment, hostingLifetime, shortStringHelper, entitySerializer, null, mainDom, testing, enableRepositoryEvents)
 {
     _umbracoContextAccessor = umbracoContextAccessor;
 }
示例#4
0
    /// <summary>
    ///     Initializes a new instance of the <see cref="CoreRuntime" /> class.
    /// </summary>
    public CoreRuntime(
        IRuntimeState state,
        ILoggerFactory loggerFactory,
        ComponentCollection components,
        IApplicationShutdownRegistry applicationShutdownRegistry,
        IProfilingLogger profilingLogger,
        IMainDom mainDom,
        IUmbracoDatabaseFactory databaseFactory,
        IEventAggregator eventAggregator,
        IHostingEnvironment hostingEnvironment,
        IUmbracoVersion umbracoVersion,
        IServiceProvider?serviceProvider,
        IHostApplicationLifetime?hostApplicationLifetime)
    {
        State = state;

        _loggerFactory = loggerFactory;
        _components    = components;
        _applicationShutdownRegistry = applicationShutdownRegistry;
        _profilingLogger             = profilingLogger;
        _mainDom                 = mainDom;
        _databaseFactory         = databaseFactory;
        _eventAggregator         = eventAggregator;
        _hostingEnvironment      = hostingEnvironment;
        _umbracoVersion          = umbracoVersion;
        _serviceProvider         = serviceProvider;
        _hostApplicationLifetime = hostApplicationLifetime;
        _logger = _loggerFactory.CreateLogger <CoreRuntime>();
    }
示例#5
0
 public CoreRuntime(
     ILoggerFactory loggerFactory,
     IRuntimeState state,
     ComponentCollection components,
     IApplicationShutdownRegistry applicationShutdownRegistry,
     IProfilingLogger profilingLogger,
     IMainDom mainDom,
     IUmbracoDatabaseFactory databaseFactory,
     IEventAggregator eventAggregator,
     IHostingEnvironment hostingEnvironment,
     IUmbracoVersion umbracoVersion)
     : this(
         loggerFactory,
         state,
         components,
         applicationShutdownRegistry,
         profilingLogger,
         mainDom,
         databaseFactory,
         eventAggregator,
         hostingEnvironment,
         umbracoVersion,
         null)
 {
 }
示例#6
0
        /// <inheritdoc/>
        public bool Acquire(IApplicationShutdownRegistry hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));

            return(LazyInitializer.EnsureInitialized(ref _isMainDom, ref _isInitialized, ref _locko, () =>
            {
                hostingEnvironment.RegisterObject(this);
                return Acquire();
            }).Value);
        }
        public InMemoryModelFactory(
            Lazy <UmbracoServices> umbracoServices,
            IProfilingLogger profilingLogger,
            ILogger <InMemoryModelFactory> logger,
            IOptionsMonitor <ModelsBuilderSettings> config,
            IHostingEnvironment hostingEnvironment,
            IApplicationShutdownRegistry hostingLifetime,
            IPublishedValueFallback publishedValueFallback,
            ApplicationPartManager applicationPartManager)
        {
            _umbracoServices        = umbracoServices;
            _profilingLogger        = profilingLogger;
            _logger                 = logger;
            _config                 = config.CurrentValue;
            _hostingEnvironment     = hostingEnvironment;
            _hostingLifetime        = hostingLifetime;
            _publishedValueFallback = publishedValueFallback;
            _applicationPartManager = applicationPartManager;
            _errors                 = new ModelsGenerationError(config, _hostingEnvironment);
            _ver     = 1;  // zero is for when we had no version
            _skipver = -1; // nothing to skip

            if (!hostingEnvironment.IsHosted)
            {
                return;
            }

            config.OnChange(x => _config = x);
            _pureLiveDirectory           = new Lazy <string>(PureLiveDirectoryAbsolute);

            if (!Directory.Exists(_pureLiveDirectory.Value))
            {
                Directory.CreateDirectory(_pureLiveDirectory.Value);
            }

            // BEWARE! if the watcher is not properly released then for some reason the
            // BuildManager will start confusing types - using a 'registered object' here
            // though we should probably plug into Umbraco's MainDom - which is internal
            _hostingLifetime.RegisterObject(this);
            _watcher                     = new FileSystemWatcher(_pureLiveDirectory.Value);
            _watcher.Changed            += WatcherOnChanged;
            _watcher.EnableRaisingEvents = true;

            // get it here, this need to be fast
            _debugLevel = _config.DebugLevel;

            AssemblyLoadContext.Default.Resolving += OnResolvingDefaultAssemblyLoadContext;
        }
示例#8
0
        public TemplateWatcher(
            IConfiguration configuration,
            IApplicationShutdownRegistry hostingLifetime,
            ILogger <TemplateWatcher> logger,
            IFileService fileService,
            FileSystems fileSystems,
            IShortStringHelper shortStringHelper,
            IHostEnvironment hostEnvironment)
        {
            _fileService       = fileService;
            _shortStringHelper = shortStringHelper;
            _hostEnvironment   = hostEnvironment;
            _hostingLifetime   = hostingLifetime;

            _logger = logger;

            _templateFileSystem = fileSystems.MvcViewsFileSystem;

            _viewsFolder = _hostEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews);


            //
            // use appsettings.json to turn on/off.
            //
            // "uSync" : {
            //      "AutoTemplates" : {
            //          "Enabled": true,
            //          "Delete": false
            //      }
            // }
            //

            _enabled       = configuration.GetValue <bool>("uSync:AutoTemplates:Enabled", false); // by default this might be off.
            _deleteMissing = configuration.GetValue <bool>("uSync:AutoTemplates:Delete", false);
            _delay         = configuration.GetValue <int>("uSync:AutoTemplates:Delay", 1000);     // wait.

            _hostingLifetime.RegisterObject(this);
            _watcher          = new FileSystemWatcher(_viewsFolder);
            _watcher.Changed += Watcher_FileChanged;
            _watcher.Deleted += Watcher_FileDeleted;
            _watcher.Renamed += Watcher_Renamed;
        }
        // used in some tests
        internal XmlPublishedSnapshotService(
            ServiceContext serviceContext,
            IPublishedContentTypeFactory publishedContentTypeFactory,
            IScopeProvider scopeProvider,
            IAppCache requestCache,
            IPublishedSnapshotAccessor publishedSnapshotAccessor,
            IVariationContextAccessor variationContextAccessor,
            IUmbracoContextAccessor umbracoContextAccessor,
            IDocumentRepository documentRepository,
            IMediaRepository mediaRepository,
            IMemberRepository memberRepository,
            IDefaultCultureAccessor defaultCultureAccessor,
            ILoggerFactory loggerFactory,
            GlobalSettings globalSettings,
            IHostingEnvironment hostingEnvironment,
            IApplicationShutdownRegistry hostingLifetime,
            IShortStringHelper shortStringHelper,
            IEntityXmlSerializer entitySerializer,
            PublishedContentTypeCache contentTypeCache,
            MainDom mainDom,
            bool testing,
            bool enableRepositoryEvents)
        {
            _routesCache = new RoutesCache();
            _publishedContentTypeFactory = publishedContentTypeFactory;
            _contentTypeCache            = contentTypeCache
                                           ?? new PublishedContentTypeCache(serviceContext.ContentTypeService, serviceContext.MediaTypeService, serviceContext.MemberTypeService, publishedContentTypeFactory, loggerFactory.CreateLogger <PublishedContentTypeCache>());

            _xmlStore = new XmlStore(serviceContext.ContentTypeService, serviceContext.ContentService, scopeProvider, _routesCache,
                                     _contentTypeCache, publishedSnapshotAccessor, mainDom, testing, enableRepositoryEvents,
                                     documentRepository, mediaRepository, memberRepository, entitySerializer, hostingEnvironment, hostingLifetime, shortStringHelper);

            _domainService            = serviceContext.DomainService;
            _mediaService             = serviceContext.MediaService;
            _userService              = serviceContext.UserService;
            _defaultCultureAccessor   = defaultCultureAccessor;
            _variationContextAccessor = variationContextAccessor;
            _requestCache             = requestCache;
            _umbracoContextAccessor   = umbracoContextAccessor;
            _globalSettings           = globalSettings;
            _entitySerializer         = entitySerializer;
        }
示例#10
0
 // always acquire
 public bool Acquire(IApplicationShutdownRegistry hostingEnvironment) => true;
示例#11
0
    private async Task StartAsync(CancellationToken cancellationToken, bool isRestarting)
    {
        // Store token, so we can re-use this during restart
        _cancellationToken = cancellationToken;

        // Just in-case HostBuilder.ConfigureUmbracoDefaults() isn't used (e.g. upgrade from 9 and ignored advice).
        if (StaticServiceProvider.Instance == null !)
        {
            StaticServiceProvider.Instance = _serviceProvider !;
        }

        if (isRestarting == false)
        {
            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)));
        }
    }
示例#12
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);
        }