private IEnumerable <CustomEntityRenderSummary> Map(
            ICollection <CustomEntityVersion> dbResults,
            IDictionary <int, IEnumerable <PageRoutingInfo> > allRoutings,
            IEnumerable <ActiveLocale> allLocalesAsEnumerable
            )
        {
            var results    = new List <CustomEntityRenderSummary>(dbResults.Count);
            var allLocales = allLocalesAsEnumerable.ToDictionary(l => l.LocaleId);

            foreach (var dbResult in dbResults)
            {
                var entity = Mapper.Map <CustomEntityRenderSummary>(dbResult);

                if (dbResult.CustomEntity.LocaleId.HasValue)
                {
                    entity.Locale = allLocales.GetOrDefault(dbResult.CustomEntity.LocaleId.Value);
                    EntityNotFoundException.ThrowIfNull(entity.Locale, dbResult.CustomEntity.LocaleId.Value);
                }

                entity.DetailsPageUrls = MapPageRoutings(allRoutings.GetOrDefault(dbResult.CustomEntityId), dbResult);
                entity.Model           = _customEntityDataModelMapper.Map(dbResult.CustomEntity.CustomEntityDefinitionCode, dbResult.SerializedData);

                results.Add(entity);
            }

            return(results);
        }
Exemple #2
0
        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  = false;
            user.LastPasswordChangeDate = executionContext.ExecutionDate;
            user.CreateDate             = executionContext.ExecutionDate;
            user.Role = superUserRole;

            var hashResult = _passwordCryptographyService.CreateHash(command.Password);

            user.Password = hashResult.Hash;
            user.PasswordEncryptionVersion = (int)hashResult.EncryptionVersion;

            user.UserArea = userArea;
            EntityNotFoundException.ThrowIfNull(user.UserArea, CofoundryAdminUserArea.AreaCode);

            _dbContext.Users.Add(user);

            return(user);
        }
        private ICollection <CustomEntityRenderSummary> Map(
            ICollection <CustomEntityVersion> dbResults,
            IDictionary <int, ICollection <PageRoutingInfo> > allRoutings,
            ICollection <ActiveLocale> allLocalesAsEnumerable
            )
        {
            var results    = new List <CustomEntityRenderSummary>(dbResults.Count);
            var allLocales = allLocalesAsEnumerable.ToDictionary(l => l.LocaleId);

            foreach (var dbResult in dbResults)
            {
                var entity = MapCore(dbResult);

                if (dbResult.CustomEntity.LocaleId.HasValue)
                {
                    entity.Locale = allLocales.GetOrDefault(dbResult.CustomEntity.LocaleId.Value);
                    EntityNotFoundException.ThrowIfNull(entity.Locale, dbResult.CustomEntity.LocaleId.Value);
                }

                entity.PageUrls = MapPageRoutings(allRoutings.GetOrDefault(dbResult.CustomEntityId), dbResult);

                results.Add(entity);
            }

            return(results);
        }
        public async Task ExecuteAsync(AddCustomEntityDraftVersionCommand command, IExecutionContext executionContext)
        {
            var definitionCode = await QueryVersionAndGetDefinitionCode(command).FirstOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(definitionCode, command.CustomEntityId);

            _permissionValidationService.EnforceCustomEntityPermission <CustomEntityUpdatePermission>(definitionCode);

            var newVersionId = await _entityFrameworkSqlExecutor
                               .ExecuteCommandWithOutputAsync <int?>("Cofoundry.CustomEntity_AddDraft",
                                                                     "CustomEntityVersionId",
                                                                     new SqlParameter("CustomEntityId", command.CustomEntityId),
                                                                     new SqlParameter("CopyFromCustomEntityVersionId", command.CopyFromCustomEntityVersionId),
                                                                     new SqlParameter("CreateDate", executionContext.ExecutionDate),
                                                                     new SqlParameter("CreatorId", executionContext.UserContext.UserId)
                                                                     );

            if (!newVersionId.HasValue)
            {
                throw new UnexpectedSqlStoredProcedureResultException("Cofoundry.CustomEntity_AddDraft", "No CustomEntityVersionId was returned.");
            }

            command.OutputCustomEntityVersionId = newVersionId.Value;
            _customEntityCache.Clear(definitionCode, command.CustomEntityId);

            await _messageAggregator.PublishAsync(new CustomEntityDraftVersionAddedMessage()
            {
                CustomEntityId             = command.CustomEntityId,
                CustomEntityVersionId      = newVersionId.Value,
                CustomEntityDefinitionCode = definitionCode
            });
        }
