public ActionResult Edit([Bind(Include = "TenantId,Code,Name,Description,Culture,TimeZone,Created,Status")] EditTenantViewModel tenantViewModel) { try { using (var ctx = new SaasDbContext()) { // Get existing tenant from db var tenant = ctx.Tenants.Where(t => t.TenantId == tenantViewModel.TenantId).FirstOrDefault(); tenant.Code = tenantViewModel.Code; tenant.Name = tenantViewModel.Name; tenant.Description = tenantViewModel.Description; tenant.Culture = tenantViewModel.Culture; tenant.TimeZone = tenantViewModel.TimeZone; tenant.Status = tenantViewModel.Status; if (ModelState.IsValid) { ctx.Entry(tenant).State = EntityState.Modified; ctx.SaveChanges(); return(RedirectToAction("Index")); } } } catch (Exception ex) { LogService.Info("Tenants not found", ex.Message, ex.InnerException); } return(View(tenantViewModel)); }
public async Task TenantValidationFailsIfInvalidConfigurationsWasProvided(string name, string urlPrefix, string hostName, string featureProfile, string[] errorMessages) { // Arrange var tenantValidator = CreateTenantValidator(defaultTenant: false); // Act & Assert var viewModel = new EditTenantViewModel { Name = name, RequestUrlPrefix = urlPrefix, RequestUrlHost = hostName, FeatureProfile = featureProfile, IsNewTenant = true }; var errors = await tenantValidator.ValidateAsync(viewModel); // Assert Assert.Equal(errorMessages.Length, errors.Count()); for (var i = 0; i < errors.Count(); i++) { Assert.Equal(errorMessages[i], errors.ElementAt(i).Message); } }
public async Task <IActionResult> CreatePost(EditTenantViewModel model) { // Ensure we have permission if (!await _authorizationService.AuthorizeAsync(User, Permissions.AddTenants)) { return(Unauthorized()); } // Ensure host if (!_shellSettings.IsDefaultShell()) { return(Unauthorized()); } // Execute view provider var result = await _viewProvider.ProvideUpdateAsync(new ShellSettings(), this); // Errors occurred in the view provider if (!ModelState.IsValid) { return(await Create()); } // Success _alerter.Success(T["Tenant Created Successfully!"]); return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); var model = new EditTenantViewModel { Recipes = recipes, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, DatabaseProvider = shellSettings["DatabaseProvider"], TablePrefix = shellSettings["TablePrefix"], ConnectionString = shellSettings["ConnectionString"], RecipeName = shellSettings["RecipeName"] }; model.Recipes = recipes; return(View(model)); }
public async Task <IActionResult> Edit(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } if (ModelState.IsValid) { ValidateViewModel(model, false); } var shellContext = GetShells() .Where(x => String.Equals(x.Settings.Name, model.Name, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellContext == null) { return(NotFound()); } var shellSettings = shellContext.Settings; if (ModelState.IsValid) { shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.RequestUrlHost = model.RequestUrlHost; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { shellSettings.DatabaseProvider = model.DatabaseProvider; shellSettings.TablePrefix = model.TablePrefix; shellSettings.ConnectionString = model.ConnectionString; } _orchardHost.UpdateShellSettings(shellSettings); return(RedirectToAction(nameof(Index))); } // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { model.DatabaseProvider = shellSettings.DatabaseProvider; model.TablePrefix = shellSettings.TablePrefix; model.ConnectionString = shellSettings.ConnectionString; model.CanSetDatabasePresets = true; } // If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// 修改 /// </summary> /// <param name="Id"></param> /// <returns></returns> public async Task <PartialViewResult> EditModal(int?Id) { var tenantDto = await _tenantAppService.GetForEditAsync(new NullableIdDto(Id)); var viewModel = new EditTenantViewModel(tenantDto); return(PartialView("_EditModal", viewModel)); }
private EditTenantViewModel GetModel(ShellSettings settings) { // Configure defaults string userName = "******", email = "*****@*****.**", password = "******"; // Build view model EditTenantViewModel viewModel = null; if (string.IsNullOrEmpty(settings.Name)) { viewModel = new EditTenantViewModel() { ConnectionString = _defaultTenantSettings.ConnectionString, TablePrefix = _defaultTenantSettings.TablePrefix, UserName = userName, Email = email, Password = password, PasswordConfirmation = password, SmtpSettings = new SmtpSettings() { DefaultFrom = _defaultTenantSettings.SmtpSettings.DefaultFrom, Host = _defaultTenantSettings.SmtpSettings.Host, Port = _defaultTenantSettings.SmtpSettings.Port, UserName = _defaultTenantSettings.SmtpSettings.UserName, Password = _defaultTenantSettings.SmtpSettings.Password, RequireCredentials = _defaultTenantSettings.SmtpSettings.RequireCredentials, EnableSsl = _defaultTenantSettings.SmtpSettings.EnableSsl }, IsNewTenant = true }; } else { viewModel = new EditTenantViewModel() { SiteName = settings.Name, Location = settings.Location, ConnectionString = settings.ConnectionString, TablePrefix = settings.TablePrefix, RequestedUrlHost = settings.RequestedUrlHost, RequestedUrlPrefix = settings.RequestedUrlPrefix, UserName = userName, Email = email, Password = password, PasswordConfirmation = password, State = settings.State, OwnerId = settings.OwnerId, CreatedDate = settings.CreatedDate, ModifiedDate = settings.ModifiedDate, AvailableTenantStates = GetAvailableTenantStates() }; } return(viewModel); }
private async Task ValidateViewModel(EditTenantViewModel model, bool newTenant) { var selectedProvider = _databaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(EditTenantViewModel.ConnectionString), S["The connection string is mandatory for this provider."]); } if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["The tenant name is mandatory."]); } if (!String.IsNullOrWhiteSpace(model.FeatureProfile)) { var featureProfiles = await _featureProfilesService.GetFeatureProfilesAsync(); if (!featureProfiles.ContainsKey(model.FeatureProfile)) { ModelState.AddModelError(nameof(EditTenantViewModel.FeatureProfile), S["The feature profile does not exist.", model.FeatureProfile]); } } var allSettings = _shellHost.GetAllSettings(); if (newTenant && allSettings.Any(tenant => String.Equals(tenant.Name, model.Name, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["A tenant with the same name already exists.", model.Name]); } if (!String.IsNullOrEmpty(model.Name) && !Regex.IsMatch(model.Name, @"^\w+$")) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["Invalid tenant name. Must contain characters only and no spaces."]); } if (!IsDefaultShell() && String.IsNullOrWhiteSpace(model.RequestUrlHost) && String.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["Host and url prefix can not be empty at the same time."]); } var allOtherShells = allSettings.Where(tenant => !string.Equals(tenant.Name, model.Name, StringComparison.OrdinalIgnoreCase)); if (allOtherShells.Any(tenant => String.Equals(tenant.RequestUrlPrefix, model.RequestUrlPrefix?.Trim(), StringComparison.OrdinalIgnoreCase) && String.Equals(tenant.RequestUrlHost, model.RequestUrlHost, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["A tenant with the same host and prefix already exists.", model.Name]); } if (!String.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { if (model.RequestUrlPrefix.Contains('/')) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["The url prefix can not contain more than one segment."]); } } }
public async Task <PartialViewResult> EditModal(int id) { var tenantEditDto = await _tenantAppService.GetTenantForEdit(new EntityRequestInput(id)); var editionItems = await _editionAppService.GetEditionComboboxItems(tenantEditDto.EditionId); var viewModel = new EditTenantViewModel(tenantEditDto, editionItems); return(PartialView("_EditModal", viewModel)); }
public async Task <IActionResult> Edit(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Forbid()); } if (!_currentShellSettings.IsDefaultShell()) { return(Forbid()); } var shellSettings = _shellHost.GetAllSettings() .Where(x => String.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return(NotFound()); } var currentFeatureProfile = shellSettings["FeatureProfile"]; var featureProfiles = await GetFeatureProfilesAsync(currentFeatureProfile); var model = new EditTenantViewModel { Category = shellSettings["Category"], Description = shellSettings["Description"], Name = shellSettings.Name, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, FeatureProfile = currentFeatureProfile, FeatureProfiles = featureProfiles }; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).OrderBy(r => r.DisplayName).ToArray(); model.Recipes = recipes; model.DatabaseProvider = shellSettings["DatabaseProvider"]; model.TablePrefix = shellSettings["TablePrefix"]; model.ConnectionString = shellSettings["ConnectionString"]; model.RecipeName = shellSettings["RecipeName"]; model.CanEditDatabasePresets = true; SetConfigurationShellValues(model); } return(View(model)); }
public async Task <IActionResult> Create(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Forbid()); } if (!_currentShellSettings.IsDefaultShell()) { return(Forbid()); } if (ModelState.IsValid) { await ValidateViewModelAsync(model, true); } if (ModelState.IsValid) { // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); shellSettings.Name = model.Name; shellSettings.RequestUrlHost = model.RequestUrlHost; shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.State = TenantState.Uninitialized; SetConfigurationShellValues(model); shellSettings["Category"] = model.Category; shellSettings["Description"] = model.Description; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["Secret"] = Guid.NewGuid().ToString(); shellSettings["RecipeName"] = model.RecipeName; shellSettings["FeatureProfile"] = model.FeatureProfile; await _shellHost.UpdateShellSettingsAsync(shellSettings); return(RedirectToAction(nameof(Index))); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).OrderBy(r => r.DisplayName).ToArray(); model.Recipes = recipes; model.FeatureProfiles = await GetFeatureProfilesAsync(model.FeatureProfile); // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Edit(Guid id) { var response = Context.Tenants.FirstOrDefault(x => x.Id == id); if (response == null) { return(RedirectToAction(nameof(Index), "Tenant")); } var model = new EditTenantViewModel(response) { CountrySelectListItems = await _organizationService.GetCountrySelectListAsync() }; return(View(model)); }
public async Task <IActionResult> Edit(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } var shellContext = (await GetShellsAsync()) .Where(x => string.Equals(x.Settings.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellContext == null) { return(NotFound()); } var shellSettings = shellContext.Settings; var model = new EditTenantViewModel { Name = shellSettings.Name, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, }; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; model.DatabaseProvider = shellSettings.DatabaseProvider; model.TablePrefix = shellSettings.TablePrefix; model.ConnectionString = shellSettings.ConnectionString; model.RecipeName = shellSettings.RecipeName; model.CanSetDatabasePresets = true; } return(View(model)); }
public async Task <IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } var model = new EditTenantViewModel(); return(View(model)); }
public async Task<IActionResult> Update(Guid id) { EditTenantViewModel editTenantViewModel = null; try { var tenant = await _internalApiClient.GetTenantByGuid(id); editTenantViewModel = _mapper.Map<EditTenantViewModel>(tenant); } catch (BasicWebAppException ex) { ExceptionProcessor.ProcessError(LoggingEvents.UpdateItemFailed, _logger, HttpContext, ex, id); } return View(editTenantViewModel); }
public async Task <IActionResult> Create(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } if (ModelState.IsValid) { await ValidateViewModel(model, true); } if (ModelState.IsValid) { var shellSettings = new ShellSettings { Name = model.Name, RequestUrlPrefix = model.RequestUrlPrefix?.Trim(), RequestUrlHost = model.RequestUrlHost, ConnectionString = model.ConnectionString, TablePrefix = model.TablePrefix, DatabaseProvider = model.DatabaseProvider, State = TenantState.Uninitialized, Secret = Guid.NewGuid().ToString(), RecipeName = model.RecipeName }; _shellSettingsManager.SaveSettings(shellSettings); var shellContext = await _orchardHost.GetOrCreateShellContextAsync(shellSettings); return(RedirectToAction(nameof(Index))); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; // If we got this far, something failed, redisplay form return(View(model)); }
private void SetConfigurationShellValues(EditTenantViewModel model) { var shellSettings = _shellSettingsManager.CreateDefaultSettings(); var configurationShellConnectionString = shellSettings["ConnectionString"]; var configurationDatabaseProvider = shellSettings["DatabaseProvider"]; model.DatabaseConfigurationPreset = !string.IsNullOrEmpty(configurationShellConnectionString) || !string.IsNullOrEmpty(configurationDatabaseProvider); if (!string.IsNullOrEmpty(configurationShellConnectionString)) { model.ConnectionString = configurationShellConnectionString; } if (!string.IsNullOrEmpty(configurationDatabaseProvider)) { model.DatabaseProvider = configurationDatabaseProvider; } }
private void ValidateViewModel(EditTenantViewModel model, bool newTenant) { if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["The tenant name is mandatory."]); } var allShells = GetShells(); if (newTenant && allShells.Any(tenant => String.Equals(tenant.Settings.Name, model.Name, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["A tenant with the same name already exists.", model.Name]); } if (newTenant && allShells.Any(tenant => String.Equals(tenant.Settings.RequestUrlPrefix, model.RequestUrlPrefix, StringComparison.OrdinalIgnoreCase) && String.Equals(tenant.Settings.RequestUrlHost, model.RequestUrlHost, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["A tenant with the same host and prefix already exists.", model.Name]); } if (!String.IsNullOrEmpty(model.Name) && !Regex.IsMatch(model.Name, @"^\w+$")) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["Invalid tenant name. Must contain characters only and no spaces."]); } if (!IsDefaultShell() && string.IsNullOrWhiteSpace(model.RequestUrlHost) && string.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["Host and url prefix can not be empty at the same time."]); } if (!String.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { if (model.RequestUrlPrefix.Contains('/')) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["The url prefix can not contains more than one segment."]); } if (allShells.Any(x => x.Settings.RequestUrlPrefix != null && String.Equals(x.Settings.RequestUrlPrefix.Trim(), model.RequestUrlPrefix.Trim(), StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["The url prefix is already used by another tenant."]); } } }
public async Task <IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Forbid()); } if (!_currentShellSettings.IsDefaultShell()) { return(Forbid()); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).OrderBy(r => r.DisplayName).ToArray(); // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); var currentFeatureProfile = shellSettings["FeatureProfile"]; var featureProfiles = await GetFeatureProfilesAsync(currentFeatureProfile); var model = new EditTenantViewModel { Recipes = recipes, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, TablePrefix = shellSettings["TablePrefix"], RecipeName = shellSettings["RecipeName"], FeatureProfile = currentFeatureProfile, FeatureProfiles = featureProfiles }; SetConfigurationShellValues(model); model.Recipes = recipes; return(View(model)); }
public async Task DuplicateTenantHostOrPrefixShouldFailValidation(bool isNewTenant) { // Arrange var tenantValidator = CreateTenantValidator(); var viewModel = new EditTenantViewModel { Name = "Tenant5", RequestUrlPrefix = "tenant4", RequestUrlHost = "example5.com", FeatureProfile = "Feature Profile", IsNewTenant = isNewTenant }; // Act var errors = await tenantValidator.ValidateAsync(viewModel); // Asserts Assert.Single(errors); Assert.Equal("A tenant with the same host and prefix already exists.", errors.Single().Message); }
public async Task <IActionResult> Edit(EditTenantViewModel model, string callBack = null) { if (!ModelState.IsValid) { return(View(model)); } var dbTenant = _organizationService.GetTenantById(model.Id); var updateModel = model.GetBase(); if (model.OrganizationLogoFormFile != null) { using (var memoryStream = new MemoryStream()) { await model.OrganizationLogoFormFile.CopyToAsync(memoryStream); updateModel.OrganizationLogo = memoryStream.ToArray(); } } else { updateModel.OrganizationLogo = dbTenant.OrganizationLogo; updateModel.MachineName = dbTenant.MachineName; } Context.Tenants.Update(updateModel); var dbResult = await Context.SaveAsync(); if (dbResult.IsSuccess && !string.IsNullOrEmpty(callBack)) { return(Redirect(callBack)); } if (dbResult.IsSuccess) { return(RedirectToAction(nameof(Index), "Tenant")); } ModelState.AppendResultModelErrors(dbResult.Errors); return(View(model)); }
public async Task<IActionResult> Delete(Guid id, EditTenantViewModel editTenantViewModel) { if (!ModelState.IsValid) { _logger.LogWarning(LoggingEvents.DeleteItemBadData, "Delete tenant model is not valid. {ErrorMessages}", ModelState.GetModelStateErrorMessages()); return View(nameof(Update), editTenantViewModel); } try { await _internalApiClient.DeleteTenant(id); return RedirectToAction("index"); } catch (BasicWebAppException ex) { ExceptionProcessor.ProcessError(LoggingEvents.DeleteItemFailed, _logger, HttpContext, ex, id); } return View(nameof(Update), editTenantViewModel); }
public async Task <IActionResult> Create(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } if (ModelState.IsValid) { ValidateViewModel(model, true); } if (ModelState.IsValid) { var shellSettings = new ShellSettings { Name = model.Name, RequestUrlPrefix = model.RequestUrlPrefix, RequestUrlHost = model.RequestUrlHost, ConnectionString = model.ConnectionString, TablePrefix = model.TablePrefix, DatabaseProvider = model.DatabaseProvider, State = TenantState.Uninitialized }; _shellSettingsManager.SaveSettings(shellSettings); var shellContext = _orchardHost.GetOrCreateShellContext(shellSettings); return(RedirectToAction(nameof(Index))); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); var model = new EditTenantViewModel(); model.Recipes = recipes; return(View(model)); }
public async Task<IActionResult> Update(Guid id, EditTenantViewModel editTenantViewModel) { if (!ModelState.IsValid) { _logger.LogWarning(LoggingEvents.UpdateItemBadData, "Edit tenant model is not valid. {ErrorMessages}", ModelState.GetModelStateErrorMessages()); return View(editTenantViewModel); } try { var editTenantContract = _mapper.Map<EditTenantContract>(editTenantViewModel); await _internalApiClient.EditTenant(id, editTenantContract); return RedirectToAction(nameof(Index)); } catch (BasicWebAppException ex) { ExceptionProcessor.ProcessError(LoggingEvents.UpdateItemFailed, _logger, HttpContext, ex, id); } return View(editTenantViewModel); }
public async Task <IActionResult> Edit(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return(Unauthorized()); } if (!IsDefaultShell()) { return(Unauthorized()); } if (ModelState.IsValid) { ValidateViewModel(model, false); } var shellSettings = _shellHost.GetAllSettings() .Where(x => string.Equals(x.Name, model.Name, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return(NotFound()); } if (ModelState.IsValid) { shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.RequestUrlHost = model.RequestUrlHost; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["RecipeName"] = model.RecipeName; shellSettings["Secret"] = Guid.NewGuid().ToString(); } await _shellHost.UpdateShellSettingsAsync(shellSettings); return(RedirectToAction(nameof(Index))); } // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { model.DatabaseProvider = shellSettings["DatabaseProvider"]; model.TablePrefix = shellSettings["TablePrefix"]; model.ConnectionString = shellSettings["ConnectionString"]; model.RecipeName = shellSettings["RecipeName"]; model.CanSetDatabasePresets = true; } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; // If we got this far, something failed, redisplay form return(View(model)); }
private async Task ValidateViewModelAsync(EditTenantViewModel model, bool newTenant) { model.IsNewTenant = newTenant; ModelState.AddModelErrors(await _tenantValidator.ValidateAsync(model)); }
public override async Task <IViewProviderResult> BuildUpdateAsync(ShellSettings settings, IViewProviderContext context) { var model = new EditTenantViewModel(); if (!await context.Updater.TryUpdateModelAsync(model)) { return(await BuildEditAsync(settings, context)); } if (context.Updater.ModelState.IsValid) { // Ensure password if (model.SmtpSettings != null) { if (!string.IsNullOrWhiteSpace(model.SmtpSettings.Password)) { try { model.SmtpSettings.Password = _encrypter.Encrypt(model.SmtpSettings.Password); } catch (Exception e) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError($"There was a problem encrypting the SMTP server password. {e.Message}"); } } } } var setupContext = new TenantSetUpContext() { SiteName = model.SiteName, Location = model.Location, DatabaseProvider = "SqlClient", DatabaseConnectionString = model.ConnectionString, AdminUsername = model.UserName, AdminEmail = model.Email, AdminPassword = model.Password, RequestedUrlHost = model.RequestedUrlHost, RequestedUrlPrefix = model.RequestedUrlPrefix, State = model.State, OwnerId = model.OwnerId, CreatedDate = model.IsNewTenant ? DateTimeOffset.Now : model.CreatedDate, ModifiedDate = model.IsNewTenant ? model.ModifiedDate : DateTimeOffset.Now, EmailSettings = new EmailSettings() { SmtpSettings = model.SmtpSettings }, Errors = new Dictionary <string, string>() }; if (!model.TablePrefixPreset) { setupContext.DatabaseTablePrefix = model.TablePrefix; } // Install or update tenant var result = model.IsNewTenant ? await _tenantSetUpService.InstallAsync(setupContext) : await _tenantSetUpService.UpdateAsync(setupContext); // Report any errors if (!result.Succeeded) { if (_logger.IsEnabled(LogLevel.Information)) { if (model.IsNewTenant) { _logger.LogInformation($"Set-up of tenant '{setupContext.SiteName}' failed with the following errors..."); } else { _logger.LogInformation($"Update of tenant '{setupContext.SiteName}' failed with the following errors..."); } } foreach (var error in result.Errors) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation(error.Code + " " + error.Description); } context.Updater.ModelState.AddModelError(error.Code, error.Description); } } } return(await BuildEditAsync(settings, context)); }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } //Create the model var model = new EditTenantViewModel(); var tenant = new Tenant(); try { using (var ctx = new SaasDbContext()) { tenant = ctx.Tenants.Find(id); } if (tenant == null) { return(HttpNotFound()); } //Add tenant to model model.TenantId = tenant.TenantId; model.Code = tenant.Code; model.Name = tenant.Name; model.Description = tenant.Description; model.Culture = tenant.Culture; model.TimeZone = tenant.TimeZone; model.Created = tenant.Created; model.Status = tenant.Status; // Create the breadcrumb var breadcrumb = new List <BreadcrumbItemViewModel>(); breadcrumb.Add(new BreadcrumbItemViewModel() { Text = "Tenants", Link = "/Tenants" }); breadcrumb.Add(new BreadcrumbItemViewModel() { Text = tenant.Name, Link = "/Tenants/" + tenant.TenantId + "/Details" }); breadcrumb.Add(new BreadcrumbItemViewModel() { Text = "Edit" }); ViewBag.Breadcrumb = breadcrumb; } catch (Exception ex) { LogService.Info("Jobs not found", ex.Message, ex.InnerException); } return(View(model)); }