public async Task ExecuteAsync(UpdatePageDraftVersionCommand command, IExecutionContext executionContext) { Normalize(command); var draft = await GetDraftVersion(command.PageId).SingleOrDefaultAsync(); using (var scope = _transactionScopeFactory.Create(_dbContext)) { draft = await CreateDraftIfRequiredAsync(command.PageId, draft); UpdateDraft(command, draft); await _dbContext.SaveChangesAsync(); await _pageStoredProcedures.UpdatePublishStatusQueryLookupAsync(command.PageId); scope.QueueCompletionTask(() => OnTransactionComplete(draft)); if (command.Publish) { await _commandExecutor.ExecuteAsync(new PublishPageCommand(draft.PageId, command.PublishDate), executionContext); } await scope.CompleteAsync(); } }
public async Task ExecuteAsync(UpdatePageDraftVersionCommand command, IExecutionContext executionContext) { var draft = await GetDraftVersion(command.PageId).SingleOrDefaultAsync(); using (var scope = _transactionScopeFactory.Create()) { draft = await CreateDraftIfRequiredAsync(command.PageId, draft); UpdateDraft(command, draft); await _dbContext.SaveChangesAsync(); scope.Complete(); } _pageCache.Clear(command.PageId); await _messageAggregator.PublishAsync(new PageDraftVersionUpdatedMessage() { PageId = command.PageId, PageVersionId = draft.PageVersionId }); if (command.Publish) { await _commandExecutor.ExecuteAsync(new PublishPageCommand(draft.PageId)); } }
public async Task ExecuteAsync(SetupCofoundryCommand command, IExecutionContext executionContext) { var settings = await _queryExecutor.ExecuteAsync(new GetSettingsQuery <InternalSettings>()); if (settings.IsSetup) { throw new InvalidOperationException("Site is already set up."); } using (var scope = _transactionScopeFactory.Create(_dbContext)) { var userId = await CreateAdminUser(command); var impersonatedUserContext = await GetImpersonatedUserContext(executionContext, userId); var settingsCommand = await _queryExecutor.ExecuteAsync(new GetUpdateCommandQuery <UpdateGeneralSiteSettingsCommand>()); settingsCommand.ApplicationName = command.ApplicationName; await _commandExecutor.ExecuteAsync(settingsCommand, impersonatedUserContext); // Take the opportunity to break the cache in case any additional install scripts have been run since initialization _objectCacheFactory.Clear(); // Setup Complete await _commandExecutor.ExecuteAsync(new MarkAsSetUpCommand(), impersonatedUserContext); await scope.CompleteAsync(); } }
private async Task <Cpu> GetCpuFromCommandOutput() { var cpuLoadOutput = await _commandExecutor.ExecuteAsync(CpuLoadCommand); var loadParameters = cpuLoadOutput.Output.Split(' '); var cpuInfoOutput = await _commandExecutor.ExecuteAsync(CpuInfoCommand); var cpuInfoLines = cpuInfoOutput.Output.Split(Environment.NewLine); // TODO: now we checks only first core var cpuInfo = new CpuInfo { Architecture = _outputParser.Parse(cpuInfoLines, "Architecture"), Cores = int.Parse(_outputParser.Parse(cpuInfoLines, "Cores")), Model = _outputParser.Parse(cpuInfoLines, "Model name") }; var cpu = new Cpu { AverageUsageFor1M = double.Parse(loadParameters[0].Trim()), AverageUsageFor5M = double.Parse(loadParameters[1].Trim()), AverageUsageFor15M = double.Parse(loadParameters[2].Trim()), RunningProcesses = int.Parse(loadParameters[3].Split('/').First()), TotalProcesses = int.Parse(loadParameters[3].Split('/').Last()), CpuInfo = cpuInfo }; return(cpu); }
public async Task ExecuteAsync(UpdateCustomEntityDraftVersionCommand command, IExecutionContext executionContext) { var definition = _customEntityDefinitionRepository.GetByCode(command.CustomEntityDefinitionCode); var draft = await GetDraftVersionAsync(command); using (var scope = _transactionScopeFactory.Create(_dbContext)) { draft = await CreateDraftIfRequiredAsync(command, draft, executionContext); await ValidateTitleAsync(command, draft, definition, executionContext); UpdateDraft(command, draft); await _dbContext.SaveChangesAsync(); var dependencyCommand = new UpdateUnstructuredDataDependenciesCommand( CustomEntityVersionEntityDefinition.DefinitionCode, draft.CustomEntityVersionId, command.Model); await _commandExecutor.ExecuteAsync(dependencyCommand, executionContext); scope.QueueCompletionTask(() => OnUpdateDraftComplete(command, draft)); if (command.Publish) { await _commandExecutor.ExecuteAsync(new PublishCustomEntityCommand(draft.CustomEntityId, command.PublishDate), executionContext); } await scope.CompleteAsync(); } }
public async Task ExecuteAsync(DeleteImageAssetCommand command, IExecutionContext executionContext) { var imageAsset = await _dbContext .ImageAssets .FilterById(command.ImageAssetId) .SingleOrDefaultAsync(); if (imageAsset != null) { _dbContext.ImageAssets.Remove(imageAsset); var fileName = Path.ChangeExtension(imageAsset.FileNameOnDisk, imageAsset.FileExtension); var deleteUnstructuredDataComand = new DeleteUnstructuredDataDependenciesCommand(ImageAssetEntityDefinition.DefinitionCode, imageAsset.ImageAssetId); var deleteFileCommand = new QueueAssetFileDeletionCommand() { EntityDefinitionCode = ImageAssetEntityDefinition.DefinitionCode, FileNameOnDisk = imageAsset.FileNameOnDisk, FileExtension = imageAsset.FileExtension }; using (var scope = _transactionScopeFactory.Create(_dbContext)) { await _dbContext.SaveChangesAsync(); await _commandExecutor.ExecuteAsync(deleteFileCommand, executionContext); await _commandExecutor.ExecuteAsync(deleteUnstructuredDataComand, executionContext); scope.QueueCompletionTask(() => OnTransactionComplete(command)); await scope.CompleteAsync(); } } }
public async Task ExecuteAsync(DuplicateCustomEntityCommand command, IExecutionContext executionContext) { var customEntityToDuplicate = await GetCustomEntityToDuplicateAsync(command); var definition = _customEntityDefinitionRepository.GetRequiredByCode(customEntityToDuplicate.CustomEntity.CustomEntityDefinitionCode); var addCustomEntityCommand = MapCommand(command, customEntityToDuplicate); using (var scope = _transactionScopeFactory.Create(_dbContext)) { // Note: the underlying AddCustomEntityCommand will enforce permissions await _commandExecutor.ExecuteAsync(addCustomEntityCommand, executionContext); await _customEntityStoredProcedures.CopyBlocksToDraftAsync( addCustomEntityCommand.OutputCustomEntityId, customEntityToDuplicate.CustomEntityVersionId); if (definition.AutoPublish) { var publishCommand = new PublishCustomEntityCommand(addCustomEntityCommand.OutputCustomEntityId); await _commandExecutor.ExecuteAsync(publishCommand); } await scope.CompleteAsync(); } // Set Ouput command.OutputCustomEntityId = addCustomEntityCommand.OutputCustomEntityId; }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { var createdUserId = default(int); var command = new CreateUserCommand { EmailAddress = model.Email, Password = model.Password }; _commandExecutor.CommandExecuted += args => createdUserId = (int)args.Args; await _commandExecutor.ExecuteAsync(command); var userDto = new UserDto { UserId = createdUserId, EmailAddress = model.Email }; #if NETCOREAPP var identity = new ClaimsIdentity(GetUserClaims(userDto), CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); #endif #if NETFRAMEWORK FormsAuthentication.SetAuthCookie(_GetAuthenticationCookieUserName(userDto), false); #endif return(RedirectToAction("Index", "Home")); } return(View(model)); }
public async Task ExecuteAsync(UpdateUnauthenticatedUserPasswordCommand command, IExecutionContext executionContext) { if (IsLoggedInAlready(command, executionContext)) { throw new Exception("UpdateUnauthenticatedUserPasswordCommand cannot be used when the user is already logged in."); } await ValidateMaxLoginAttemptsNotExceeded(command, executionContext); var userArea = _userAreaRepository.GetByCode(command.UserAreaCode); var userLoginInfo = await GetUserLoginInfoAsync(command, executionContext); if (userLoginInfo == null) { var failedLoginLogCommand = new LogFailedLoginAttemptCommand(command.UserAreaCode, command.Username); await _commandExecutor.ExecuteAsync(failedLoginLogCommand); throw new InvalidCredentialsAuthenticationException(nameof(command.OldPassword)); } var updatePasswordCommand = new UpdateUserPasswordByUserIdCommand() { UserId = userLoginInfo.UserId, NewPassword = command.NewPassword }; // User is not logged in, so will need to elevate permissions here to change the password. var systemExecutionContext = await _executionContextFactory.CreateSystemUserExecutionContextAsync(executionContext); await _commandExecutor.ExecuteAsync(updatePasswordCommand, systemExecutionContext); // We pass out the userid since we do the auth inside the command and it might be useful to the callee command.OutputUserId = userLoginInfo.UserId; }
public async Task <IActionResult> InsertNewCustomer([FromBody] InsertCustomerApiParameters parameters) { await _commandExecutor.ExecuteAsync( new InsertCustomerCommandParameters( age : parameters.Age)); return(Ok()); }
public async Task ExecuteAsync(RegisterPageTemplatesAndPageBlockTypesCommand command) { var cx = await _executionContextFactory.CreateSystemUserExecutionContextAsync(); await _commandExecutor.ExecuteAsync(new RegisterPageTemplatesCommand(), cx); await _commandExecutor.ExecuteAsync(new RegisterPageBlockTypesCommand(), cx); }
public async Task <TagResult> PostTag(TagCreateRequest tagCreateRequest) { var tagCommand = CreateTagCommand(tagCreateRequest); await m_commandExecutor.ExecuteAsync(tagCommand); var postedTag = await FindTag(tagCommand.Id); return(postedTag); }
public async Task <IActionResult> CreateNewShip(CreateNewShipCommand createNewShipCommand) { var createdShipId = 0; _commandExecutor.CommandExecuted += args => createdShipId = (int)args.Args; await _commandExecutor.ExecuteAsync(createNewShipCommand); return(RedirectToAction("CreateNewShip", new { lastCreatedShipId = createdShipId })); }
public async Task <IngredientResult> PostIngredient(IngredientCreateRequest ingredientRequest) { var ingredientCommand = CreateIngredientCommand(ingredientRequest); await m_commandExecutor.ExecuteAsync(ingredientCommand); var postedIngredient = await FindIngredient(ingredientCommand.Id); return(postedIngredient); }
public async Task <string> CreateNewShip(string shipName, decimal tonnage) { var generatedShipId = 0; _commandExecutor.CommandExecuted += args => generatedShipId = (int)args.Args; await _commandExecutor.ExecuteAsync(new CreateNewShipCommand { ShipName = shipName, Tonnage = tonnage }); return($"A new ship was created. ship id: {generatedShipId}"); }
public async Task <ActionResult> Create() { var createdEmailTemplateId = default(int); var command = new CreateEmailTemplateCommand { UserId = GetUserId() }; _commandExecutor.CommandExecuted += args => createdEmailTemplateId = (int)args.Args; await _commandExecutor.ExecuteAsync(command); return(RedirectToAction("Edit", "Template", new { id = createdEmailTemplateId })); }
public async Task <ActionResult> Create(int id) { var createdEmailId = default(int); var command = new CreateEmailCommand { EmailTemplateId = id }; _commandExecutor.CommandExecuted += args => createdEmailId = (int)args.Args; await _commandExecutor.ExecuteAsync(command); return(RedirectToAction("EditVariables", "Email", new { id = createdEmailId })); }
public async Task PostSuggestion(CreateSuggestionRequest request) { await m_commandExecutor.ExecuteAsync( new SuggestionCommand { Id = Guid.NewGuid(), Count = request.Count, ModeId = request.ModeId, Overruled = request.Overruled, SpotifyId = request.SpotifyId, YoutubeId = request.YoutubeId } ); }
/// <summary> /// Logs a user into the application but performs no /// authentication. The user should have already passed /// authentication prior to calling this method. /// </summary> /// <param name="userId">The id of the user to log in.</param> /// <param name="rememberUser"> /// True if the user should stay logged in perminantely; false /// if the user should only stay logged in for the duration of /// the session. /// </param> public async Task LogAuthenticatedUserInAsync(int userId, bool rememberUser) { // Remove any existing login (user may be switching between login areas) SignOut(); var command = new LogAuthenticatedUserInCommand() { UserId = userId }; await _commandExecutor.ExecuteAsync(command); _userSessionService.SetCurrentUserId(userId, rememberUser); }
/// <summary> /// Logs a user into the application but performs no /// authentication. The user should have already passed /// authentication prior to calling this method. /// </summary> /// <param name="userAreaCode">The code of the user area to log into.</param> /// <param name="userId">The id of the user to log in.</param> /// <param name="rememberUser"> /// True if the user should stay logged in perminantely; false /// if the user should only stay logged in for the duration of /// the session. /// </param> public async Task LogAuthenticatedUserInAsync(string userAreaCode, int userId, bool rememberUser) { // Remove any existing login await SignOutAsync(userAreaCode); var command = new LogAuthenticatedUserInCommand() { UserId = userId }; await _commandExecutor.ExecuteAsync(command); await _userSessionService.LogUserInAsync(userAreaCode, userId, rememberUser); }
public async Task <int> CreateNewShipAsync(string shipName, decimal tonnage) { var createNewShipCommand = new CreateNewShipCommand { ShipName = shipName, Tonnage = tonnage }; var generatedShipId = 0; _commandExecutor.CommandExecuted += args => generatedShipId = (int)args.Args; await _commandExecutor.ExecuteAsync(createNewShipCommand); return(generatedShipId); }
/// <summary> /// Logs a user into the application but performs no /// authentication. The user should have already passed /// authentication prior to calling this method. /// </summary> /// <param name="userAreaCode">The code of the user area to log into.</param> /// <param name="userId">The id of the user to log in.</param> /// <param name="rememberUser"> /// True if the user should stay logged in perminantely; false /// if the user should only stay logged in for the duration of /// the session. /// </param> public virtual async Task LogAuthenticatedUserInAsync(string userAreaCode, int userId, bool rememberUser) { // Clear any existing session await SignOutAsync(userAreaCode); // Log in new session await _userSessionService.LogUserInAsync(userAreaCode, userId, rememberUser); // Update the user record var command = new LogSuccessfulLoginCommand() { UserId = userId }; await _commandExecutor.ExecuteAsync(command); }
public async Task DeleteIngredientFromDish(int dishId, int[] ingredientIds) { List <DeleteDishIngredientCommand> deleteDishIngredientCommands = new List <DeleteDishIngredientCommand>(); foreach (var ingredientid in ingredientIds) { deleteDishIngredientCommands.Add(new DeleteDishIngredientCommand { DishId = dishId, IngredientId = ingredientid }); } await m_commandExecutor.ExecuteAsync(deleteDishIngredientCommands.AsEnumerable()); }
public async Task AddTagsToDish(DishTagCreateRequest dishTagCreateRequest) { var dishTagCommands = new List <DishTagCommand>(); foreach (var tagId in dishTagCreateRequest.TagIds) { dishTagCommands.Add(new DishTagCommand { Id = m_idGenerator.GenerateId(), Dish_id_fk = dishTagCreateRequest.DishId, Tag_id_fk = tagId }); } await m_commandExecutor.ExecuteAsync(dishTagCommands.AsEnumerable()); }
public async Task <JsonResult> RunCommandAsync <TCommand>(TCommand command) where TCommand : ICommand { var errors = _commandValidationService.GetErrors(command).ToList(); if (!errors.Any()) { try { await _commandExecutor.ExecuteAsync(command); } catch (ValidationException ex) { AddValidationExceptionToErrorList(ex, errors); } catch (NotPermittedException ex) { return(NotPermittedResponse(ex)); } } var outputValue = GetCommandOutputValue(command); if (outputValue != null) { return(SimpleCommandResponse(errors, outputValue)); } return(SimpleCommandResponse(errors)); }
public async Task ExecuteAsync(DeletePageVersionBlockCommand command, IExecutionContext executionContext) { var dbResult = await _dbContext .PageVersionBlocks .Where(b => b.PageVersionBlockId == command.PageVersionBlockId) .Select(b => new { Block = b, PageId = b.PageVersion.PageId, WorkFlowStatusId = b.PageVersion.WorkFlowStatusId }) .SingleOrDefaultAsync(); if (dbResult != null) { if (dbResult.WorkFlowStatusId != (int)WorkFlowStatus.Draft) { throw new NotPermittedException("Page blocks cannot be deleted unless the page version is in draft status"); } var versionId = dbResult.Block.PageVersionId; using (var scope = _transactionScopeFactory.Create(_dbContext)) { await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(PageVersionBlockEntityDefinition.DefinitionCode, dbResult.Block.PageVersionBlockId), executionContext); _dbContext.PageVersionBlocks.Remove(dbResult.Block); await _dbContext.SaveChangesAsync(); scope.QueueCompletionTask(() => OnTransactionComplete(dbResult.PageId, versionId)); await scope.CompleteAsync(); } } }
public async Task <IActionResult> Execute([FromBody] ExecuteScriptRequest request) { PrepareCommandArguments(request); try { var result = await _commandExecutor.ExecuteAsync(); ExecuteScriptResponse response = new ExecuteScriptResponse { Logs = await GetLogs() }; switch (result) { case 0: return(Ok(response)); } throw new HttpError(HttpStatusCode.InternalServerError, result.ToString()) { Logs = await GetLogs() }; } catch (BuildScriptLocatorException e) { throw new HttpError(HttpStatusCode.BadRequest, ErrorCodes.ScriptNotFound, e.Message); } catch (TargetNotFoundException e) { throw new HttpError(HttpStatusCode.BadRequest, ErrorCodes.TargetNotFound, e.Message); } }
public async Task ExecuteAsync(DeleteCustomEntityDraftVersionCommand command, IExecutionContext executionContext) { var draft = await _dbContext .CustomEntityVersions .Include(v => v.CustomEntity) .SingleOrDefaultAsync(v => v.CustomEntityId == command.CustomEntityId && v.WorkFlowStatusId == (int)WorkFlowStatus.Draft); if (draft != null) { _permissionValidationService.EnforceCustomEntityPermission <CustomEntityUpdatePermission>(draft.CustomEntity.CustomEntityDefinitionCode); var definitionCode = draft.CustomEntity.CustomEntityDefinitionCode; var versionId = draft.CustomEntityVersionId; using (var scope = _transactionScopeFactory.Create()) { await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(CustomEntityVersionEntityDefinition.DefinitionCode, draft.CustomEntityVersionId)); _dbContext.CustomEntityVersions.Remove(draft); await _dbContext.SaveChangesAsync(); scope.Complete(); } _customEntityCache.Clear(definitionCode, command.CustomEntityId); await _messageAggregator.PublishAsync(new CustomEntityDraftVersionDeletedMessage() { CustomEntityId = command.CustomEntityId, CustomEntityDefinitionCode = definitionCode, CustomEntityVersionId = versionId }); } }
public async Task ExecuteAsync(DeleteDocumentAssetCommand command, IExecutionContext executionContext) { var documentAsset = await _dbContext .DocumentAssets .FilterById(command.DocumentAssetId) .SingleOrDefaultAsync(); if (documentAsset != null) { await _dependableEntityDeleteCommandValidator.ValidateAsync(DocumentAssetEntityDefinition.DefinitionCode, documentAsset.DocumentAssetId, executionContext); var deleteFileCommand = new QueueAssetFileDeletionCommand() { EntityDefinitionCode = DocumentAssetEntityDefinition.DefinitionCode, FileNameOnDisk = documentAsset.FileNameOnDisk, FileExtension = documentAsset.FileExtension }; _dbContext.DocumentAssets.Remove(documentAsset); using (var scope = _transactionScopeFactory.Create(_dbContext)) { await _dbContext.SaveChangesAsync(); await _commandExecutor.ExecuteAsync(deleteFileCommand, executionContext); scope.QueueCompletionTask(() => OnTransactionComplete(command)); await scope.CompleteAsync(); } } }
public async Task ExecuteAsync(EnsureCustomEntityDefinitionExistsCommand command, IExecutionContext executionContext) { var customEntityDefinition = _customEntityDefinitionRepository.GetByCode(command.CustomEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(customEntityDefinition, command.CustomEntityDefinitionCode); var dbDefinition = await _dbContext .CustomEntityDefinitions .FilterByCode(command.CustomEntityDefinitionCode) .SingleOrDefaultAsync(); if (dbDefinition == null) { await _commandExecutor.ExecuteAsync(new EnsureEntityDefinitionExistsCommand(command.CustomEntityDefinitionCode)); dbDefinition = new CustomEntityDefinition() { CustomEntityDefinitionCode = customEntityDefinition.CustomEntityDefinitionCode, ForceUrlSlugUniqueness = customEntityDefinition.ForceUrlSlugUniqueness, HasLocale = customEntityDefinition.HasLocale }; if (customEntityDefinition is IOrderableCustomEntityDefinition) { dbDefinition.IsOrderable = ((IOrderableCustomEntityDefinition)customEntityDefinition).Ordering != CustomEntityOrdering.None; } _dbContext.CustomEntityDefinitions.Add(dbDefinition); await _dbContext.SaveChangesAsync(); } }