Exemple #5
0
        private void SetDraftVersionPublished(PublishPageCommand command, List <PageVersion> pageVersions)
        {
            var draftVersion = pageVersions.SingleOrDefault(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Draft);

            EntityNotFoundException.ThrowIfNull(draftVersion, "Draft:" + command.PageId);
            draftVersion.WorkFlowStatusId = (int)WorkFlowStatus.Published;
        }
        public async Task Update(Guid id, ProductModel model)
        {
            var query = _readOnlyRepository.Query <Product>(x => x.Id.Equals(id))
                        .ProjectTo <ProductModel>(_mapper.ConfigurationProvider);

            var result = await _readOnlyRepository.SingleAsync(query);

            if (result != null)
            {
                //result.Id = id;
                //result.ProductName = model.ProductName;
                //result.Description = model.Description;
                //result.Characteristics = model.Characteristics;
                //result.Price = model.Price;
                ////result.Category = model.Category;
                //result.CategoryId = model.CategoryId;
                var entity = _mapper.Map <Product>(model);
                entity.Id         = id;
                entity.CategoryId = model.CategoryId;
                _repository.Update(entity);

                await _repository.SaveChangesAsync();
            }
            else
            {
                throw EntityNotFoundException.For <Product>(id);
            }
        }
        public void And_Using_Message_Ctor_Then_Sets_Message_From_Param(
            string message)
        {
            var exception = new EntityNotFoundException <TestEntity>(message);

            exception.Message.Should().Be(message);
        }
Exemple #8
0
        private async Task <CustomEntityVersionPageBlockRenderDetails> MapAsync(
            CustomEntityVersionPageBlock versionBlock,
            string blockTypeFileName,
            string customEntityDefinitionCode,
            PublishStatusQuery publishStatus,
            IExecutionContext executionContext
            )
        {
            _permissionValidationService.EnforceCustomEntityPermission <CustomEntityReadPermission>(customEntityDefinitionCode, executionContext.UserContext);

            var blockTypeQuery = new GetPageBlockTypeSummaryByIdQuery(versionBlock.PageBlockTypeId);
            var blockType      = await _queryExecutor.ExecuteAsync(blockTypeQuery, executionContext);

            EntityNotFoundException.ThrowIfNull(blockType, versionBlock.PageBlockTypeId);

            var result = new CustomEntityVersionPageBlockRenderDetails();

            result.CustomEntityVersionPageBlockId = versionBlock.CustomEntityVersionPageBlockId;
            result.BlockType    = blockType;
            result.DisplayModel = await _pageVersionBlockModelMapper.MapDisplayModelAsync(
                blockTypeFileName,
                versionBlock,
                publishStatus,
                executionContext
                );

            return(result);
        }
Exemple #9
0
 public EntityNotExistsDetails(EntityNotFoundException exception)
 {
     Title  = $"Can't find {exception.TypeName}.";
     Status = StatusCodes.Status404NotFound;
     Detail = exception.Message;
     Type   = $"https://httpstatuses.com/{Status}";
 }
