public WorkContext GetContext(string tenantName)
        {
            var currentWorkContext = _wca.GetContext();

            if (_shellSettings.Name == tenantName)
            {
                return(currentWorkContext);
            }

            if (!TenantWorkContextScopes.ContainsKey(tenantName))
            {
                var tenantShellSettings = _shellSettingsManager.LoadSettings().Where(settings => settings.Name == tenantName).Single();
                var shellContext        = _orchardHost.GetShellContext(tenantShellSettings);

                //var tenantBaseUrl = _urlHelper.Tenant(tenantShellSettings);
                //var httpContextBase = new Orchard.Mvc.MvcModule.HttpContextPlaceholder(tenantBaseUrl);
                //var httpContext = shellContext.LifetimeScope.Resolve<HttpContextBase>();
                //context.Resolve<IWorkContextAccessor>().CreateWorkContextScope(httpContextBase);
                //return httpContextBase;

                //shellContext.LifetimeScope.Resolve<IHttpContextAcсessor>()
                var tenantWorkContextScope = shellContext.LifetimeScope.Resolve <IWorkContextAccessor>().CreateWorkContextScope();
                tenantWorkContextScope.WorkContext.CurrentCulture = currentWorkContext.CurrentCulture;
                TenantWorkContextScopes[tenantName] = tenantWorkContextScope;
            }
            return(TenantWorkContextScopes[tenantName].WorkContext);
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            IComponentRegistration registration;

            if (constructorString == null)
            {
                throw new ArgumentNullException("constructorString");
            }

            if (constructorString == string.Empty)
            {
                throw new ArgumentOutOfRangeException("constructorString");
            }

            if (HostContainer == null)
            {
                throw new InvalidOperationException();
            }

            // Create work context
            IRunningShellTable runningShellTable = HostContainer.Resolve <IRunningShellTable>();
            ShellSettings      shellSettings     = runningShellTable.Match(baseAddresses.First().Host, baseAddresses.First().LocalPath);

            IOrchardHost         orchardHost         = HostContainer.Resolve <IOrchardHost>();
            ShellContext         shellContext        = orchardHost.GetShellContext(shellSettings);
            IWorkContextAccessor workContextAccessor = shellContext.LifetimeScope.Resolve <IWorkContextAccessor>();
            WorkContext          workContext         = workContextAccessor.GetContext();

            if (workContext == null)
            {
                using (IWorkContextScope workContextScope = workContextAccessor.CreateWorkContextScope()) {
                    ILifetimeScope lifetimeScope = workContextScope.Resolve <ILifetimeScope>();
                    registration = GetRegistration(lifetimeScope, constructorString);
                }
            }
            else
            {
                ILifetimeScope lifetimeScope = workContext.Resolve <ILifetimeScope>();
                registration = GetRegistration(lifetimeScope, constructorString);
            }

            if (registration == null)
            {
                throw new InvalidOperationException();
            }

            if (!registration.Activator.LimitType.IsClass)
            {
                throw new InvalidOperationException();
            }

            return(CreateServiceHost(workContextAccessor, registration, registration.Activator.LimitType, baseAddresses));
        }
Exemple #3
0
        private void DoWork(object group)
        {
            // DoWork is not re-entrant as Timer will not call the callback until the previous callback has returned.
            // This way if a tasks takes longer than the period itself, DoWork is not called while it's still running.
            ShellContext shellContext = _orchardHost.GetShellContext(_shellSettings);

            var groupName = group as string ?? "";

            foreach (var task in _tasks[groupName])
            {
                var taskName = task.GetType().FullName;

                using (var scope = shellContext.CreateServiceScope())
                {
                    try
                    {
                        lock (_states)
                        {
                            _states[task] = BackgroundTaskState.Running;
                        }

                        if (Logger.IsEnabled(LogLevel.Information))
                        {
                            Logger.LogInformation("Start processing background task \"{0}\".", taskName);
                        }

                        task.DoWork(scope.ServiceProvider, _applicationLifetime.ApplicationStopping);

                        if (Logger.IsEnabled(LogLevel.Information))
                        {
                            Logger.LogInformation("Finished processing background task \"{0}\".", taskName);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (Logger.IsEnabled(LogLevel.Error))
                        {
                            Logger.LogError($"Error while processing background task \"{taskName}\": {ex.Message}");
                        }
                    }
                    finally
                    {
                        lock (_states)
                        {
                            _states[task] = BackgroundTaskState.Idle;
                        }
                    }
                }
            }
        }
Exemple #4
0
        public async Task Invoke(HttpContext httpContext)
        {
            // Ensure all ShellContext are loaded and available.
            _orchardHost.Initialize();

            var shellSetting = _runningShellTable.Match(httpContext);

            // Register the shell settings as a custom feature.
            httpContext.Features[typeof(ShellSettings)] = shellSetting;

            // We only serve the next request if the tenant has been resolved.
            if (shellSetting != null)
            {
                ShellContext shellContext = _orchardHost.GetShellContext(shellSetting);

                using (var scope = shellContext.CreateServiceScope())
                {
                    httpContext.RequestServices = scope.ServiceProvider;

                    if (!shellContext.IsActivated)
                    {
                        lock (shellSetting)
                        {
                            // The tenant gets activated here
                            if (!shellContext.IsActivated)
                            {
                                var eventBus = scope.ServiceProvider.GetService <IEventBus>();
                                eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatingAsync()).Wait();
                                eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatedAsync()).Wait();

                                shellContext.IsActivated = true;
                            }
                        }
                    }

                    await _next.Invoke(httpContext);
                }

                using (var scope = shellContext.CreateServiceScope())
                {
                    var deferredTaskEngine = scope.ServiceProvider.GetService <IDeferredTaskEngine>();

                    if (deferredTaskEngine != null && deferredTaskEngine.HasPendingTasks)
                    {
                        var context = new DeferredTaskContext(scope.ServiceProvider);
                        await deferredTaskEngine.ExecuteTasksAsync(context);
                    }
                }
            }
        }
