public void CtorSetContainers() { var expectedContainer1 = new ContainerViewModel<ICloneable>("bar", new ICloneable[0]); var expectedContainer2 = new ContainerViewModel<IFormattable>("baz", new IFormattable[0]); var target = new SetupViewModel("foo", false, false, expectedContainer1, expectedContainer2); Assert.Equal(2, target.Containers.Count()); Assert.Same(expectedContainer1, target.Containers.ElementAt(0)); Assert.Same(expectedContainer2, target.Containers.ElementAt(1)); }
public MainViewModel( IPluginRepository pluginRepository, IAccountSettingsProvider accountSettings, IColumnsSettingsProvider columnsSettings, IApplicationSettingsProvider applicationSettingsProvider, Func<StreamViewModel> createStreamViewModel, Func<SearchViewModel> createSearchViewModel, SetupViewModel setupViewModel) { _pluginRepository = pluginRepository; _accountSettings = accountSettings; _columnsSettings = columnsSettings; _createStreamViewModel = createStreamViewModel; _createSearchViewModel = createSearchViewModel; _setupViewModel = setupViewModel; _applicationSettingsProvider = applicationSettingsProvider; EventAggregator.GetEvent<ShowLink>().Subscribe(HandleShowLink); EventAggregator.GetEvent<ShowProfile>().Subscribe(HandleShowProfile); EventAggregator.GetEvent<ShowConversation>().Subscribe(HandleShowConversation); EventAggregator.GetEvent<ShowSearch>().Subscribe(CreateNewSearch); EventAggregator.GetEvent<ShowContainer>().Subscribe(HandleShowContainer); EventAggregator.GetEvent<MicroblogAdded>().Subscribe(HandleNewMicroblog); EventAggregator.GetEvent<ShowColumns>().Subscribe(HandleNewColumns); ContactService = CompositionManager.Get<IContactService>(); StatusManager = CompositionManager.Get<IStatusUpdateService>(); SelectedMicroblogs = new ThreadSafeObservableCollection<IMicroblog>(); CurrentSearches = new ObservableCollection<ISearchViewModel>(); StreamContainers = new ObservableCollection<IContainerViewModel>(); FilterGroups = new ObservableCollection<StreamModel>(); HiddenPanels = new ObservableCollection<UIElement>(); IsSearchVisible = false; }
private void CopyShellSettingsValues(SetupViewModel model) { if (!String.IsNullOrEmpty(_shellSettings["ConnectionString"])) { model.DatabaseConfigurationPreset = true; model.ConnectionString = _shellSettings["ConnectionString"]; } if (!String.IsNullOrEmpty(_shellSettings["RecipeName"])) { model.RecipeNamePreset = true; model.RecipeName = _shellSettings["RecipeName"]; } if (!String.IsNullOrEmpty(_shellSettings["DatabaseProvider"])) { model.DatabaseConfigurationPreset = true; model.DatabaseProvider = _shellSettings["DatabaseProvider"]; } else { model.DatabaseProvider = model.DatabaseProviders.FirstOrDefault(p => p.IsDefault)?.Value; } }
protected override void OnBindingContextChanged(ViewModel oldViewModel, ViewModel newViewModel) { base.OnBindingContextChanged(oldViewModel, newViewModel); SetupViewModel oldVm = oldViewModel as SetupViewModel; if (oldVm != null) { oldVm.Name.OnValueChanged -= NameValueChanged; oldVm.Job.OnValueChanged -= JobValueChanged; oldVm.ATK.OnValueChanged -= ATKValueChanged; oldVm.State.OnValueChanged -= StateValueChanged; oldVm.SuccessRate.OnValueChanged -= SuccessRateValueChanged; } if (ViewModel != null) { ViewModel.Name.OnValueChanged += NameValueChanged; ViewModel.Job.OnValueChanged += JobValueChanged; ViewModel.ATK.OnValueChanged += ATKValueChanged; ViewModel.State.OnValueChanged += StateValueChanged; ViewModel.SuccessRate.OnValueChanged += SuccessRateValueChanged; } UpdateControls(); }
public ActionResult CitySetup(SetupViewModel model = null, string state = "") { if (model != null) { if (model.State != null) { var CheckForCities = db.Cities.Where(c => c.State == model.State).ToList(); if (CheckForCities.Count() == 0) { model.NoCities = true; } else { model.Cities = CheckForCities; } return(View(model)); } } if (state != null) { var cities = db.Cities.Where(c => c.State == state); if (cities.Count() == 0) { model.NoCities = true; } else { model.Cities = cities.ToList(); } return(View(model)); } else { return(RedirectToAction("Index")); } }
private ActionResult IndexViewResult(SetupViewModel model) { return(View(model)); }
public async Task <ActionResult> IndexPOST(SetupViewModel model) { if (!string.IsNullOrWhiteSpace(_shellSettings["Secret"])) { if (string.IsNullOrEmpty(model.Secret) || !await IsTokenValid(model.Secret)) { _logger.LogWarning("An attempt to access '{TenantName}' without providing a valid secret was made", _shellSettings.Name); return(StatusCode(404)); } } model.DatabaseProviders = _databaseProviders; model.Recipes = await _setupService.GetSetupRecipesAsync(); var selectedProvider = model.DatabaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (!model.DatabaseConfigurationPreset) { if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(model.ConnectionString), T["The connection string is mandatory for this provider."]); } } if (String.IsNullOrEmpty(model.Password)) { ModelState.AddModelError(nameof(model.Password), T["The password is required."]); } if (model.Password != model.PasswordConfirmation) { ModelState.AddModelError(nameof(model.PasswordConfirmation), T["The password confirmation doesn't match the password."]); } RecipeDescriptor selectedRecipe = null; if (!string.IsNullOrEmpty(_shellSettings["RecipeName"])) { selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == _shellSettings["RecipeName"]); if (selectedRecipe == null) { ModelState.AddModelError(nameof(model.RecipeName), T["Invalid recipe."]); } } else if (String.IsNullOrEmpty(model.RecipeName) || (selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == model.RecipeName)) == null) { ModelState.AddModelError(nameof(model.RecipeName), T["Invalid recipe."]); } if (!ModelState.IsValid) { CopyShellSettingsValues(model); return(View(model)); } var setupContext = new SetupContext { ShellSettings = _shellSettings, SiteName = model.SiteName, EnabledFeatures = null, // default list, AdminUsername = model.UserName, AdminEmail = model.Email, AdminPassword = model.Password, Errors = new Dictionary <string, string>(), Recipe = selectedRecipe, SiteTimeZone = model.SiteTimeZone, }; if (!string.IsNullOrEmpty(_shellSettings["ConnectionString"])) { setupContext.DatabaseProvider = _shellSettings["DatabaseProvider"]; setupContext.DatabaseConnectionString = _shellSettings["ConnectionString"]; setupContext.DatabaseTablePrefix = _shellSettings["TablePrefix"]; } else { setupContext.DatabaseProvider = model.DatabaseProvider; setupContext.DatabaseConnectionString = model.ConnectionString; setupContext.DatabaseTablePrefix = model.TablePrefix; } var executionId = await _setupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { foreach (var error in setupContext.Errors) { ModelState.AddModelError(error.Key, error.Value); } return(View(model)); } return(Redirect("~/")); }
public async Task <IActionResult> Setup(SetupViewModel SetupViewModel) { if (ModelState.IsValid) { var validation = _context.Jobs.SingleOrDefault(x => x.Job.ToString() == SetupViewModel.Job && x.ClientId == SetupViewModel.CustomerId); if (validation != null) { ModelState.AddModelError(string.Empty, "This project already exists."); var ClientList = _context.Clients.ToList(); var dropdownClientList = new List <SelectListItem>(); foreach (var clients in ClientList) { dropdownClientList.Add(new SelectListItem { Value = clients.Id.ToString(), Text = clients.Client.ToString() }); } ViewBag.CustomerNameList = dropdownClientList; var BusinessValuesList = _context.BusinessValues.ToList(); var dropdownBusinessValuesList = new List <SelectListItem>(); foreach (var values in BusinessValuesList) { dropdownBusinessValuesList.Add(new SelectListItem { Value = values.Business.ToString(), Text = values.Business.ToString() }); } ViewBag.BusinessValuesList = dropdownBusinessValuesList; return(View()); } else { Jobs jobs = new Jobs(); jobs.Job = SetupViewModel.Job; jobs.ClientId = SetupViewModel.CustomerId; var customer = _context.Clients.Where(x => x.Id == SetupViewModel.CustomerId).ToList(); foreach (var c in customer) { jobs.ClientName = c.Client; } _context.Add(jobs); await _context.SaveChangesAsync(); var project = _context.Jobs.Where(x => x.Job.ToString() == SetupViewModel.Job.ToString() && x.ClientId == SetupViewModel.CustomerId).ToList(); var busval = _context.BusinessValues.Where(x => x.Business.ToString() == SetupViewModel.BusinessValue.ToString()).ToList(); for (int i = 0; i < SetupViewModel.TaskName.Length; i++) { Tasks tasks = new Tasks(); tasks.Task = SetupViewModel.TaskName[i]; foreach (var p in project) { tasks.JobId = p.Id; } foreach (var b in busval) { tasks.BusinessValuesId = b.Id; } _context.Add(tasks); await _context.SaveChangesAsync(); } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } return(View(SetupViewModel)); }
public void CtorSetsIsVerifiable() { var target = new SetupViewModel("foo", true, false); Assert.Equal(true, target.IsVerifiable); }
public async Task <ActionResult> IndexPOST(SetupViewModel model) { model.DatabaseProviders = _databaseProviders; model.Recipes = await _setupService.GetSetupRecipesAsync(); var selectedProvider = model.DatabaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(model.ConnectionString), T["The connection string is mandatory for this provider."]); } if (String.IsNullOrEmpty(model.Password)) { ModelState.AddModelError(nameof(model.Password), T["The password is required."]); } if (model.Password != model.PasswordConfirmation) { ModelState.AddModelError(nameof(model.PasswordConfirmation), T["The password confirmation doesn't match the password."]); } RecipeDescriptor selectedRecipe = null; if (String.IsNullOrEmpty(model.RecipeName) || (selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == model.RecipeName)) == null) { ModelState.AddModelError(nameof(model.RecipeName), T["Invalid recipe."]); } if (!String.IsNullOrEmpty(_shellSettings.ConnectionString)) { model.ConnectionStringPreset = true; model.ConnectionString = _shellSettings.ConnectionString; } if (!String.IsNullOrEmpty(_shellSettings.DatabaseProvider)) { model.DatabaseProviderPreset = true; model.DatabaseProvider = _shellSettings.DatabaseProvider; } if (!String.IsNullOrEmpty(_shellSettings.TablePrefix)) { model.TablePrefixPreset = true; model.TablePrefix = _shellSettings.TablePrefix; } if (!ModelState.IsValid) { return(View(model)); } var setupContext = new SetupContext { SiteName = model.SiteName, EnabledFeatures = null, // default list, AdminUsername = model.AdminUserName, AdminEmail = model.AdminEmail, AdminPassword = model.Password, Errors = new Dictionary <string, string>(), Recipe = selectedRecipe }; if (!model.DatabaseProviderPreset) { setupContext.DatabaseProvider = model.DatabaseProvider; } if (!model.ConnectionStringPreset) { setupContext.DatabaseConnectionString = model.ConnectionString; } if (!model.TablePrefixPreset) { setupContext.DatabaseTablePrefix = model.TablePrefix; } var executionId = await _setupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { foreach (var error in setupContext.Errors) { ModelState.AddModelError(error.Key, error.Value); } return(View(model)); } var urlPrefix = ""; if (!String.IsNullOrWhiteSpace(_shellSettings.RequestUrlPrefix)) { urlPrefix = _shellSettings.RequestUrlPrefix + "/"; } return(Redirect("~/" + urlPrefix)); }
public void CtorSetsIsExpandedAsFalse() { var target = new SetupViewModel("foo", false, false); Assert.False(target.IsExpanded); }
public async Task <ActionResult> Setup(SetupViewModel model) { if (ModelState.IsValid) { // dispose of quickly using (FM_Datastore_Entities_EF db_manager = new FM_Datastore_Entities_EF()) { if (db_manager.Users.Count() != 0) { return(new HttpNotFoundResult()); } } if (TempData.ContainsKey("Setup") && Session["SetupUser"] == null) { return(new HttpNotFoundResult()); } Address address; Division division; using (FM_Datastore_Entities_EF db_manager = new FM_Datastore_Entities_EF()) { address = db_manager.Addresses.Add(model.Address); division = db_manager.Divisions.Add(model.Division); foreach (var item in AppSettings.Roles.ComboBox) { db_manager.Roles.Add(new Role() { Name = item.Value }); } try { db_manager.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } AccountUser user = new AccountUser { UserName = model.Email, Email = model.Email, Address = address.Id, Division = division.Id, TimeZoneOffset = DateTime.UtcNow,// TODO: change to hours of offset CreationDate = DateTime.UtcNow }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // create or add role UserManager.AddToRole(UserManager.FindByEmail(model.Email).Id, AppSettings.Roles.CONGRESS); await SignInAsync(user, false); return(RedirectToAction("Index", "Manage")); // redirect to manage home } AddErrors(result); return(View(model)); } return(Setup()); }
/// <summary> /// Initializes the SetupView class. /// </summary> /// <param name="vm">The vm<see cref="SetupViewModel"/>.</param> private void Initialize(SetupViewModel vm) { Debug.Assert(vm != null); vm.BrowseForFolderRequested += Setup_BrowseForFolderRequested; vm.AcceptChangesRequested += Setup_AcceptChangesRequested; }
public SetupPage() { this.InitializeComponent(); ViewModel = new SetupViewModel(); }
public SetupPage() { InitializeComponent(); BindingContext = viewModel = new SetupViewModel(); }
public Action(UndercarriageContext context, IEquipmentActionRecord actionRecord, SetupViewModel Parameters) { _context = context; Operation = new UpdateUndercarriageSetupAction(_context, actionRecord, Parameters); }
public UpdateUndercarriageSetupAction(System.Data.Entity.DbContext context, IEquipmentActionRecord actionRecord, SetupViewModel Paramteres) : base(context) { Params = Paramteres; Status = ActionStatus.Close; _current = actionRecord; }
public SendInviteCommand(SetupViewModel viewModel) { this.viewModel = viewModel; }
public ActionResult IndexPOST(SetupViewModel model) { var recipes = OrderRecipes(_setupService.Recipes()); //TODO: Couldn't get a custom ValidationAttribute to validate two properties if (!model.DatabaseOptions && string.IsNullOrEmpty(model.DatabaseConnectionString)) { ModelState.AddModelError("DatabaseConnectionString", T("A SQL connection string is required").Text); } if (!String.IsNullOrWhiteSpace(model.ConfirmPassword) && model.AdminPassword != model.ConfirmPassword) { ModelState.AddModelError("ConfirmPassword", T("Password confirmation must match").Text); } if (!model.DatabaseOptions && !String.IsNullOrWhiteSpace(model.DatabaseTablePrefix)) { model.DatabaseTablePrefix = model.DatabaseTablePrefix.Trim(); if (!Char.IsLetter(model.DatabaseTablePrefix[0])) { ModelState.AddModelError("DatabaseTablePrefix", T("The table prefix must begin with a letter").Text); } } if (model.Recipe == null) { if (!(recipes.Select(r => r.Name).Contains(DefaultRecipe))) { ModelState.AddModelError("Recipe", T("No recipes were found in the Setup module").Text); } else { model.Recipe = DefaultRecipe; } } if (!ModelState.IsValid) { model.Recipes = recipes; foreach (var recipe in recipes.Where(recipe => recipe.Name == model.Recipe)) { model.RecipeDescription = recipe.Description; } model.DatabaseIsPreconfigured = !string.IsNullOrEmpty(_setupService.Prime().DataProvider); return(IndexViewResult(model)); } try { string providerName = null; if (model.DatabaseOptions) { providerName = "SqlCe"; } else { switch (model.DatabaseType) { case SetupDatabaseType.SqlServer: providerName = "SqlServer"; break; case SetupDatabaseType.MySQL: providerName = "MySql"; break; default: throw new ApplicationException("Unknown database type: " + model.DatabaseType); } } var setupContext = new SetupContext { SiteName = model.SiteName, AdminUsername = model.AdminUsername, AdminPassword = model.AdminPassword, DatabaseProvider = providerName, DatabaseConnectionString = model.DatabaseConnectionString, DatabaseTablePrefix = model.DatabaseTablePrefix, EnabledFeatures = null, // default list Recipe = model.Recipe }; string executionId = _setupService.Setup(setupContext); // First time installation if finally done. Tell the background views compilation // process to stop, so that it doesn't interfere with the user (asp.net compilation // uses a "single lock" mechanism for compiling views). _viewsBackgroundCompilation.Stop(); // redirect to the welcome page. return(Redirect("~/")); } catch (Exception ex) { Logger.Error(ex, "Setup failed"); _notifier.Error(T("Setup failed: {0}", ex.Message)); model.Recipes = recipes; foreach (var recipe in recipes.Where(recipe => recipe.Name == model.Recipe)) { model.RecipeDescription = recipe.Description; } model.DatabaseIsPreconfigured = !string.IsNullOrEmpty(_setupService.Prime().DataProvider); return(IndexViewResult(model)); } }
public void CtorSetsIsNever() { var target = new SetupViewModel("foo", false, true); Assert.Equal(true, target.IsNever); }
public ShowDialogBoxCommand(SetupViewModel viewModel) { this.viewModel = viewModel; Console.WriteLine("created"); }
public void CtorSetsSetupExpression() { var target = new SetupViewModel("foo", false, false); Assert.Equal("foo", target.SetupExpression); }
public ActionResult IndexPOST(SetupViewModel model) { // Sets the setup request timeout to a configurable amount of seconds to give enough time to execute custom recipes. HttpContext.Server.ScriptTimeout = RecipeExecutionTimeout; var recipes = _setupService.Recipes().ToList(); // If no builtin provider, a connection string is mandatory. if (model.DatabaseProvider != SetupDatabaseType.Builtin && string.IsNullOrEmpty(model.DatabaseConnectionString)) { ModelState.AddModelError("DatabaseConnectionString", T("A connection string is required.").Text); } if (!String.IsNullOrWhiteSpace(model.ConfirmPassword) && model.AdminPassword != model.ConfirmPassword) { ModelState.AddModelError("ConfirmPassword", T("Password confirmation must match.").Text); } if (model.DatabaseProvider != SetupDatabaseType.Builtin && !string.IsNullOrWhiteSpace(model.DatabaseTablePrefix)) { model.DatabaseTablePrefix = model.DatabaseTablePrefix.Trim(); if (!Char.IsLetter(model.DatabaseTablePrefix[0])) { ModelState.AddModelError("DatabaseTablePrefix", T("The table prefix must begin with a letter.").Text); } if (model.DatabaseTablePrefix.Any(x => !Char.IsLetterOrDigit(x))) { ModelState.AddModelError("DatabaseTablePrefix", T("The table prefix must contain letters or digits.").Text); } } if (model.Recipe == null) { if (!(recipes.Select(r => r.Name).Contains(DefaultRecipe))) { ModelState.AddModelError("Recipe", T("No recipes were found.").Text); } else { model.Recipe = DefaultRecipe; } } if (!ModelState.IsValid) { model.Recipes = recipes; foreach (var recipe in recipes.Where(recipe => recipe.Name == model.Recipe)) { model.RecipeDescription = recipe.Description; } model.DatabaseIsPreconfigured = !String.IsNullOrEmpty(_setupService.Prime().DataProvider); return(IndexViewResult(model)); } try { string providerName = null; switch (model.DatabaseProvider) { case SetupDatabaseType.Builtin: providerName = "SqlCe"; break; case SetupDatabaseType.SqlServer: providerName = "SqlServer"; break; case SetupDatabaseType.MySql: providerName = "MySql"; break; case SetupDatabaseType.PostgreSql: providerName = "PostgreSql"; break; default: throw new ApplicationException("Unknown database type: " + model.DatabaseProvider); } var recipe = recipes.GetRecipeByName(model.Recipe); var setupContext = new SetupContext { SiteName = model.SiteName, AdminUsername = model.AdminUsername, AdminPassword = model.AdminPassword, DatabaseProvider = providerName, DatabaseConnectionString = model.DatabaseConnectionString, DatabaseTablePrefix = model.DatabaseTablePrefix, EnabledFeatures = null, // Default list Recipe = recipe }; var executionId = _setupService.Setup(setupContext); // First time installation if finally done. Tell the background views compilation // process to stop, so that it doesn't interfere with the user (asp.net compilation // uses a "single lock" mechanism for compiling views). _viewsBackgroundCompilation.Stop(); // Redirect to the welcome page. return(Redirect("~/" + _shellSettings.RequestUrlPrefix)); } catch (Exception ex) { Logger.Error(ex, "Setup failed"); _notifier.Error(T("Setup failed: {0}", ex.Message)); model.Recipes = recipes; foreach (var recipe in recipes.Where(recipe => recipe.Name == model.Recipe)) { model.RecipeDescription = recipe.Description; } model.DatabaseIsPreconfigured = !String.IsNullOrEmpty(_setupService.Prime().DataProvider); return(IndexViewResult(model)); } }
public PerformClientInitializationCommand(SetupViewModel viewModel) { this.viewModel = viewModel; }
public ViewPreviousChatsCommand(SetupViewModel viewModel) { this.viewModel = viewModel; }
public async Task <ActionResult> IndexPOST(SetupViewModel model) { if (!string.IsNullOrWhiteSpace(_shellSettings["Secret"])) { if (string.IsNullOrEmpty(model.Secret) || !await IsTokenValid(model.Secret)) { _logger.LogWarning("An attempt to access '{TenantName}' without providing a valid secret was made", _shellSettings.Name); return(StatusCode(404)); } } model.DatabaseProviders = _databaseProviders; model.Recipes = await _setupService.GetSetupRecipesAsync(); var selectedProvider = model.DatabaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (!model.DatabaseConfigurationPreset) { if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(model.ConnectionString), S["The connection string is mandatory for this provider."]); } } if (String.IsNullOrEmpty(model.Password)) { ModelState.AddModelError(nameof(model.Password), S["The password is required."]); } if (model.Password != model.PasswordConfirmation) { ModelState.AddModelError(nameof(model.PasswordConfirmation), S["The password confirmation doesn't match the password."]); } RecipeDescriptor selectedRecipe = null; if (!string.IsNullOrEmpty(_shellSettings["RecipeName"])) { selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == _shellSettings["RecipeName"]); if (selectedRecipe == null) { ModelState.AddModelError(nameof(model.RecipeName), S["Invalid recipe."]); } } else if (String.IsNullOrEmpty(model.RecipeName) || (selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == model.RecipeName)) == null) { ModelState.AddModelError(nameof(model.RecipeName), S["Invalid recipe."]); } // Only add additional errors if attribute validation has passed. if (!String.IsNullOrEmpty(model.Email) && !_emailAddressValidator.Validate(model.Email)) { ModelState.AddModelError(nameof(model.Email), S["The email is invalid."]); } if (!String.IsNullOrEmpty(model.UserName) && model.UserName.Any(c => !_identityOptions.User.AllowedUserNameCharacters.Contains(c))) { ModelState.AddModelError(nameof(model.UserName), S["User name '{0}' is invalid, can only contain letters or digits.", model.UserName]); } if (!ModelState.IsValid) { CopyShellSettingsValues(model); return(View(model)); } var setupContext = new SetupContext { ShellSettings = _shellSettings, EnabledFeatures = null, // default list, Errors = new Dictionary <string, string>(), Recipe = selectedRecipe, Properties = new Dictionary <string, object> { { SetupConstants.SiteName, model.SiteName }, { SetupConstants.AdminUsername, model.UserName }, { SetupConstants.AdminEmail, model.Email }, { SetupConstants.AdminPassword, model.Password }, { SetupConstants.SiteTimeZone, model.SiteTimeZone }, } }; if (!string.IsNullOrEmpty(_shellSettings["ConnectionString"])) { setupContext.Properties[SetupConstants.DatabaseProvider] = _shellSettings["DatabaseProvider"]; setupContext.Properties[SetupConstants.DatabaseConnectionString] = _shellSettings["ConnectionString"]; setupContext.Properties[SetupConstants.DatabaseTablePrefix] = _shellSettings["TablePrefix"]; } else { setupContext.Properties[SetupConstants.DatabaseProvider] = model.DatabaseProvider; setupContext.Properties[SetupConstants.DatabaseConnectionString] = model.ConnectionString; setupContext.Properties[SetupConstants.DatabaseTablePrefix] = model.TablePrefix; } var executionId = await _setupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { foreach (var error in setupContext.Errors) { ModelState.AddModelError(error.Key, error.Value); } return(View(model)); } return(Redirect("~/")); }
public async Task <IActionResult> Setup(SetupViewModel model) { if (ModelState.IsValid) { _logger.LogInformation("Tamils1809 Setup Begins"); // user with email as username var user = new User { UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName }; var adminRole = "Administrator"; var role = new Role { Name = adminRole, IsSystemRole = true, Description = "An Administrator has full power over the site and can do everything." }; // create user var result = await _userManager.CreateAsync(user, model.Password); // create Admin role if (result.Succeeded) { _logger.LogInformation("{@User} account created with password.", user); if (!await _roleManager.RoleExistsAsync(adminRole)) { result = await _roleManager.CreateAsync(role); } } // assign Admin role to user if (result.Succeeded) { _logger.LogInformation("{@Role} created.", role); result = await _userManager.AddToRoleAsync(user, adminRole); } if (result.Succeeded) { _logger.LogInformation("{@Role} assigned to {@User}.", role, user); // sign-in user await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User has been signed in."); // create core settings await _settingSvc.UpsertSettingsAsync(new CoreSettings { Title = model.Title, Tagline = model.Tagline, TimeZoneId = model.TimeZoneId, GoogleAnalyticsTrackingID = model.GoogleAnalyticsTrackingID.IsNullOrWhiteSpace() ? null : model.GoogleAnalyticsTrackingID.Trim(), }); _logger.LogInformation("CoreSettings created."); // setup blog await _blogSvc.SetupAsync(model.DisqusShortname); return(RedirectToAction("Index", "Blog")); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(View(model)); }
public SetupPage(INetworkService networkService) { BindingContext = _viewModel = new SetupViewModel(networkService); InitializeComponent(); }
public ActionResult IndexPOST(SetupViewModel model) { // Sets the setup request timeout to a configurable amount of seconds to give enough time to execute custom recipes. HttpContext.Server.ScriptTimeout = RecipeExecutionTimeout; var recipes = _setupService.Recipes().ToList(); // If no builtin provider, a connection string is mandatory. if (model.DatabaseProvider != SetupDatabaseType.Builtin && string.IsNullOrEmpty(model.DatabaseConnectionString)) { return(Json(new { State = 0, Msg = T("数据库连接字符串未填.").Text })); } if (!String.IsNullOrWhiteSpace(model.ConfirmPassword) && model.AdminPassword != model.ConfirmPassword) { return(Json(new { State = 0, Msg = T("密码不一致.").Text })); } if (model.DatabaseProvider != SetupDatabaseType.Builtin && !string.IsNullOrWhiteSpace(model.DatabaseTablePrefix)) { model.DatabaseTablePrefix = model.DatabaseTablePrefix.Trim(); if (!Char.IsLetter(model.DatabaseTablePrefix[0])) { return(Json(new { State = 0, Msg = T("表前缀必须以字母开头.").Text })); } if (model.DatabaseTablePrefix.Any(x => !Char.IsLetterOrDigit(x))) { return(Json(new { State = 0, Msg = T("表前缀必须包含字母或数字.").Text })); } } if (model.Recipe == null) { if (!(recipes.Select(r => r.Name).Contains(DefaultRecipe))) { return(Json(new { State = 0, Msg = T("安装模式不存在.").Text })); } else { model.Recipe = DefaultRecipe; } } if (!ModelState.IsValid) { return(Json(new { State = 0, Msg = T("验证失败.").Text })); } try { string providerName = null; switch (model.DatabaseProvider) { case SetupDatabaseType.Builtin: providerName = "SqlCe"; break; case SetupDatabaseType.SqlServer: providerName = "SqlServer"; break; case SetupDatabaseType.MySql: providerName = "MySql"; break; case SetupDatabaseType.PostgreSql: providerName = "PostgreSql"; break; default: throw new ApplicationException("Unknown database type: " + model.DatabaseProvider); } var recipe = recipes.GetRecipeByName(model.Recipe); var setupContext = new SetupContext { SiteName = model.SiteName, AdminUsername = model.AdminUsername, AdminPassword = model.AdminPassword, DatabaseProvider = providerName, DatabaseConnectionString = model.DatabaseConnectionString, DatabaseTablePrefix = model.DatabaseTablePrefix, EnabledFeatures = null, // Default list Recipe = recipe }; var executionId = _setupService.Setup(setupContext); // First time installation if finally done. Tell the background views compilation // process to stop, so that it doesn't interfere with the user (asp.net compilation // uses a "single lock" mechanism for compiling views). _viewsBackgroundCompilation.Stop(); // Redirect to the welcome page. return(Json(new { State = 1, Msg = "/" + _shellSettings.RequestUrlPrefix })); } catch (Exception ex) { Logger.Error(ex, "Setup failed"); //_notifier.Error(T("安装失败: {0}", ex.Message)); return(Json(new { State = 0, Msg = T("安装失败:" + ex.Message).Text })); } }
public async Task <ActionResult> Setup(SetupViewModel model, HttpPostedFileBase AttachedLogoImage, HttpPostedFileBase AttachedIconImage) { if (!ModelState.IsValid) { return(View("_Setup", model)); } await _settingService.EditAsync("Website Name", model.WebsiteName); Session.Remove("Setting-Website Name"); if (AttachedLogoImage != null) { var imageFilePath = SaveImage(AttachedLogoImage); await _imageService.CreateAsync(imageFilePath, ImageCategory.Logo); await _settingService.EditAsync("Website Logo", imageFilePath); Session.Remove("Setting-Website Logo"); } if (AttachedIconImage != null) { var imageFilePath = SaveImage(AttachedIconImage); await _imageService.CreateAsync(imageFilePath, ImageCategory.Logo); await _settingService.EditAsync("Website FavIcon", imageFilePath); Session.Remove("Setting-Website FavIcon"); } await _settingService.EditAsync("Description Meta Tag", model.WebsiteDescription); Session.Remove("Setting-Description Meta Tag"); await _settingService.EditAsync("Google Analytics Tracking ID", model.GoogleAnalyticsId); Session.Remove("Setting-Google Analytics Tracking ID"); await _settingService.EditAsync("Email From Address", model.EmailFromAddress); Session.Remove("Setting-Email From Address"); await _settingService.EditAsync("SendGrid ApiKey", model.SendGridApiKey); Session.Remove("Setting-SendGrid ApiKey"); await _settingService.EditAsync("CDN Address", model.CDNAddress); Session.Remove("Setting-CDN Address"); await _settingService.EditAsync("Recaptcha Site Key", model.RecaptchaSiteKey); Session.Remove("Setting-Recaptcha Site Key"); await _settingService.EditAsync("Recaptcha Secret Key", model.RecaptchaSecretKey); Session.Remove("Setting-Recaptcha Secret Key"); return(Content("Refresh")); }
/// <summary> /// The setup. /// </summary> public void Setup() { if (this._channels.Any()) { this.LoadDataFromSetupNode(); var viewModel = new SetupViewModel(_displayWidth, _displayHeight, _background); this._channels.ForEach(x => viewModel.Channels.Add(x)); this._elements.ForEach(x => viewModel.DisplayElements.Add(x)); bool saveData = false; using (this._setupDialog = new Setup(viewModel)) { this._setupDialog.ShowDialog(); var result = MessageBox.Show( "Do you want to save the changes made?", "Save Changes", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (result == MessageBoxResult.Yes) { saveData = true; this._elements.Clear(); this._elements.AddRange(viewModel.DisplayElements); this._displayWidth = viewModel.DisplayWidth; this._displayHeight = viewModel.DisplayHeight; _background = viewModel.BackgroundImage; } } if (saveData) { while (this._setupNode.ChildNodes.Count > 0) { this._setupNode.RemoveChild(this._setupNode.ChildNodes[0]); } var imageBytes = _background.ToByteArray(); if (imageBytes.Length > 0) { _setupData.SetBytes(_setupNode, "BackgroundImage", imageBytes); } var heightAttribute = _setupNode.Attributes.GetNamedItem("displayHeight"); var widthAttribute = _setupNode.Attributes.GetNamedItem("displayWidth"); if (heightAttribute == null) { _setupNode.AppendAttribute("displayHeight", _displayHeight.ToString()); } else { heightAttribute.Value = _displayHeight.ToString(); } if (widthAttribute == null) { _setupNode.AppendAttribute("displayWidth", _displayWidth.ToString()); } else { widthAttribute.Value = _displayWidth.ToString(); } foreach (var element in this._elements) { var node = this._setupNode.OwnerDocument.CreateElement("DisplayElement"); node.AppendAttribute("Rows", element.Rows.ToString()); node.AppendAttribute("Columns", element.Columns.ToString()); node.AppendAttribute("Height", element.Height.ToString()); node.AppendAttribute("Width", element.Width.ToString()); node.AppendAttribute("LeftOffset", element.LeftOffset.ToString()); node.AppendAttribute("TopOffset", element.TopOffset.ToString()); node.AppendAttribute("Name", element.Name); node.AppendAttribute("IsUnlocked", element.IsUnlocked.ToString()); foreach (var mappedChannel in element.PixelMappings) { var mappedNode = node.OwnerDocument.CreateElement("PixelMapping"); var pixel = mappedChannel.Pixel; if (pixel != null) { var channelNode = mappedNode.OwnerDocument.CreateElement("Channel"); mappedNode.AppendChild(channelNode); if (pixel is EmptyPixel) { channelNode.AppendAttribute("Type", "Empty"); } else if (pixel is SingleColorPixel) { channelNode.AppendAttribute("Type", "Single"); var singleColorChannel = (SingleColorPixel)pixel; var vixenChannel = singleColorChannel.Channel; channelNode.AppendAttribute( "ChannelId", vixenChannel == null ? string.Empty : vixenChannel.Name); channelNode.AppendAttribute("Color", singleColorChannel.DisplayColor.ToString()); } else { var rgb = pixel as RedGreenBluePixel; var redChannel = rgb.RedChannel; channelNode.AppendAttribute( "RedChannel", redChannel == null ? string.Empty : redChannel.Name); var greenChannel = rgb.GreenChannel; channelNode.AppendAttribute( "GreenChannel", greenChannel == null ? string.Empty : greenChannel.Name); var blueChannel = rgb.BlueChannel; channelNode.AppendAttribute( "BlueChannel", blueChannel == null ? string.Empty : blueChannel.Name); var rgbw = pixel as RedGreenBlueWhitePixel; var type = "RGB"; if (rgbw != null) { var whiteChannel = rgbw.WhiteChannel; channelNode.AppendAttribute( "WhiteChannel", whiteChannel == null ? string.Empty : whiteChannel.Name); type += "W"; } channelNode.AppendAttribute("Type", type); } } node.AppendChild(mappedNode); } this._setupNode.AppendChild(node); } } this.LoadDataFromSetupNode(); this._setupDialog = null; } else { MessageBox.Show( "There are no channels assigned to this plugin.", this.Name, MessageBoxButton.OK, MessageBoxImage.Hand); } }
public SelectedSetupChanged(SetupViewModel setup) { this.Setup = setup; }