Exemple #10
0
        public async Task ExecuteAsync(UpdateCustomEntityUrlCommand command, IExecutionContext executionContext)
        {
            var entity = await _dbContext
                         .CustomEntities
                         .Where(e => e.CustomEntityId == command.CustomEntityId)
                         .SingleOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(entity, command.CustomEntityId);
            _permissionValidationService.EnforceCustomEntityPermission <CustomEntityUpdateUrlPermission>(entity.CustomEntityDefinitionCode, executionContext.UserContext);

            var definitionQuery = new GetCustomEntityDefinitionSummaryByCodeQuery(entity.CustomEntityDefinitionCode);
            var definition      = await _queryExecutor.ExecuteAsync(definitionQuery, executionContext);

            EntityNotFoundException.ThrowIfNull(definition, entity.CustomEntityDefinitionCode);

            await ValidateIsUniqueAsync(command, definition, executionContext);

            Map(command, entity, definition);

            await _dbContext.SaveChangesAsync();

            _customEntityCache.Clear(entity.CustomEntityDefinitionCode, command.CustomEntityId);

            await _messageAggregator.PublishAsync(new CustomEntityUrlChangedMessage()
            {
                CustomEntityId             = command.CustomEntityId,
                CustomEntityDefinitionCode = entity.CustomEntityDefinitionCode,
                HasPublishedVersionChanged = entity.PublishStatusCode == PublishStatusCode.Published
            });
        }
        public async Task <ProductsModel> Get(Guid id)
        {
            var query = _readOnlyRepository.Query <Product>(x => x.Id == id && x.Status == EnabledStatus.Enabled)
                        .ProjectTo <ProductsModel>(_mapper.ConfigurationProvider);

            var queryCategory = _readOnlyRepository.Query <ProductCat>(x => x.Status == EnabledStatus.Enabled && x.ProductId == id, y => y.Category).ToList();



            var result = await _readOnlyRepository.SingleAsync(query);

            if (result == null)
            {
                throw EntityNotFoundException.For <Product>(id);
            }


            if (result.ProductDetails != null)
            {
                result.ProductDetails = result.ProductDetails.Where(x => x.Status == EnabledStatus.Enabled).ToList();
            }


            result.Categories = new List <Category>();

            queryCategory.ForEach(x => {
                result.Categories.Add(new Category {
                    Id          = x.Category.Id,
                    Name        = x.Category.Name,
                    Description = x.Category.Description
                });
            });
            return(result);
        }
        private async Task <IDictionary <int, ICollection <PageRoutingInfo> > > MapAsync(IExecutionContext executionContext, List <IdQueryResult> idSets, Dictionary <int, CustomEntityRoute> customEntityRoutes, IDictionary <int, PageRoute> pageRoutes)
        {
            var allRules = await _queryExecutor.ExecuteAsync(new GetAllCustomEntityRoutingRulesQuery(), executionContext);

            var result = new List <PageRoutingInfo>(idSets.Count);

            foreach (var idSet in idSets)
            {
                var routingInfo = new PageRoutingInfo();

                routingInfo.PageRoute = pageRoutes.GetOrDefault(idSet.PageId);
                EntityNotFoundException.ThrowIfNull(routingInfo.PageRoute, idSet.PageId);

                routingInfo.CustomEntityRoute = customEntityRoutes.GetOrDefault(idSet.CustomEntityId);
                EntityNotFoundException.ThrowIfNull(routingInfo.CustomEntityRoute, idSet.PageId);

                routingInfo.CustomEntityRouteRule = allRules.FirstOrDefault(r => r.RouteFormat == routingInfo.PageRoute.UrlPath);

                result.Add(routingInfo);
            }

            var groupedResult = result
                                .GroupBy(r => r.CustomEntityRoute.CustomEntityId)
                                .ToDictionary(g => g.Key, g => (ICollection <PageRoutingInfo>)g.ToList());

            return(groupedResult);
        }
Exemple #13
0
        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);
        }
