Ejemplo n.º 1
0
        public async Task <ICommandResult <TenantSetUpContext> > InstallAsync(TenantSetUpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var result = new CommandResult <TenantSetUpContext>();

            try
            {
                // Validate tenant

                var shells = _shellSettingsManager.LoadSettings();
                if (shells != null)
                {
                    // Ensure a unique shell name
                    var shell = shells.FirstOrDefault(s => s.Name.Equals(context.SiteName, StringComparison.OrdinalIgnoreCase));
                    if (shell != null)
                    {
                        return(result.Failed($"A tenant with the name \"{shell.Name}\" already exists! Consider renaming the tenant."));
                    }

                    // Ensure a unique shell location
                    shell = shells.FirstOrDefault(s => s.Location.Equals(context.SiteName.ToSafeFileName(), StringComparison.OrdinalIgnoreCase));
                    if (shell != null)
                    {
                        return(result.Failed($"A tenant with the same location \"{shell.Location}\" already exists! Consider renaming the tenant."));
                    }

                    // Ensure a unique connection string & table prefix
                    shell = shells.FirstOrDefault(s =>
                                                  s.ConnectionString.Equals(context.DatabaseConnectionString, StringComparison.OrdinalIgnoreCase) &&
                                                  s.TablePrefix.Equals(context.DatabaseTablePrefix, StringComparison.OrdinalIgnoreCase));
                    if (shell != null)
                    {
                        return(result.Failed($"A tenant with the same connection string and table prefix already exists! Tenant name: \"{shell.Name}\"."));
                    }
                }

                // Install tenant

                return(await InstallInternalAsync(context));
            }
            catch (Exception ex)
            {
                return(result.Failed(ex.Message));
            }
        }
Ejemplo n.º 2
0
        public override async Task <IDisplayResult> EditAsync(OpenIdValidationSettings settings, BuildEditorContext context)
        {
            var user = _httpContextAccessor.HttpContext?.User;

            if (user == null || !await _authorizationService.AuthorizeAsync(user, Permissions.ManageValidationSettings))
            {
                return(null);
            }

            return(Initialize <OpenIdValidationSettingsViewModel>("OpenIdValidationSettings_Edit", async model =>
            {
                model.Authority = settings.Authority;
                model.Audience = settings.Audience;
                model.Tenant = settings.Tenant;

                var availableTenants = new List <string>();
                var tenants = _shellSettingsManager.LoadSettings().Where(s => s.State == TenantState.Running);

                foreach (var shellContext in await _shellHost.ListShellContextsAsync())
                {
                    using (var scope = shellContext.CreateScope())
                    {
                        var descriptor = scope.ServiceProvider.GetRequiredService <ShellDescriptor>();
                        if (descriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server))
                        {
                            availableTenants.Add(shellContext.Settings.Name);
                        }
                    }
                }

                model.AvailableTenants = availableTenants;
            }).Location("Content:2").OnGroup(SettingsGroupId));
        }
Ejemplo n.º 3
0
        private void CreateAndActivateShells()
        {
            Logger.Info("Start creation of shells");

            var allSettings = shellSettingsManager.LoadSettings().ToArray();

            // load all tenants, and activate their shell
            if (allSettings.Any())
            {
                foreach (var settings in allSettings)
                {
                    try
                    {
                        var context = CreateShellContext(settings);
                        ActivateShell(context);
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat(e, "A tenant could not be started: " + settings.Name);
#if DEBUG
                        throw;
#endif
                    }
                }
            }

            Logger.Info("Done creating shells");
        }
Ejemplo n.º 4
0
        private void CreateAndActivateShells()
        {
            Logger.Information("开始创建外壳上下文。");

            var allSettings = _shellSettingsManager
                              .LoadSettings()
                              .Where(settings => settings.State == TenantState.Running || settings.State == TenantState.Uninitialized)
                              .ToArray();

            if (allSettings.Any())
            {
                Parallel.ForEach(allSettings, settings =>
                {
                    try
                    {
                        var context = CreateShellContext(settings);
                        ActivateShell(context);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "一个租户无法被启动: " + settings.Name);
#if DEBUG
                        throw;
#endif
                    }
                });
            }

            Logger.Information("完成外壳创建");
        }