Exemple #5
0
        public async Task Invoke(HttpContext httpContext)
        {
            var sw = Stopwatch.StartNew();

            // Ensure all ShellContext are loaded and available.
            _orchardHost.Initialize();

            var shellSetting = _runningShellTable.Match(httpContext);

            if (shellSetting != null)
            {
                ShellContext shellContext = _orchardHost.GetShellContext(shellSetting);
                httpContext.Items["ShellSettings"] = shellSetting;
                httpContext.ApplicationServices    = shellContext.ServiceProvider;

                var scope = shellContext.ServiceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope();

                using (scope)
                {
                    httpContext.RequestServices = scope.ServiceProvider;

                    if (!shellContext.IsActived)
                    {
                        var eventBus = scope.ServiceProvider.GetService <IEventBus>();
                        await eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatingAsync());

                        await eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatedAsync());

                        shellContext.IsActived = true;
                    }

                    await _next.Invoke(httpContext);
                }
            }
            else
            {
                _logger.LogError("Tenant not found");
                throw new Exception("Tenant not found");
            }
            _logger.LogVerbose("Request took {0}ms", sw.ElapsedMilliseconds);
        }
        private bool CallOnDefaultShell(Action <ICacheFileService> cacheFileServiceCall)
        {
            var shellContext = _orchardHost.GetShellContext(new ShellSettings {
                Name = ShellSettings.DefaultName
            });

            if (shellContext == null)
            {
                throw new InvalidOperationException("The Default tenant's shell context does not exist. This most possibly indicates that the shell is not running. Combinator resource sharing needs the Default tenant to run.");
            }
            using (var wc = shellContext.LifetimeScope.Resolve <IWorkContextAccessor>().CreateWorkContextScope())
            {
                ICacheFileService cacheFileService;
                if (!wc.TryResolve <ICacheFileService>(out cacheFileService))
                {
                    return(false);
                }
                cacheFileServiceCall(cacheFileService);
                return(true);
            }
        }
        public async Task Invoke(HttpContext httpContext)
        {
            // Ensure all ShellContext are loaded and available.
            _orchardHost.Initialize();

            var shellSetting = _runningShellTable.Match(httpContext);

            // We only serve the next request if the tenant has been resolved.
            if (shellSetting != null)
            {
                ShellContext shellContext = _orchardHost.GetShellContext(shellSetting);
                httpContext.ApplicationServices = shellContext.ServiceProvider;

                var scope = shellContext.ServiceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope();

                using (scope)
                {
                    httpContext.RequestServices = scope.ServiceProvider;

                    if (!shellContext.IsActived)
                    {
                        IEventBus eventBus = null;
                        lock (shellSetting)
                        {
                            // The tenant gets activated here
                            if (!shellContext.IsActived)
                            {
                                eventBus = scope.ServiceProvider.GetService <IEventBus>();
                            }
                            eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatingAsync()).Wait();
                            eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatedAsync()).Wait();

                            shellContext.IsActived = true;
                        }
                    }

                    await _next.Invoke(httpContext);
                }
            }
        }
        public IEnumerable <NotifyEntry> GetNotifications()
        {
            var listofcontentitems = _orchardServices.ContentManager.Query <MaintenancePart>(VersionOptions.Published).List();

            foreach (var y in listofcontentitems)
            {
                yield return(new NotifyEntry {
                    Message = T(y.As <MaintenancePart>().MaintenanceNotify), Type = y.As <MaintenancePart>().MaintenanceNotifyType
                });
            }

            //// Fetching the shell settings for a tenant. This is more efficient if you have many tenants with the Lombiq Hosting Suite,
            //// see below.
            string currentTenant = _shellSettings.Name;

            if (currentTenant.ToLower() != "default")
            {
                var tenantShellSettings = _shellSettingsManager.LoadSettings().Where(settings => settings.Name == "Default").Single();
                var shellContext        = _orchardHost.GetShellContext(tenantShellSettings);
                if (shellContext != null)
                {
                    using (var wc = shellContext.LifetimeScope.Resolve <IWorkContextAccessor>().CreateWorkContextScope()) {
                        //     var tenantSiteName = wc.Resolve<ISiteService>().GetSiteSettings().SiteName;
                        List <MaintenanceVM> ListMaintenanceVM = new List <MaintenanceVM>();
                        try {
                            ListMaintenanceVM = wc.Resolve <IMaintenanceService>().Get().Where(y => y.Selected_TenantVM.Contains(currentTenant)).ToList();
                        } catch {
                            // non so a priori se il master (default tenant) ha il modulo maintenance enabled
                        }
                        foreach (var y in ListMaintenanceVM)
                        {
                            yield return(new NotifyEntry {
                                Message = T(y.MaintenanceNotify), Type = y.MaintenanceNotifyType
                            });
                        }
                    }
                }
            }
        }