Exemple #14
0
        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();
            }
        }
        public async Task <UpdateCustomEntityDraftVersionCommand> ExecuteAsync(GetPatchableCommandByIdQuery <UpdateCustomEntityDraftVersionCommand> query, IExecutionContext executionContext)
        {
            var dbResult = await _dbContext
                           .CustomEntityVersions
                           .Include(v => v.CustomEntity)
                           .AsNoTracking()
                           .FilterActive()
                           .FilterByCustomEntityId(query.Id)
                           .Where(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Draft)
                           .SingleOrDefaultAsync();

            if (dbResult == null)
            {
                return(null);
            }
            _permissionValidationService.EnforceCustomEntityPermission <CustomEntityReadPermission>(dbResult.CustomEntity.CustomEntityDefinitionCode, executionContext.UserContext);

            var command = new UpdateCustomEntityDraftVersionCommand()
            {
                CustomEntityDefinitionCode = dbResult.CustomEntity.CustomEntityDefinitionCode,
                CustomEntityId             = dbResult.CustomEntityId,
                Title = dbResult.Title
            };

            var definitionQuery = new GetCustomEntityDefinitionSummaryByCodeQuery(command.CustomEntityDefinitionCode);
            var definition      = await _queryExecutor.ExecuteAsync(definitionQuery, executionContext);

            EntityNotFoundException.ThrowIfNull(definition, command.CustomEntityDefinitionCode);
            command.Model = (ICustomEntityDataModel)_dbUnstructuredDataSerializer.Deserialize(dbResult.SerializedData, definition.DataModelType);

            return(command);
        }
        public async Task UpdateModelAsync(IPageVersionModuleDataModelCommand command, IEntityVersionPageModule dbModule)
        {
            if (command.PageModuleTypeId != dbModule.PageModuleTypeId)
            {
                var pageTemplateSectionId = dbModule.PageTemplateSection != null ? dbModule.PageTemplateSection.PageTemplateSectionId : dbModule.PageTemplateSectionId;
                var pageModuleType        = await _dbContext
                                            .PageModuleTypes
                                            .Where(m => m.PageModuleTypeId == command.PageModuleTypeId)
                                            .SingleOrDefaultAsync();

                EntityNotFoundException.ThrowIfNull(pageModuleType, command.PageModuleTypeId);
                dbModule.PageModuleType = pageModuleType;
            }

            dbModule.SerializedData = _dbUnstructuredDataSerializer.Serialize(command.DataModel);

            if (command.PageModuleTypeTemplateId != dbModule.PageModuleTypeTemplateId && command.PageModuleTypeTemplateId.HasValue)
            {
                dbModule.PageModuleTypeTemplate = await _dbContext
                                                  .PageModuleTypeTemplates
                                                  .SingleOrDefaultAsync(m => m.PageModuleTypeId == command.PageModuleTypeId && m.PageModuleTypeTemplateId == command.PageModuleTypeTemplateId);

                EntityNotFoundException.ThrowIfNull(dbModule.PageModuleTypeTemplate, command.PageModuleTypeTemplateId);
            }
            else if (command.PageModuleTypeTemplateId != dbModule.PageModuleTypeTemplateId)
            {
                dbModule.PageModuleTypeTemplate = null;
            }
        }
