private User MapAndAddUser(AddMasterCofoundryUserCommand command, IExecutionContext executionContext, Role superUserRole, UserArea userArea) { var user = new User(); user.FirstName = command.FirstName; user.LastName = command.LastName; user.Username = command.Email; user.Email = command.Email; user.RequirePasswordChange = command.RequirePasswordChange; user.LastPasswordChangeDate = executionContext.ExecutionDate; user.CreateDate = executionContext.ExecutionDate; user.Role = superUserRole; var hashResult = _passwordCryptographyService.CreateHash(command.Password); user.Password = hashResult.Hash; user.PasswordHashVersion = hashResult.HashVersion; user.UserArea = userArea; EntityNotFoundException.ThrowIfNull(user.UserArea, CofoundryAdminUserArea.AreaCode); _dbContext.Users.Add(user); return(user); }
public async Task ExecuteAsync(UpdateUserCommand command, IExecutionContext executionContext) { // Get User var user = await _dbContext .Users .FilterCanLogIn() .FilterById(command.UserId) .SingleOrDefaultAsync(); EntityNotFoundException.ThrowIfNull(user, command.UserId); // Validate var userArea = _userAreaRepository.GetByCode(user.UserAreaCode); ValidatePermissions(userArea, executionContext); ValidateCommand(command, userArea); await ValidateIsUniqueAsync(command, userArea, executionContext); // Role if (command.RoleId != user.RoleId) { user.Role = await _userCommandPermissionsHelper.GetAndValidateNewRoleAsync( command.RoleId, user.RoleId, user.UserAreaCode, executionContext ); } // Map Map(command, user, userArea); // Save await _dbContext.SaveChangesAsync(); }
public async Task ExecuteAsync(AddMasterCofoundryUserCommand command, IExecutionContext executionContext) { var settings = await _queryExecutor.ExecuteAsync(new GetSettingsQuery <InternalSettings>(), executionContext); if (settings.IsSetup) { throw new ValidationException("Site is already set up."); } if (await _dbContext .Users .FilterCanLogIn() .AnyAsync(u => u.Role.RoleCode == SuperAdminRole.SuperAdminRoleCode)) { throw new ValidationException("Cannot create a master user when master users already exist in the database."); } var role = await _dbContext .Roles .SingleOrDefaultAsync(r => r.RoleCode == SuperAdminRole.SuperAdminRoleCode); EntityNotFoundException.ThrowIfNull(role, SuperAdminRole.SuperAdminRoleCode); var userArea = await _dbContext .UserAreas .SingleOrDefaultAsync(a => a.UserAreaCode == CofoundryAdminUserArea.AreaCode); var user = MapAndAddUser(command, executionContext, role, userArea); await _dbContext.SaveChangesAsync(); command.OutputUserId = user.UserId; }
private async Task MapPageAsync(UpdatePageUrlCommand command, IExecutionContext executionContext, Page page) { if (page.PageTypeId == (int)PageType.CustomEntityDetails) { var rule = await _queryExecutor.ExecuteAsync(new GetCustomEntityRoutingRuleByRouteFormatQuery(command.CustomEntityRoutingRule), executionContext); if (rule == null) { throw ValidationErrorException.CreateWithProperties("Routing rule not found", "CustomEntityRoutingRule"); } var customEntityDefinition = await _queryExecutor.ExecuteAsync(new GetCustomEntityDefinitionSummaryByCodeQuery(page.CustomEntityDefinitionCode), executionContext); EntityNotFoundException.ThrowIfNull(customEntityDefinition, page.CustomEntityDefinitionCode); if (customEntityDefinition.ForceUrlSlugUniqueness && !rule.RequiresUniqueUrlSlug) { throw ValidationErrorException.CreateWithProperties("Ths routing rule requires a unique url slug, but the selected custom entity does not enforce url slug uniqueness", "CustomEntityRoutingRule"); } page.UrlPath = rule.RouteFormat; } else { page.UrlPath = command.UrlPath; } page.PageDirectoryId = command.PageDirectoryId; page.LocaleId = command.LocaleId; }
private async Task <PagedQueryResult <CustomEntityVersion> > GetQueryAsync(SearchCustomEntityRenderSummariesQuery query, IExecutionContext executionContext) { var definition = _customEntityDefinitionRepository.GetByCode(query.CustomEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(definition, query.CustomEntityDefinitionCode); var dbQuery = _dbContext .CustomEntityPublishStatusQueries .AsNoTracking() .FilterByCustomEntityDefinitionCode(query.CustomEntityDefinitionCode) .FilterActive() .FilterByStatus(query.PublishStatus, executionContext.ExecutionDate); // Filter by locale if (query.LocaleId > 0 && definition.HasLocale) { dbQuery = dbQuery.Where(p => p.CustomEntity.LocaleId == query.LocaleId); } else { dbQuery = dbQuery.Where(p => !p.CustomEntity.LocaleId.HasValue); } var dbPagedResult = await dbQuery .SortBy(definition, query.SortBy, query.SortDirection) .Select(p => p.CustomEntityVersion) .Include(e => e.CustomEntity) .ToPagedResultAsync(query); return(dbPagedResult); }
private async Task <PageVersionBlockRenderDetails> MapAsync( PageVersionBlock pageVersionBlock, string blockTypeFileName, PublishStatusQuery publishStatus, IExecutionContext executionContext ) { var blockTypeQuery = new GetPageBlockTypeSummaryByIdQuery(pageVersionBlock.PageBlockTypeId); var blockType = await _queryExecutor.ExecuteAsync(blockTypeQuery, executionContext); EntityNotFoundException.ThrowIfNull(blockType, pageVersionBlock.PageBlockTypeId); var result = new PageVersionBlockRenderDetails(); result.PageVersionBlockId = pageVersionBlock.PageVersionBlockId; result.BlockType = blockType; result.DisplayModel = await _pageVersionBlockModelMapper.MapDisplayModelAsync( blockTypeFileName, pageVersionBlock, publishStatus, executionContext ); return(result); }
public async Task ExecuteAsync(DeletePageCommand command, IExecutionContext executionContext) { var page = await _dbContext .Pages .FilterById(command.PageId) .SingleOrDefaultAsync(); if (page == null) { return; } var pageRoute = await _queryExecutor.ExecuteAsync(new GetPageRouteByIdQuery(page.PageId), executionContext); EntityNotFoundException.ThrowIfNull(pageRoute, command.PageId); await _dependableEntityDeleteCommandValidator.ValidateAsync(PageEntityDefinition.DefinitionCode, command.PageId, executionContext); _dbContext.Pages.Remove(page); using (var scope = _transactionScopeFactory.Create(_dbContext)) { await _dbContext.SaveChangesAsync(); await _pageStoredProcedures.UpdatePublishStatusQueryLookupAsync(command.PageId); scope.QueueCompletionTask(() => OnTransactionComplete(pageRoute)); await scope.CompleteAsync(); } }
private void UpdateDraft(UpdateCustomEntityDraftVersionCommand command, CustomEntityVersion draft) { EntityNotFoundException.ThrowIfNull(draft, "Draft:" + command.CustomEntityId); draft.Title = command.Title.Trim(); draft.SerializedData = _dbUnstructuredDataSerializer.Serialize(command.Model); }
public async Task <ICollection <EntityDependencySummary> > ExecuteAsync(GetEntityDependencySummaryByRelatedEntityIdRangeQuery query, IExecutionContext executionContext) { var dbQuery = _dbContext .UnstructuredDataDependencies .AsNoTracking() .FilterByRelatedEntity(query.EntityDefinitionCode, query.EntityIds); if (query.ExcludeDeletable) { dbQuery = dbQuery.Where(r => r.RelatedEntityCascadeActionId == (int)RelatedEntityCascadeAction.None); } // Groupby still not suppored in EF 3.1 ¯\_(ツ)_/¯ var queryResult = await dbQuery.ToListAsync(); var dbDependencyGroups = queryResult .GroupBy(r => r.RootEntityDefinitionCode) .ToList(); var allRelatedEntities = new List <EntityDependencySummary>(); foreach (var dbDependencyGroup in dbDependencyGroups) { var definition = _entityDefinitionRepository.GetRequiredByCode(dbDependencyGroup.Key) as IDependableEntityDefinition; EntityNotFoundException.ThrowIfNull(definition, dbDependencyGroup.Key); var getEntitiesQuery = definition.CreateGetEntityMicroSummariesByIdRangeQuery(dbDependencyGroup.Select(e => e.RootEntityId)); var entityMicroSummaries = await _queryExecutor.ExecuteAsync(getEntitiesQuery, executionContext); foreach (var entityMicroSummary in entityMicroSummaries.OrderBy(e => e.Value.RootEntityTitle)) { var dbDependency = dbDependencyGroup.SingleOrDefault(e => e.RootEntityId == entityMicroSummary.Key); // relations for previous versions can be removed even when they are required. var canDelete = dbDependency.RelatedEntityCascadeActionId != (int)RelatedEntityCascadeAction.None || entityMicroSummary.Value.IsPreviousVersion; if (query.ExcludeDeletable && canDelete) { continue; } allRelatedEntities.Add(new EntityDependencySummary() { Entity = entityMicroSummary.Value, CanDelete = canDelete }); } } // filter out duplicates, selecting the more restrictive entity first var results = allRelatedEntities .GroupBy(e => new { e.Entity.EntityDefinitionCode, e.Entity.RootEntityId }, (k, v) => v.OrderBy(e => e.CanDelete).First()) .ToList(); return(results); }
/// <summary> /// Finishes off bulk mapping of tags and page routes in a PageSummary object /// </summary> public async Task <List <PageSummary> > MapAsync(ICollection <Page> dbPages, IExecutionContext executionContext) { var routes = await _queryExecutor.ExecuteAsync(new GetAllPageRoutesQuery(), executionContext); var ids = dbPages .Select(p => p.PageId) .ToArray(); var pageTags = await _dbContext .PageTags .AsNoTracking() .Where(p => ids.Contains(p.PageId)) .Select(t => new { PageId = t.PageId, Tag = t.Tag.TagText }) .ToListAsync(); var pages = new List <PageSummary>(ids.Length); foreach (var dbPage in dbPages) { var pageRoute = routes.SingleOrDefault(r => r.PageId == dbPage.PageId); EntityNotFoundException.ThrowIfNull(pageRoute, dbPage.PageId); var page = new PageSummary() { FullPath = pageRoute.FullPath, HasDraftVersion = pageRoute.HasDraftVersion, HasPublishedVersion = pageRoute.HasPublishedVersion, PublishDate = pageRoute.PublishDate, PublishStatus = pageRoute.PublishStatus, Locale = pageRoute.Locale, PageId = pageRoute.PageId, PageType = pageRoute.PageType, Title = pageRoute.Title, UrlPath = pageRoute.UrlPath }; page.IsPublished = page.PublishStatus == PublishStatus.Published && page.PublishDate <= executionContext.ExecutionDate; page.AuditData = _auditDataMapper.MapCreateAuditData(dbPage); if (!string.IsNullOrWhiteSpace(dbPage.CustomEntityDefinitionCode)) { var customEntityDefinition = _customEntityDefinitionRepository.GetByCode(dbPage.CustomEntityDefinitionCode); page.CustomEntityName = customEntityDefinition.Name; } page.Tags = pageTags .Where(t => t.PageId == page.PageId) .Select(t => t.Tag) .ToArray(); pages.Add(page); } return(pages); }
public IEnumerable <IPermissionApplication> GetPermissions(IsCustomEntityUrlSlugUniqueQuery query) { var definition = _customEntityDefinitionRepository.GetByCode(query.CustomEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(definition, query.CustomEntityDefinitionCode); yield return(new CustomEntityReadPermission(definition)); }
public IEnumerable <IPermissionApplication> GetPermissions(GetCustomEntityDataModelSchemaDetailsByDefinitionCodeQuery query) { var definition = _customEntityDefinitionRepository.GetByCode(query.CustomEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(definition, query.CustomEntityDefinitionCode); yield return(new CustomEntityReadPermission(definition)); }
/// <summary> /// Creates a data model type from the database id. Throws /// an InvalidOperationException if the requested type is not register /// or has been defined multiple times /// </summary> /// <param name="pageModuleTypeId">Id of the page module type in the database</param> public Type CreateByPageModuleTypeId(int pageModuleTypeId) { var moduleType = _queryExecutor.GetById <PageModuleTypeSummary>(pageModuleTypeId); EntityNotFoundException.ThrowIfNull(moduleType, pageModuleTypeId); return(CreateByPageModuleTypeFileName(moduleType.FileName)); }
private void MapDataModel(GetByIdQuery <CustomEntityDetails> query, CustomEntityVersion dbVersion, CustomEntityVersionDetails version) { var definition = _queryExecutor.GetById <CustomEntityDefinitionSummary>(dbVersion.CustomEntity.CustomEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(definition, dbVersion.CustomEntity.CustomEntityDefinitionCode); version.Model = (ICustomEntityVersionDataModel)_dbUnstructuredDataSerializer.Deserialize(dbVersion.SerializedData, definition.DataModelType); }
private void ResetAmbientUserAreaToDefault() { var defaultUserArea = _userAreaDefinitionRepository.GetDefault(); EntityNotFoundException.ThrowIfNull(defaultUserArea, "Default"); _ambientUserAreaCode = defaultUserArea.UserAreaCode; }
/// <summary> /// Creates a data model type from the database id. Throws /// an InvalidOperationException if the requested type is not register /// or has been defined multiple times /// </summary> /// <param name="pageBlockTypeId">Id of the page block type in the database</param> public async Task <Type> CreateByPageBlockTypeIdAsync(int pageBlockTypeId) { var query = new GetPageBlockTypeSummaryByIdQuery(pageBlockTypeId); var blockType = await _queryExecutor.ExecuteAsync(query); EntityNotFoundException.ThrowIfNull(blockType, pageBlockTypeId); return(CreateByPageBlockTypeFileName(blockType.FileName)); }
public ICustomEntityDataModel Map(string customEntityDefinitionCode, string serializedData) { var definition = _customEntityDefinitions.SingleOrDefault(d => d.CustomEntityDefinitionCode == customEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(definition, customEntityDefinitionCode); var dataModelType = definition.GetDataModelType(); return((ICustomEntityDataModel)_dbUnstructuredDataSerializer.Deserialize(serializedData, dataModelType)); }
private async Task <PageDirectory> GetParentDirectoryAsync(AddPageDirectoryCommand command) { var parentDirectory = await _dbContext .PageDirectories .SingleOrDefaultAsync(d => d.PageDirectoryId == command.ParentPageDirectoryId); EntityNotFoundException.ThrowIfNull(parentDirectory, command.ParentPageDirectoryId); return(parentDirectory); }
/// <summary> /// Use this to get a user context for the system user, useful /// if you need to impersonate the user to perform an action with elevated /// privileges /// </summary> public IUserContext GetSystemUserContext() { // Grab the first super admin user. var dbUser = QuerySystemUser().FirstOrDefault(); EntityNotFoundException.ThrowIfNull(dbUser, SpecialistRoleTypeCodes.SuperAdministrator); var impersonatedUserContext = _userContextMapper.Map(dbUser); return(impersonatedUserContext); }
private IQueryable <CustomEntityVersion> GetQuery(SearchCustomEntityRenderSummariesQuery query) { var definition = _queryExecutor.GetById <CustomEntityDefinitionSummary>(query.CustomEntityDefinitionCode); EntityNotFoundException.ThrowIfNull(definition, query.CustomEntityDefinitionCode); var dbQuery = _dbContext .CustomEntityVersions .AsNoTracking() .Where(e => e.CustomEntity.CustomEntityDefinitionCode == query.CustomEntityDefinitionCode) .Where(v => v.WorkFlowStatusId == (int)Domain.WorkFlowStatus.Draft || v.WorkFlowStatusId == (int)Domain.WorkFlowStatus.Published) .GroupBy(e => e.CustomEntityId, (key, g) => g.OrderByDescending(v => v.WorkFlowStatusId == (int)Domain.WorkFlowStatus.Draft).FirstOrDefault()) .Include(e => e.CustomEntity); // Filter by locale if (query.LocaleId > 0) { dbQuery = dbQuery.Where(p => p.CustomEntity.LocaleId == query.LocaleId); } else { dbQuery = dbQuery.Where(p => !p.CustomEntity.LocaleId.HasValue); } switch (query.SortBy) { case CustomEntityQuerySortType.Default: case CustomEntityQuerySortType.Natural: if (definition.Ordering != CustomEntityOrdering.None) { dbQuery = dbQuery .OrderByWithSortDirection(e => !e.CustomEntity.Ordering.HasValue, query.SortDirection) .ThenByWithSortDirection(e => e.CustomEntity.Ordering, query.SortDirection) .ThenByDescendingWithSortDirection(e => e.CreateDate, query.SortDirection); } else { dbQuery = dbQuery .OrderByDescendingWithSortDirection(e => e.CreateDate, query.SortDirection); } break; case CustomEntityQuerySortType.Title: dbQuery = dbQuery .OrderByWithSortDirection(e => e.Title, query.SortDirection); break; case CustomEntityQuerySortType.CreateDate: dbQuery = dbQuery .OrderByDescendingWithSortDirection(e => e.CreateDate, query.SortDirection); break; } return(dbQuery); }
private RoleDetails GetAnonymousRole() { return(_roleCache.GetOrAddAnonymousRole(() => { var dbRole = QueryAnonymousRole().FirstOrDefault(); EntityNotFoundException.ThrowIfNull(dbRole, SpecialistRoleTypeCodes.Anonymous); var role = _roleMappingHelper.MapDetails(dbRole); return role; })); }
private void UpdateDraft(UpdatePageDraftVersionCommand command, PageVersion draft) { EntityNotFoundException.ThrowIfNull(draft, "Draft:" + command.PageId); draft.Title = command.Title; draft.ExcludeFromSitemap = !command.ShowInSiteMap; draft.MetaDescription = command.MetaDescription ?? string.Empty; draft.OpenGraphTitle = command.OpenGraphTitle; draft.OpenGraphDescription = command.OpenGraphDescription; draft.OpenGraphImageId = command.OpenGraphImageId; }
private List <PageRoute> Map( List <PageQueryResult> dbPages, List <PageVersionQueryResult> dbPageVersions, Dictionary <int, PageDirectoryRoute> pageDirectories, Dictionary <int, PageTemplateQueryResult> templates, ICollection <ActiveLocale> activeLocales ) { var routes = new List <PageRoute>(); foreach (var dbPage in dbPages) { var pageRoute = dbPage.RoutingInfo; // Page directory will be null if it is inactive or has an inactive parent. pageRoute.PageDirectory = pageDirectories.GetOrDefault(dbPage.PageDirectoryId); if (pageRoute.PageDirectory == null) { continue; } // Configure Version Info SetPageVersions(pageRoute, dbPageVersions, templates); if (!pageRoute.Versions.Any()) { continue; } // Configure Locale string directoryPath = null; if (dbPage.LocaleId.HasValue) { pageRoute.Locale = activeLocales.FirstOrDefault(l => l.LocaleId == dbPage.LocaleId.Value); EntityNotFoundException.ThrowIfNull(pageRoute.Locale, dbPage.LocaleId); directoryPath = pageRoute .PageDirectory .LocaleVariations .Where(v => v.LocaleId == pageRoute.Locale.LocaleId) .Select(v => v.FullUrlPath) .FirstOrDefault(); } if (directoryPath == null) { directoryPath = pageRoute.PageDirectory.FullUrlPath; } // Set Full Path pageRoute.FullPath = CreateFullPath(directoryPath, pageRoute.UrlPath, pageRoute.Locale); routes.Add(pageRoute); } return(routes); }
public Role GetAndValidateNewRole(int roleId, string userAreaCode, IExecutionContext executionContext) { var executorRole = GetExecutorRole(executionContext); var newRole = QueryRole(roleId).SingleOrDefault(); EntityNotFoundException.ThrowIfNull(newRole, roleId); ValidateRole(userAreaCode, newRole, executorRole); return(newRole); }
public async Task ExecuteAsync(UpdatePageCommand command, IExecutionContext executionContext) { var page = await GetPageById(command.PageId).SingleOrDefaultAsync(); EntityNotFoundException.ThrowIfNull(page, command.PageId); MapPage(command, executionContext, page); await _dbContext.SaveChangesAsync(); await _transactionScopeFactory.QueueCompletionTaskAsync(_dbContext, () => OnTransactionComplete(page)); }
public async Task <Role> GetAndValidateNewRoleAsync(int roleId, string userAreaCode, IExecutionContext executionContext) { var executorRole = await GetExecutorRoleAsync(executionContext); var newRole = await QueryRole(roleId).SingleOrDefaultAsync(); EntityNotFoundException.ThrowIfNull(newRole, roleId); ValidateRole(userAreaCode, newRole, executorRole); return(newRole); }
public async Task RemoveAccountAsync(Guid accountId) { var accountRepository = _unitOfWork.GetRepository <AccountModel>(); var removingEntity = await accountRepository.FindAsync(accountId); EntityNotFoundException.ThrowIfNull(removingEntity, accountId); accountRepository.Delete(removingEntity); await _unitOfWork.SaveChangesAsync(); }
public async Task <AccountModel> GetAccountAsync(Guid accountId) { var accountRepository = _unitOfWork.GetRepository <AccountModel>(); var account = await accountRepository.GetFirstOrDefaultAsync( predicate : a => a.Id == accountId, include : q => q.Include(a => a.OwnerUser).Include(a => a.AccountType)); EntityNotFoundException.ThrowIfNull(account, accountId); return(account); }
private List <WebDirectoryRoute> Map(List <WebDirectoryRoute> allWebDirectories) { var root = allWebDirectories.SingleOrDefault(r => !r.ParentWebDirectoryId.HasValue); EntityNotFoundException.ThrowIfNull(root, "ROOT"); var activeWebRoutes = SetChildRoutes(root, allWebDirectories).ToList(); root.FullUrlPath = "/"; return(activeWebRoutes); }
private Task <RoleDetails> GetAnonymousRoleAsync() { return(_roleCache.GetOrAddAnonymousRoleAsync(async() => { var dbRole = await QueryAnonymousRole().FirstOrDefaultAsync(); EntityNotFoundException.ThrowIfNull(dbRole, AnonymousRole.AnonymousRoleCode); var role = _roleMappingHelper.Map(dbRole); return role; })); }