Ejemplo n.º 5
0
        private void CreateAndActivateShells()
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Start creation of shells");
            }

            // Is there any tenant right now?
            var allSettings = _shellSettingsManager
                              .LoadSettings()
                              .Where(CanCreateShell).ToArray();

            // Load all tenants, and activate their shell.
            if (allSettings.Any())
            {
                //Parallel.ForEach(allSettings, settings =>
                //{
                foreach (var settings in allSettings)
                {
                    GetOrCreateShellContext(settings);
                }
                //});
            }
            else
            {
                // No settings, run the Setup.
                var setupContext = CreateSetupContext();
                ActivateShell(setupContext);
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done creating shells");
            }
        }
Ejemplo n.º 6
0
        void CreateAndActivateShells()
        {
            Logger.Information("Start creation of shells");

            // is there any tenant right now ?
            var allSettings = _shellSettingsManager.LoadSettings().ToArray();

            // load all tenants, and activate their shell
            if (allSettings.Any())
            {
                foreach (var settings in allSettings)
                {
                    try {
                        var context = CreateShellContext(settings);
                        ActivateShell(context);
                    }
                    catch (Exception e) {
                        Logger.Error(e, "A tenant could not be started: " + settings.Name);
                    }
                }
            }
            // no settings, run the Setup
            else
            {
                var setupContext = CreateSetupContext();
                ActivateShell(setupContext);
            }

            Logger.Information("Done creating shells");
        }
        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);
        }
Ejemplo n.º 8
0
        void CreateAndActivateShells()
        {
            _logger.LogInformation("Start creation of shells");

            // Is there any tenant right now?
            var allSettings = _shellSettingsManager.LoadSettings()
                              .Where(settings => settings.State == TenantState.Running || settings.State == TenantState.Uninitialized || settings.State == TenantState.Initializing)
                              .ToArray();

            // Load all tenants, and activate their shell.
            if (allSettings.Any())
            {
                Parallel.ForEach(allSettings, settings => {
                    try {
                        var context = CreateShellContext(settings);
                        ActivateShell(context);
                    }
                    catch (Exception ex) {
                        if (ex.IsFatal())
                        {
                            throw;
                        }
                        _logger.LogError(string.Format("A tenant could not be started: {0}", settings.Name), ex);
                    }
                });
            }
            // No settings, run the Setup.
            else
            {
                var setupContext = CreateSetupContext();
                ActivateShell(setupContext);
            }

            _logger.LogInformation("Done creating shells");
        }
Ejemplo n.º 9
0
        public override Task <IViewProviderResult> BuildIndexAsync(ShellSettings role, IViewProviderContext context)
        {
            var viewModel = context.Controller.HttpContext.Items[typeof(TenantIndexViewModel)] as TenantIndexViewModel;

            if (viewModel == null)
            {
                throw new Exception($"A view model of type {typeof(TenantIndexViewModel).ToString()} has not been registered on the HttpContext!");
            }

            viewModel.Results = _shellSettingsManager.LoadSettings();

            return(Task.FromResult(Views(
                                       View <TenantIndexViewModel>("Admin.Index.Header", model => viewModel).Zone("header"),
                                       View <TenantIndexViewModel>("Admin.Index.Tools", model => viewModel).Zone("header-right"),
                                       View <TenantIndexViewModel>("Admin.Index.Content", model => viewModel).Zone("content")
                                       )));
        }
 private TenantEditorViewModel BuildEditorViewModel(TenantPart part)
 {
     return(new TenantEditorViewModel
     {
         TenantPart = part,
         TenantSettings = _shellSettingsManager.LoadSettings()
     });
 }
Ejemplo n.º 11
0
        async Task CreateAndRegisterShellsAsync()
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Start creation of shells");
            }

            // Load all extensions and features so that the controllers are
            // registered in ITypeFeatureProvider and their areas defined in the application
            // conventions.
            _extensionManager
            .GetExtensions()
            .Features
            .InvokeAsync(
                f => _extensionManager.LoadFeatureAsync(f), _logger)
            .Wait();

            // Is there any tenant right now?
            var allSettings = _shellSettingsManager.LoadSettings().Where(CanCreateShell).ToArray();

            // Load all tenants, and activate their shell.
            if (allSettings.Any())
            {
                Parallel.ForEach(allSettings, settings =>
                {
                    try
                    {
                        GetOrCreateShellContext(settings);
                    }
                    catch (Exception ex)
                    {
                        if (ex.IsFatal())
                        {
                            throw;
                        }

                        _logger.LogError(string.Format("A tenant could not be started: {0}", settings.Name), ex);
                    }
                });
            }

            // No settings, run the Setup.
            else
            {
                var setupContext = await CreateSetupContextAsync();

                RegisterShell(setupContext);
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done creating shells");
            }
        }