Exemple #17
0
        public override async Task <KioskVersionGetResponse> ExecuteAsync(EmptyRequest request)
        {
            var kioskId = _currentUser.Id;

            var kioskData = await _kioskManager.GetActiveKiosksQuery()
                            .Where(x => x.Id == kioskId)
                            .Select(x => new
            {
                x.ApplicationType,
                x.AssignedKioskVersion,
            })
                            .FirstOrDefaultAsync();

            if (kioskData == null)
            {
                throw EntityNotFoundException.Create <Entities.Kiosk>(kioskId);
            }

            var response = new KioskVersionGetResponse()
            {
                AssignedKioskVersion = kioskData.AssignedKioskVersion,
            };

            if (!string.IsNullOrEmpty(response.AssignedKioskVersion))
            {
                response.AssignedKioskVersionUpdateUrl = await _kioskVersionUpdateManager.GetUpdateUrlAsync(
                    kioskData.ApplicationType,
                    response.AssignedKioskVersion);
            }

            return(response);
        }
        public async Task ExecuteAsync(UpdatePageVersionBlockCommand command, IExecutionContext executionContext)
        {
            var dbBlock = await _dbContext
                          .PageVersionBlocks
                          .Include(m => m.PageBlockTypeTemplate)
                          .Include(m => m.PageBlockType)
                          .Include(m => m.PageVersion)
                          .Where(l => l.PageVersionBlockId == command.PageVersionBlockId)
                          .SingleOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(dbBlock, command.PageVersionBlockId);

            if (dbBlock.PageVersion.WorkFlowStatusId != (int)WorkFlowStatus.Draft)
            {
                throw new NotPermittedException("Page blocks cannot be updated unless the page version is in draft status");
            }

            if (command.PageBlockTypeId != dbBlock.PageBlockTypeId)
            {
                var pageBlockType = await _dbContext
                                    .PageBlockTypes
                                    .Where(m => m.PageBlockTypeId == command.PageBlockTypeId)
                                    .SingleOrDefaultAsync();

                EntityNotFoundException.ThrowIfNull(pageBlockType, command.PageBlockTypeId);
                dbBlock.PageBlockType = pageBlockType;
            }

            dbBlock.SerializedData = _dbUnstructuredDataSerializer.Serialize(command.DataModel);
            dbBlock.UpdateDate     = executionContext.ExecutionDate;

            if (command.PageBlockTypeTemplateId != dbBlock.PageBlockTypeTemplateId && command.PageBlockTypeTemplateId.HasValue)
            {
                dbBlock.PageBlockTypeTemplate = await _dbContext
                                                .PageBlockTypeTemplates
                                                .SingleOrDefaultAsync(m => m.PageBlockTypeId == dbBlock.PageBlockTypeId && m.PageBlockTypeTemplateId == command.PageBlockTypeTemplateId);

                EntityNotFoundException.ThrowIfNull(dbBlock.PageBlockTypeTemplate, command.PageBlockTypeTemplateId);
            }
            else if (command.PageBlockTypeTemplateId != dbBlock.PageBlockTypeTemplateId)
            {
                dbBlock.PageBlockTypeTemplate = null;
            }

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                await _dbContext.SaveChangesAsync();

                var dependencyCommand = new UpdateUnstructuredDataDependenciesCommand(
                    PageVersionBlockEntityDefinition.DefinitionCode,
                    dbBlock.PageVersionBlockId,
                    command.DataModel);

                await _commandExecutor.ExecuteAsync(dependencyCommand, executionContext);

                scope.QueueCompletionTask(() => OnTransactionComplete(dbBlock));

                await scope.CompleteAsync();
            }
        }
 /// <summary>
 /// Deletes the <see cref="TViewModel"/> with the specified identifier.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <returns></returns>
 public async Task DeleteAsync(string id)
 {
     if (!await Repository.DeleteAsync(id, RequestAborted))
     {
         throw EntityNotFoundException.Create <TEntity>(x => x.Id, id);
     }
 }
Exemple #20
0
        private void SetCustomModelTypeFields(PageTemplateFileInfo pageTemplateFileInfo, string line, IExecutionContext ex)
        {
            const string CUSTOM_ENTITY_MODEL_REGEX = @"CustomEntityDetailsPageViewModel<(\w+)";

            var match = Regex.Match(line, CUSTOM_ENTITY_MODEL_REGEX);

            if (match.Success)
            {
                var modelType = _pageTemplateCustomEntityTypeMapper.Map(match.Groups[1].Value);

                if (modelType == null)
                {
                    throw new ApplicationException("ICustomEntityDisplayModel<T> of type " + match.Value + " not registered");
                }

                var query = new GetCustomEntityDefinitionMicroSummaryByDisplayModelTypeQuery();
                query.DisplayModelType = modelType;

                pageTemplateFileInfo.CustomEntityDefinition = _queryExecutor.Execute(query, ex);
                EntityNotFoundException.ThrowIfNull(pageTemplateFileInfo.CustomEntityDefinition, modelType);
                pageTemplateFileInfo.CustomEntityModelType = match.Groups[1].Value;

                pageTemplateFileInfo.PageType = PageType.CustomEntityDetails;
            }
        }
        private CustomEntityDefinitionSummary GetCustomEntityDefinition(AddCustomEntityCommand command)
        {
            var definition = _queryExecutor.GetById <CustomEntityDefinitionSummary>(command.CustomEntityDefinitionCode);

            EntityNotFoundException.ThrowIfNull(definition, command.CustomEntityDefinitionCode);
            return(definition);
        }
        private async Task SetCustomModelTypeFieldsAsync(
            PageTemplateFileInfo pageTemplateFileInfo,
            string line,
            IExecutionContext executionContext
            )
        {
            // This regex find models with generic parameters and captures the last generic type
            // This could be the custom entity display model type and may have a namespace prefix
            const string CUSTOM_ENTITY_MODEL_REGEX = @"\s*@(?:inherits|model)\s+[\w+<.]*<([\w\.]+)";

            var match = Regex.Match(line, CUSTOM_ENTITY_MODEL_REGEX);

            if (match.Success)
            {
                // Try and find a matching custom entity model type.
                var modelType = _pageTemplateCustomEntityTypeMapper.Map(match.Groups[1].Value);

                if (modelType == null)
                {
                    return;
                }

                var query = new GetCustomEntityDefinitionMicroSummaryByDisplayModelTypeQuery();
                query.DisplayModelType = modelType;

                pageTemplateFileInfo.CustomEntityDefinition = await _queryExecutor.ExecuteAsync(query, executionContext);

                EntityNotFoundException.ThrowIfNull(pageTemplateFileInfo.CustomEntityDefinition, modelType);
                pageTemplateFileInfo.CustomEntityModelType = match.Groups[1].Value;

                pageTemplateFileInfo.PageType = PageType.CustomEntityDetails;
            }
        }
Exemple #23
0
        public async Task <UpdatePageDirectoryCommand> ExecuteAsync(GetUpdateCommandByIdQuery <UpdatePageDirectoryCommand> query, IExecutionContext executionContext)
        {
            var dbResult = await _dbContext
                           .PageDirectories
                           .AsNoTracking()
                           .Where(w => w.PageDirectoryId == query.Id && w.IsActive)
                           .SingleOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(dbResult, query.Id);

            if (!dbResult.ParentPageDirectoryId.HasValue)
            {
                throw new NotPermittedException("The root directory cannot be updated.");
            }

            var command = new UpdatePageDirectoryCommand()
            {
                Name                  = dbResult.Name,
                PageDirectoryId       = dbResult.PageDirectoryId,
                ParentPageDirectoryId = dbResult.ParentPageDirectoryId.Value,
                UrlPath               = dbResult.UrlPath
            };

            return(command);
        }
Exemple #24
0
        private async Task UpdateTemplates(
            IExecutionContext executionContext,
            ILookup <string, PageTemplate> dbPageTemplates,
            ICollection <PageTemplateFile> fileTemplates
            )
        {
            foreach (var fileTemplate in fileTemplates)
            {
                var fileTemplateDetails = await _queryExecutor.ExecuteAsync(new GetPageTemplateFileInfoByPathQuery(fileTemplate.VirtualPath), executionContext);

                EntityNotFoundException.ThrowIfNull(fileTemplateDetails, fileTemplate.VirtualPath);
                var dbPageTemplate = EnumerableHelper.Enumerate(dbPageTemplates[fileTemplate.FileName])
                                     .OrderBy(t => t.IsArchived)
                                     .ThenByDescending(t => t.UpdateDate)
                                     .FirstOrDefault();

                // Run this first because it may commit changes
                await EnsureCustomEntityDefinitionExistsAsync(fileTemplateDetails, dbPageTemplate, executionContext);

                dbPageTemplate = await UpdateTemplate(executionContext, dbPageTemplate, fileTemplate, fileTemplateDetails);

                // No need to update archived template regions
                if (dbPageTemplate.IsArchived)
                {
                    continue;
                }

                // Update Regions
                UpdateRegions(fileTemplate, fileTemplateDetails, dbPageTemplate, executionContext);
            }
        }
        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var code = exception switch
            {
                DisabledWorkerException _ => HttpStatusCode.Forbidden,
                EntityNotFoundException _ => HttpStatusCode.NotFound,
                InvalidParameterFormatException _ => HttpStatusCode.BadRequest,
                _ => HttpStatusCode.InternalServerError,
            };

            var response = new ResponseDto <object>
            {
                Succeeded = false,
                Errors    = new List <string>()
                {
                    exception.GetaAllMessages()
                }
            };

            var result = JsonConvert.SerializeObject(response,
                                                     new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(result));
        }