Ejemplo n.º 12
0
        // ----------------

        ShellSettings GetShell(string name)
        {
            var shell = _shellSettingsManager.LoadSettings()?
                        .First(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            if (shell == null)
            {
                throw new Exception($"Could not locate a shell with the name {name}.");
            }
            return(shell);
        }
        private ShellSettings GetSettings(string requestHost)
        {
            var shellSettings = _shellSettingsManager.LoadSettings();

            if (!shellSettings.Any())
            {
                return(ShellHelper.BuildDefaultUninitializedShell);
            }

            return(shellSettings
                   .SingleOrDefault(x => x.RequestUrlHost == requestHost));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Create(string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
            {
                return(Unauthorized());
            }

            var model = new CreateOpenIdScopeViewModel();

            foreach (var tenant in _shellSettingsManager.LoadSettings())
            {
                model.Tenants.Add(new CreateOpenIdScopeViewModel.TenantEntry
                {
                    Current = string.Equals(tenant.Name, _shellSettings.Name, StringComparison.Ordinal),
                    Name    = tenant.Name
                });
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Ejemplo n.º 15
0
        void CreateAndActivateShells()
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Start creation of shells");
            }

            // Load all extensions and features so that the controllers are
            // registered in ITypeFeatureProvider and their areas definedin the application
            // conventions.
            _extensionManager.LoadFeatures(_extensionManager.AvailableFeatures());

            // Is there any tenant right now?
            var allSettings = _shellSettingsManager.LoadSettings()
                              .Where(settings =>
                                     settings.State == TenantState.Running ||
                                     settings.State == TenantState.Uninitialized ||
                                     settings.State == TenantState.Initializing)
                              .ToArray();

            // Load all tenants, and activate their shell.
            if (allSettings.Any())
            {
                Parallel.ForEach(allSettings, settings =>
                {
                    try
                    {
                        var context = CreateShellContext(settings);
                        ActivateShell(context);
                    }
                    catch (Exception ex)
                    {
                        if (ex.IsFatal())
                        {
                            throw;
                        }

                        _logger.LogError(string.Format("A tenant could not be started: {0}", settings.Name), ex);
                    }
                });
            }
            // No settings, run the Setup.
            else
            {
                var setupContext = CreateSetupContext();
                ActivateShell(setupContext);
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done creating shells");
            }
        }
Ejemplo n.º 16
0
        async Task PreCreateAndRegisterShellsAsync()
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Start creation of shells");
            }

            // Load all extensions and features so that the controllers are
            // registered in ITypeFeatureProvider and their areas defined in the application
            // conventions.
            var features = _extensionManager.LoadFeaturesAsync();

            // Is there any tenant right now?
            var allSettings     = _shellSettingsManager.LoadSettings().Where(CanCreateShell).ToArray();
            var defaultSettings = allSettings.FirstOrDefault(s => s.Name == ShellHelper.DefaultShellName);
            var otherSettings   = allSettings.Except(new[] { defaultSettings }).ToArray();

            features.Wait();

            // The 'Default' tenant is not running, run the Setup.
            if (defaultSettings?.State != TenantState.Running)
            {
                var setupContext = await CreateSetupContextAsync(defaultSettings);

                AddAndRegisterShell(setupContext);
                allSettings = otherSettings;
            }

            if (allSettings.Length > 0)
            {
                // Pre-create and register all tenant shells.
                foreach (var settings in allSettings)
                {
                    if (settings.Name == ShellHelper.DefaultShellName)
                    {
                        await GetOrCreateShellContextAsync(settings);

                        continue;
                    }

                    AddAndRegisterShell(new ShellContext.PlaceHolder {
                        Settings = settings
                    });
                }
                ;
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done pre-creating and registering shells");
            }
        }
Ejemplo n.º 17
0
        private ShellSettings GetSettings(string requestHost)
        {
            var shellSettings = _shellSettingsManager.LoadSettings();

            if (!shellSettings.Any())
            {
                return(new ShellSettings {
                    Name = ShellSettings.DefaultName, State = TenantState.Uninitialized
                });
            }

            return(shellSettings
                   .SingleOrDefault(x => x.RequestUrlHost == requestHost));
        }