Exemple #26
0
        private async Task UpdateTemplates(
            IExecutionContext executionContext,
            Dictionary <string, PageTemplate> dbPageTemplates,
            IEnumerable <PageTemplateFile> fileTemplates
            )
        {
            foreach (var fileTemplate in fileTemplates)
            {
                var fileTemplateDetails = await _queryExecutor.ExecuteAsync(new GetPageTemplateFileInfoByPathQuery(fileTemplate.FullPath), executionContext);

                EntityNotFoundException.ThrowIfNull(fileTemplateDetails, fileTemplate.FullPath);
                var dbPageTemplate = dbPageTemplates.GetOrDefault(fileTemplate.FileName);

                // Run this first because it may commit changes
                await EnsureCustomEntityDefinitionExists(fileTemplateDetails, dbPageTemplate);

                dbPageTemplate = await UpdateTemplate(executionContext, dbPageTemplate, fileTemplate, fileTemplateDetails);

                // No need to update archived template sections
                if (dbPageTemplate.IsArchived)
                {
                    continue;
                }

                // Update Sections
                UpdateSections(fileTemplate, fileTemplateDetails, dbPageTemplate, executionContext);
            }
        }
Exemple #27
0
        protected virtual Location HandleLocationNotFound(PL patientLocation, EntityNotFoundException e)
        {
            string   locationName = patientLocation.PointOfCare.Value;
            Facility facility;

            try
            {
                facility = FindFacility(patientLocation.Facility.NamespaceID.Value, PersistenceContext);
            }
            catch (Exception)
            {
                facility = null;
            }

            var location = new Location
            {
                Id          = locationName,
                Name        = locationName,
                PointOfCare = locationName,
                Facility    = facility,
                Deactivated = false,
                Description = "HL7"
            };

            PersistenceContext.Lock(location, DirtyState.New);
            return(location);
        }
        private void UpdateDraft(UpdateCustomEntityDraftVersionCommand command, CustomEntityVersion draft)
        {
            EntityNotFoundException.ThrowIfNull(draft, "Draft:" + command.CustomEntityId);

            draft.Title          = command.Title.Trim();
            draft.SerializedData = _dbUnstructuredDataSerializer.Serialize(command.Model);
        }
Exemple #29
0
        public async Task ExecuteAsync(AddMasterCofoundryUserCommand command, IExecutionContext executionContext)
        {
            var settings = _queryExecutor.Get <InternalSettings>();

            if (settings.IsSetup)
            {
                throw new ValidationException("Site is already set up.");
            }

            if (await _dbContext
                .Users
                .FilterCanLogIn()
                .AnyAsync(u => u.Role.SpecialistRoleTypeCode == SpecialistRoleTypeCodes.SuperAdministrator))
            {
                throw new ValidationException("Cannot create a master user when master users already exist in the database.");
            }

            var role = await _dbContext
                       .Roles
                       .SingleOrDefaultAsync(r => r.SpecialistRoleTypeCode == SpecialistRoleTypeCodes.SuperAdministrator);

            EntityNotFoundException.ThrowIfNull(role, SpecialistRoleTypeCodes.SuperAdministrator);

            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;
        }
Exemple #30
0
        public async Task ExecuteAsync(DeleteUnstructuredDataDependenciesCommand command, IExecutionContext executionContext)
        {
            string entityName;

            var entityDefinition = _entityDefinitionRepository.GetByCode(command.RootEntityDefinitionCode);

            EntityNotFoundException.ThrowIfNull(entityDefinition, command.RootEntityDefinitionCode);
            entityName = entityDefinition.Name;

            var query        = new GetEntityDependencySummaryByRelatedEntityQuery(command.RootEntityDefinitionCode, command.RootEntityId);
            var dependencies = await _queryExecutor.ExecuteAsync(query, executionContext);

            var requiredDependency = dependencies.FirstOrDefault(d => !d.CanDelete);

            if (requiredDependency != null)
            {
                throw new ValidationException(
                          string.Format("Cannot delete this {0} because {1} '{2}' has a dependency on it.",
                                        entityName,
                                        requiredDependency.Entity.EntityDefinitionName.ToLower(),
                                        requiredDependency.Entity.RootEntityTitle));
            }

            await _entityFrameworkSqlExecutor
            .ExecuteCommandAsync(_dbContext,
                                 "Cofoundry.UnstructuredDataDependency_Delete",
                                 new SqlParameter("EntityDefinitionCode", command.RootEntityDefinitionCode),
                                 new SqlParameter("EntityId", command.RootEntityId)
                                 );
        }
        public void GivenExceptionHasBeenHandled_AndExceptionIsEntityNotFoundException_WhenOnException_ThenResultNull_AndStatusNotChanged()
        {
            EntityNotFoundException exception = new EntityNotFoundException();
            ExceptionContext context = ControllerContextFactory.CreateExceptionContext(MockHttpContext, exception);
            context.ExceptionHandled = true;

            Target.OnException(context);

            Assert.IsInstanceOfType(context.Result, typeof(EmptyResult));
            MockHttpContext.Response.AssertWasNotCalled(m => m.StatusCode = Arg<int>.Is.Anything);
        }
        public void GivenExceptionIsEntityNotFoundException_WhenOnException_ThenHttpNotFound()
        {
            EntityNotFoundException exception = new EntityNotFoundException();
            ExceptionContext context = ControllerContextFactory.CreateExceptionContext(MockHttpContext, exception);

            Target.OnException(context);

            HttpNotFoundResult actual = context.Result as HttpNotFoundResult;
            Assert.IsNotNull(actual);
            MockHttpContext.Response.AssertWasCalled(m => m.StatusCode = 404);
        }
        public void GivenExceptionIsEntityNotFoundException_WhenOnException_ThenExceptionHandled()
        {
            EntityNotFoundException exception = new EntityNotFoundException();
            ExceptionContext context = ControllerContextFactory.CreateExceptionContext(MockHttpContext, exception);

            Target.OnException(context);

            Assert.IsTrue(context.ExceptionHandled);
        }
        public void GivenExceptionIsEntityNotFoundException_WhenOnException_ThenHttpDescriptionIsExceptionMessage()
        {
            string expected = "blah blah exception message and stuff";
            EntityNotFoundException exception = new EntityNotFoundException(expected);
            ExceptionContext context = ControllerContextFactory.CreateExceptionContext(MockHttpContext, exception);

            Target.OnException(context);

            HttpStatusCodeResult actual = context.Result as HttpStatusCodeResult;
            Assert.AreEqual(expected, actual.StatusDescription);
        }
        public void GivenResponseHasBeenWrittenTo_ExceptionIsEntityNotFoundException_WhenOnException_ThenResponseHasBeenCleared()
        {
            EntityNotFoundException exception = new EntityNotFoundException();
            ExceptionContext context = ControllerContextFactory.CreateExceptionContext(MockHttpContext, exception);

            Target.OnException(context);

            MockHttpContext.Response.AssertWasCalled(m => m.Clear());
        }