Ejemplo n.º 18
0
        async Task CreateAndRegisterShellsAsync()
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Start creation of shells");
            }

            // Load all extensions and features so that the controllers are
            // registered in ITypeFeatureProvider and their areas defined in the application
            // conventions.
            var features = _extensionManager.LoadFeaturesAsync();

            // Is there any tenant right now?
            var allSettings = _shellSettingsManager.LoadSettings().Where(CanCreateShell).ToArray();

            features.Wait();

            // No settings, run the Setup.
            if (allSettings.Length == 0)
            {
                var setupContext = await CreateSetupContextAsync();

                AddAndRegisterShell(setupContext);
            }
            else
            {
                // Load all tenants, and activate their shell.
                await Task.WhenAll(allSettings.Select(async settings =>
                {
                    try
                    {
                        await GetOrCreateShellContextAsync(settings);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "A tenant could not be started '{TenantName}'", settings.Name);

                        if (ex.IsFatal())
                        {
                            throw;
                        }
                    }
                }));
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done creating shells");
            }
        }
Ejemplo n.º 19
0
        public void SingleSettingsFileShouldComeBackAsExpected()
        {
            ShellSettingsManager.SaveSettings(new ShellSettings {
                Name = "Default", DataProvider = "SQLCe", DataConnectionString = "something else"
            });

            var settings = ShellSettingsManager.LoadSettings().Single();

            Assert.That(settings, Is.Not.Null);
            Assert.That(settings.Name, Is.EqualTo("Default"));
            Assert.That(settings.DataProvider, Is.EqualTo("SQLCe"));
            Assert.That(settings.DataConnectionString, Is.EqualTo("something else"));
        }
Ejemplo n.º 20
0
        public override async Task <IDisplayResult> EditAsync(OpenIdValidationSettings settings, BuildEditorContext context)
        {
            var user = _httpContextAccessor.HttpContext?.User;

            if (user == null || !await _authorizationService.AuthorizeAsync(user, Permissions.ManageValidationSettings))
            {
                return(null);
            }

            return(Initialize <OpenIdValidationSettingsViewModel>("OpenIdValidationSettings_Edit", model =>
            {
                model.Authority = settings.Authority;
                model.Audience = settings.Audience;
                model.Tenant = settings.Tenant;

                model.AvailableTenants = (from tenant in _shellSettingsManager.LoadSettings().AsParallel()
                                          let provider = _shellHost.GetOrCreateShellContext(tenant).ServiceProvider
                                                         let descriptor = provider.GetRequiredService <ShellDescriptor>()
                                                                          where descriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server)
                                                                          select tenant.Name).ToList();
            }).Location("Content:2").OnGroup(SettingsGroupId));
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var currentApplicationServices = httpContext.ApplicationServices;
            var currentRequestServices     = httpContext.RequestServices;

            var shellSettings = _shellSettingsManager.LoadSettings();
            var shellSetting  = shellSettings.SingleOrDefault(x => x.RequestUrlPrefix == httpContext.Request.Host.Value);

            if (shellSetting != null)
            {
                using (var shell = _shellContextFactory.CreateShellContext(shellSetting)) {
                    httpContext.RequestServices = shell.LifetimeScope;

                    shell.Shell.Activate();
                    await _next.Invoke(httpContext);
                }
            }
            else
            {
                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
                            });
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        private ShellContext CreateStandaloneEnvironment(string tenant)
        {
            // Retrieve settings for speficified tenant.
            var settingsList = _shellSettingsManager.LoadSettings();

            if (settingsList.Any())
            {
                var settings = settingsList.SingleOrDefault(s => string.Equals(s.Name, tenant, StringComparison.OrdinalIgnoreCase));
                if (settings == null)
                {
                    throw new OrchardCoreException(T("Tenant {0} does not exist", tenant));
                }

                return(_orchardHost.CreateShellContext(settings));
            }
            else
            {
                // In case of an uninitialized site (no default settings yet), we create a default settings instance.
                var settings = new ShellSettings {
                    Name = ShellHelper.DefaultShellName, State = TenantState.Uninitialized
                };
                return(_orchardHost.CreateShellContext(settings));
            }
        }
 public List <string> GetAllTenantName()
 {
     return(_shellSettingsManager.LoadSettings().Select(x => x.Name).ToList());
 }
 protected void LazyLoadHandlers(TenantPart part)
 {
     part.ShellSettingsField.Loader(() => string.IsNullOrWhiteSpace(part.Name)
         ? null
         : _shellSettingsManager.LoadSettings().Where(settings => settings.Name == part.Name).FirstOrDefault());
 }
 public IEnumerable <ShellSettings> GetTenants()
 {
     return(_shellSettingsManager.LoadSettings());
 }