public IList <CategoryFascicleRight> GetByIdCategoryRoleRestricted(int idCategory)
        {
            Category         category            = null;
            CategoryFascicle categoryFascicle    = null;
            IList <CategoryFascicleRight> result = NHibernateSession.QueryOver <CategoryFascicleRight>()
                                                   .Inner.JoinAlias(x => x.CategoryFascicle, () => categoryFascicle)
                                                   .Inner.JoinAlias(x => x.CategoryFascicle.Category, () => category)
                                                   .Where((x) => category.Id == idCategory && x.Role != null)
                                                   .List <CategoryFascicleRight>();

            return(result);
        }
        public bool HasRoles(int idCategory)
        {
            Category         category         = null;
            CategoryFascicle categoryFascicle = null;
            int result = NHibernateSession.QueryOver <CategoryFascicleRight>()
                         .Inner.JoinAlias(x => x.CategoryFascicle, () => categoryFascicle)
                         .Inner.JoinAlias(x => x.CategoryFascicle.Category, () => category)
                         .Where(x => category.Id == idCategory && x.Role != null)
                         .RowCount();

            return(result > 0);
        }
        public bool HasSpecialRole(int idCategory)
        {
            Category         category         = null;
            CategoryFascicle categoryFascicle = null;
            Role             role             = null;
            int result = NHibernateSession.QueryOver <CategoryFascicleRight>()
                         .Inner.JoinAlias(x => x.CategoryFascicle, () => categoryFascicle)
                         .Inner.JoinAlias(x => x.CategoryFascicle.Category, () => category)
                         .Inner.JoinAlias(x => x.Role, () => role)
                         .Where(() => category.Id == idCategory && role.UniqueId == Guid.Empty)
                         .RowCount();

            return(result > 0);
        }
        private ServiceBusMessage GenerateMessage(Category category, int environmentType, Func <CategoryFascicle, ICommand> func)
        {
            IList <CategoryFascicle> categoryFascicles = category.CategoryFascicles.Where(f => (f.DSWEnvironment == environmentType || f.DSWEnvironment == 0)).ToList();
            CategoryFascicle         categoryFascicle  = categoryFascicles.FirstOrDefault();

            if (categoryFascicles != null && categoryFascicles.Count > 1)
            {
                categoryFascicle = categoryFascicles.FirstOrDefault(f => f.FascicleType == FascicleType.Period);
            }
            IIdentityContext identity = new IdentityContext(_currentIdentity.FullUserName);

            ServiceBusMessage message = null;
            ICommand          command = func(categoryFascicle);

            message = _cqrsMapper.Map(command, new ServiceBusMessage());
            if (string.IsNullOrEmpty(message.ChannelName))
            {
                throw new DSWException($"Queue name to command [{command}] is not mapped", null, DSWExceptionCode.SC_Mapper);
            }
            return(message);
        }
        protected override void AfterSave(Resolution entity)
        {
            try
            {
                _logger.WriteDebug(new LogMessage(string.Concat("VecompSoftware.DocSuite.Private.WebAPI.Controllers.Entity.Resolutions.AfterSave with entity UniqueId ", entity.UniqueId)), LogCategories);
                Resolution resolution = _unitOfWork.Repository <Resolution>().GetFullByUniqueId(entity.UniqueId).SingleOrDefault();
                if (resolution != null)
                {
                    IList <CategoryFascicle> categoryFascicles = resolution.Category.CategoryFascicles.Where(f => (f.DSWEnvironment == (int)DSWEnvironmentType.Resolution || f.DSWEnvironment == 0)).ToList();
                    CategoryFascicle         categoryFascicle  = categoryFascicles.FirstOrDefault();
                    if (categoryFascicles != null && categoryFascicles.Count > 1)
                    {
                        categoryFascicle = categoryFascicles.FirstOrDefault(f => f.FascicleType == FascicleType.Period);
                    }
                    _mapper.FileResolution  = _unitOfWork.Repository <FileResolution>().GetByResolution(resolution.EntityId).SingleOrDefault();
                    _mapper.ResolutionRoles = _unitOfWork.Repository <ResolutionRole>().GetByResolution(resolution.EntityId);
                    IIdentityContext identity        = new IdentityContext(_currentIdentity.FullUserName);
                    ResolutionModel  resolutionModel = _mapper.Map(resolution, new ResolutionModel());

                    ICommandUpdateResolution commandUpdate = new CommandUpdateResolution(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, identity, resolutionModel, categoryFascicle, null);

                    ServiceBusMessage message = _cqrsMapper.Map(commandUpdate, new ServiceBusMessage());
                    if (string.IsNullOrEmpty(message.ChannelName))
                    {
                        throw new DSWException(string.Concat("Queue name to command [", commandUpdate.ToString(), "] is not mapped"), null, DSWExceptionCode.SC_Mapper);
                    }

                    Task.Run(async() =>
                    {
                        await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message);
                    }).Wait();
                }
                base.AfterSave(entity);
            }
            catch (DSWException ex)
            {
                _logger.WriteError(ex, LogCategories);
            }
        }
        protected override void AfterSave(Protocol entity)
        {
            try
            {
                _logger.WriteDebug(new LogMessage($"VecompSoftware.DocSuite.Private.WebAPI.Controllers.Entity.Protocols.AfterSave with entity UniqueId {entity.UniqueId}"), LogCategories);
                Protocol protocol = _unitOfWork.Repository <Protocol>().GetByUniqueIdWithRole(entity.UniqueId).FirstOrDefault();
                if (protocol != null)
                {
                    IList <CategoryFascicle> categoryFascicles = protocol.Category.CategoryFascicles.Where(f => f.DSWEnvironment == (int)DSWEnvironmentType.Protocol || f.DSWEnvironment == 0).ToList();
                    CategoryFascicle         categoryFascicle  = categoryFascicles.FirstOrDefault();
                    if (categoryFascicles != null && categoryFascicles.Count > 1)
                    {
                        categoryFascicle = categoryFascicles.FirstOrDefault(f => f.FascicleType == FascicleType.Period);
                    }
                    IIdentityContext identity = new IdentityContext(_currentIdentity.FullUserName);
                    ICQRS            command  = null;

                    if (CurrentUpdateActionType.HasValue && CurrentUpdateActionType == UpdateActionType.ActivateProtocol)
                    {
                        command = new CommandCreateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, null, null, null, identity, protocol, categoryFascicle, null);
                    }

                    if (CurrentDeleteActionType.HasValue && CurrentDeleteActionType == DeleteActionType.DeleteProtocol)
                    {
                        command = new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, null, null, null, identity, protocol, categoryFascicle, null);
                    }

                    if (HttpContext.Current.Request.HttpMethod == HttpMethod.Put.Method &&
                        CurrentUpdateActionType.HasValue && CurrentUpdateActionType != UpdateActionType.ActivateProtocol)
                    {
                        command = new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, null, null, null, identity, protocol, categoryFascicle, null);
                    }

                    if (command != null)
                    {
                        WorkflowActionDocumentUnitLinkModel workflowActionDocumentUnitLinkModel;
                        DocumentUnitModel documentUnitModel;
                        foreach (IWorkflowAction workflowAction in WorkflowActions)
                        {
                            workflowAction.IdWorkflowActivity = IdWorkflowActivity;
                            if (workflowAction is IWorkflowActionDocumentUnitLink)
                            {
                                workflowActionDocumentUnitLinkModel = (WorkflowActionDocumentUnitLinkModel)workflowAction;
                                documentUnitModel = workflowActionDocumentUnitLinkModel.GetReferenced();
                                if (documentUnitModel.UniqueId != protocol.UniqueId)
                                {
                                    documentUnitModel = workflowActionDocumentUnitLinkModel.GetDestinationLink();
                                }
                                documentUnitModel.Year   = protocol.Year;
                                documentUnitModel.Number = protocol.Number.ToString();
                            }
                            command.WorkflowActions.Add(workflowAction);
                        }
                        ServiceBusMessage message = _cqrsMapper.Map(command, new ServiceBusMessage());
                        if (message == null || string.IsNullOrEmpty(message.ChannelName))
                        {
                            throw new DSWException($"Queue name to command [{command}] is not mapped", null, DSWExceptionCode.SC_Mapper);
                        }
                        Task.Run(async() =>
                        {
                            await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message);
                        }).Wait();
                    }
                }
            }
            catch (DSWException ex)
            {
                _logger.WriteError(ex, LogCategories);
            }
            base.AfterSave(entity);
        }
Example #7
0
        public override async Task ExecuteAsync(ICommandInsertUDSData command)
        {
            _logger.WriteInfo(new LogMessage(string.Concat(command.CommandName, " is arrived")), LogCategories);

            Guid?  collaborationUniqueId;
            string collaborationTemplateName;
            int?   collaborationId;

            try
            {
                _logger.WriteInfo(new LogMessage(string.Concat(command.ContentType.Id, " model evaluating ... ")), LogCategories);
                UDSEntityModel udsEntityModel = await InsertDataAsync(command.ContentType.ContentTypeValue, command.Identity.User, command.CreationTime);

                command.ContentType.ContentTypeValue.UniqueId = udsEntityModel.IdUDS;
                ResetModelXML(command.ContentType.ContentTypeValue);

                collaborationId           = udsEntityModel.Relations.Collaborations.FirstOrDefault()?.IdCollaboration;
                collaborationUniqueId     = udsEntityModel.Relations.Collaborations.FirstOrDefault()?.CollaborationUniqueId;
                collaborationTemplateName = udsEntityModel.Relations.Collaborations.FirstOrDefault()?.CollaborationTemplateName;

                IEventInsertUDSData evt = new EventInsertUDSData(command.CorrelationId, command.TenantName, command.TenantId, command.TenantAOOId, command.Identity,
                                                                 command.ContentType.ContentTypeValue);
                evt.CorrelatedMessages.Add(command);
                if (!await PushEventAsync(evt))
                {
                    throw new Exception("EventInsertUDSData not sent");
                }

                UDSBuildModel    udsBuildModel    = MapUDSModel(command.ContentType.ContentTypeValue, udsEntityModel);
                CategoryFascicle categoryFascicle = await GetPeriodicCategoryFascicleByEnvironment(udsEntityModel.IdCategory.Value, command.ContentType.ContentTypeValue.UDSRepository.DSWEnvironment);

                if (categoryFascicle == null)
                {
                    categoryFascicle = await GetDefaultCategoryFascicle(udsEntityModel.IdCategory.Value);
                }
                ICommandCQRSCreateUDSData commandCQRS = new CommandCQRSCreateUDSData(command.TenantName, command.TenantId, command.TenantAOOId, command.Identity, udsBuildModel, categoryFascicle, null,
                                                                                     collaborationUniqueId, collaborationId, collaborationTemplateName);
                if (command.CorrelationId.HasValue)
                {
                    commandCQRS = new CommandCQRSCreateUDSData(command.CorrelationId.Value, command.TenantName, command.TenantId, command.TenantAOOId, command.Identity, udsBuildModel, categoryFascicle, null,
                                                               collaborationUniqueId, collaborationId, collaborationTemplateName);
                }
                if (udsBuildModel.WorkflowActions != null)
                {
                    foreach (IWorkflowAction workflowAction in udsBuildModel.WorkflowActions)
                    {
                        commandCQRS.WorkflowActions.Add(workflowAction);
                    }
                }
                if (!await PushCommandAsync(commandCQRS))
                {
                    throw new Exception("CommandCQRSCreateUDSData not sent");
                }
                #region [ EventCompleteUDSBuild ]
                IEventCompleteUDSBuild eventCompleteUDSBuild = new EventCompleteUDSBuild(Guid.NewGuid(), command.CorrelationId, command.TenantName, command.TenantId, command.TenantAOOId,
                                                                                         command.Identity, udsBuildModel, null);
                if (!await PushEventAsync(eventCompleteUDSBuild))
                {
                    _logger.WriteError(new LogMessage($"EventCompleteUDSBuild {udsBuildModel.UniqueId} has not been sended"), LogCategories);
                    throw new Exception("IEventCompleteUDSBuild not sended");
                }
                _logger.WriteInfo(new LogMessage($"EventCompleteUDSBuild {udsBuildModel.UniqueId} has been sended"), LogCategories);
                #endregion
            }
            catch (Exception ex)
            {
                ResetModelXML(command.ContentType.ContentTypeValue);
                IEventError evt = new EventError(command.CorrelationId, command.TenantName, command.TenantId, command.TenantAOOId, command.Identity,
                                                 new ContentTypeString($"Errore in fase di inserimento nell'archivio [{ex.Message}]"), null);
                evt.CorrelatedMessages.Add(command);
                if (!await PushEventAsync(evt))
                {
                    throw new Exception("EventError not sent");
                }
                throw ex;
            }

            _logger.WriteInfo(new LogMessage("message completed."), LogCategories);
        }
Example #8
0
        public override async Task ExecuteAsync(ICommandUpdateUDSData command)
        {
            _logger.WriteInfo(new LogMessage($"{command.CommandName} is arrived"), LogCategories);

            Guid?  collaborationUniqueId;
            string collaborationTemplateName;
            int?   collaborationId;

            try
            {
                UDSEntityModel udsEntityModel = await UpdateData(command.ContentType.ContentTypeValue, command.Identity.User, command.CreationTime);

                ResetModelXML(command.ContentType.ContentTypeValue);

                collaborationId           = udsEntityModel.Relations.Collaborations.FirstOrDefault()?.IdCollaboration;
                collaborationUniqueId     = udsEntityModel.Relations.Collaborations.FirstOrDefault()?.CollaborationUniqueId;
                collaborationTemplateName = udsEntityModel.Relations.Collaborations.FirstOrDefault()?.CollaborationTemplateName;

                IEventUpdateUDSData evt = new EventUpdateUDSData(Guid.NewGuid(), command.CorrelationId, command.TenantName, command.TenantId, command.TenantAOOId, command.Identity,
                                                                 command.ContentType.ContentTypeValue, null);
                evt.CorrelatedMessages.Add(command);
                if (!await PushEventAsync(evt))
                {
                    throw new Exception("EventUpdateUDSData not sent");
                }

                CategoryFascicle categoryFascicle = await GetPeriodicCategoryFascicleByEnvironment(udsEntityModel.IdCategory.Value, command.ContentType.ContentTypeValue.UDSRepository.DSWEnvironment);

                if (categoryFascicle == null)
                {
                    categoryFascicle = await GetDefaultCategoryFascicle(udsEntityModel.IdCategory.Value);
                }

                UDSBuildModel udsBuildModel = MapUDSModel(command.ContentType.ContentTypeValue, udsEntityModel);

                ICommandCQRSUpdateUDSData commandCQRS = new CommandCQRSUpdateUDSData(command.TenantName, command.TenantId, command.TenantAOOId, command.Identity, udsBuildModel, categoryFascicle, null,
                                                                                     collaborationUniqueId, collaborationId, collaborationTemplateName);

                if (command.CorrelationId.HasValue)
                {
                    commandCQRS = new CommandCQRSUpdateUDSData(command.CorrelationId.Value, command.TenantName, command.TenantId, command.TenantAOOId, command.Identity, udsBuildModel, categoryFascicle, null,
                                                               collaborationUniqueId, collaborationId, collaborationTemplateName);
                }

                if (udsBuildModel.WorkflowActions != null)
                {
                    foreach (IWorkflowAction workflowAction in udsBuildModel.WorkflowActions)
                    {
                        commandCQRS.WorkflowActions.Add(workflowAction);
                    }
                }
                if (!await PushCommandAsync(commandCQRS))
                {
                    throw new Exception("CommandCQRSUpdateUDSData not sent");
                }
            }
            catch (Exception ex)
            {
                ResetModelXML(command.ContentType.ContentTypeValue);
                IEventError evt = new EventError(command.CorrelationId, command.TenantName, command.TenantId, command.TenantAOOId, command.Identity,
                                                 new ContentTypeString($"Errore in fase di aggiornamento nell'archivio [{ex.Message}]"), null);
                evt.CorrelatedMessages.Add(command);
                if (!await PushEventAsync(evt))
                {
                    throw new Exception("EventError not sent");
                }
                throw ex;
            }
        }
Example #9
0
        protected override IQueryOver <Category, Category> DecorateCriteria(IQueryOver <Category, Category> queryOver)
        {
            CategoryFascicle categoryFascicle     = null;
            IQueryOver <Category, Category> query = queryOver;

            if (IncludeZeroLevel.HasValue && IncludeZeroLevel.Value)
            {
                query = query.Where(x => x.Code >= 0);
            }
            else
            {
                query = query.Where(x => x.Code > 0);
            }

            if (CategorySchemaId.HasValue)
            {
                query = query.Where(x => x.CategorySchema.Id == CategorySchemaId.Value);
            }

            if (IsActive.HasValue && IsActive.Value)
            {
                query = query.Where(x => x.IsActive == Convert.ToInt16(IsActive.Value));
            }

            if (CheckFascicolable.HasValue && CheckFascicolable.Value)
            {
                query = query.WithSubquery.WhereProperty(x => x.Id).In(SubQueryFascicle(QueryOver.Of(() => categoryFascicle)));

                if (!string.IsNullOrEmpty(Name) || !string.IsNullOrEmpty(FullCode))
                {
                    if (!string.IsNullOrEmpty(Name))
                    {
                        query = FilterByName(query);
                    }

                    if (!string.IsNullOrEmpty(FullCode))
                    {
                        query = query.Where(x => x.FullCode == FullCode);
                    }
                }
                else
                {
                    if (ParentId.HasValue)
                    {
                        if (IncludeChildren.HasValue && IncludeChildren.Value)
                        {
                            query = FilterByFullIncrementalPath(query);
                        }
                        else
                        {
                            query = FilterByParent(query);
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(Name) || !string.IsNullOrEmpty(FullCode))
                {
                    if (!string.IsNullOrEmpty(Name))
                    {
                        query = FilterByName(query);
                    }

                    if (!string.IsNullOrEmpty(FullCode))
                    {
                        query = query.Where(x => x.FullCode == FullCode);
                    }
                }
                else
                {
                    if (ParentId.HasValue)
                    {
                        query = FilterByParent(query);
                    }
                    else
                    {
                        query = query.Where(x => x.Code > 0);
                    }
                }
            }

            if (HasStatusFilter)
            {
                query = FilterByStatus(query);
            }
            else
            {
                if (Year.HasValue)
                {
                    query = FilterByYear(query);
                }
                else
                {
                    if (!CategorySchemaId.HasValue)
                    {
                        query = FilterByDate(query);
                    }
                }
            }

            return(query);
        }
Example #10
0
        protected override Fascicle BeforeCreate(Fascicle entity)
        {
            entity.FascicleFolders.Clear();
            if (entity.Contacts != null)
            {
                HashSet <Contact> contacts = new HashSet <Contact>();
                Contact           contact  = null;
                foreach (Contact item in entity.Contacts)
                {
                    contact = _unitOfWork.Repository <Contact>().Find(item.EntityId);
                    if (contact != null)
                    {
                        contacts.Add(contact);
                    }
                }
                entity.Contacts = contacts;
            }

            if (entity.FascicleDocuments != null && entity.FascicleDocuments.Count > 0)
            {
                _unitOfWork.Repository <FascicleDocument>().InsertRange(entity.FascicleDocuments);
            }

            if (entity.Category != null)
            {
                entity.Category = _unitOfWork.Repository <Category>().Find(entity.Category.EntityShortId);
            }

            if (entity.MetadataRepository != null)
            {
                entity.MetadataRepository = _unitOfWork.Repository <MetadataRepository>().Find(entity.MetadataRepository.UniqueId);
            }

            if (entity.Container != null)
            {
                entity.Container = _unitOfWork.Repository <Container>().Find(entity.Container.EntityShortId);
            }

            if (entity.FascicleTemplate != null)
            {
                entity.FascicleTemplate = _unitOfWork.Repository <ProcessFascicleTemplate>().Find(entity.FascicleTemplate.UniqueId);
            }

            entity.Number = -1;

            DateTimeOffset date = entity.StartDate;

            entity.StartDate = DateTimeOffset.UtcNow;

            if (CurrentInsertActionType.HasValue && CurrentInsertActionType.Value == InsertActionType.InsertPeriodicFascicle)
            {
                CategoryFascicle relatedCategoryFascicle = _unitOfWork.Repository <CategoryFascicle>().GetByEnvironment(entity.Category.EntityShortId, entity.DSWEnvironment.Value).FirstOrDefault();
                FasciclePeriod   period = _unitOfWork.Repository <FasciclePeriod>().Find(relatedCategoryFascicle.FasciclePeriod.UniqueId);
                entity.StartDate = PeriodHelper.GetCurrentPeriodStart(period.PeriodName, date);
                if (entity.FascicleObject.Contains(string.Concat(" - ", period.PeriodName)))
                {
                    entity.FascicleObject = entity.FascicleObject.Replace(entity.FascicleObject.Split('-').LastOrDefault(), "");
                }
                entity.FascicleObject = string.Concat(entity.FascicleObject, " - ", period.PeriodName, ", ",
                                                      period.PeriodName.Equals("Annuale", StringComparison.InvariantCultureIgnoreCase) ? entity.StartDate.Year.ToString() :
                                                      CultureInfo.CurrentCulture.TextInfo.ToTitleCase(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(entity.StartDate.Month)));
            }

            entity.Year = Convert.ToInt16(entity.StartDate.Year);

            if (entity.Category != null)
            {
                int latestNumber = _unitOfWork.Repository <Fascicle>().GetLatestNumber(entity.Year, entity.Category.EntityShortId);
                entity.Number = ++latestNumber;

                IEnumerable <short> idCategories = entity.Category.FullIncrementalPath
                                                   .Split('|')
                                                   .Select(f => short.Parse(f));
                string categorySectionTitle = string.Join(".", _unitOfWork.Repository <Category>().Queryable(true)
                                                          .Where(f => idCategories.Contains(f.EntityShortId))
                                                          .OrderBy(f => f.EntityShortId)
                                                          .Where(f => f.Code > 0)
                                                          .Select(f => f.Code));

                entity.Title = $"{entity.Year}.{categorySectionTitle}-{entity.Number:0000000}";
            }

            if (entity.DossierFolders != null)
            {
                HashSet <DossierFolder> dossierFolders        = new HashSet <DossierFolder>();
                DossierFolder           dossierFolderParent   = null;
                DossierFolder           dossierFascicleFolder = null;
                foreach (DossierFolder dossierFolder in entity.DossierFolders)
                {
                    dossierFolderParent = _unitOfWork.Repository <DossierFolder>().GetIncludeDossier(dossierFolder.UniqueId);
                    if (dossierFolderParent != null)
                    {
                        dossierFolderParent.Status = DossierFolderStatus.Folder;
                        _unitOfWork.Repository <DossierFolder>().Update(dossierFolderParent);
                        dossierFascicleFolder = new DossierFolder()
                        {
                            UniqueId       = Guid.NewGuid(),
                            Fascicle       = entity,
                            Dossier        = dossierFolderParent.Dossier,
                            ParentInsertId = dossierFolderParent.UniqueId,
                            Name           = $"{entity.Title}-{entity.FascicleObject}",
                            Status         = DossierFolderStatus.Fascicle,
                            Category       = entity.Category
                        };
                        dossierFolders.Add(dossierFascicleFolder);
                    }
                }
                entity.DossierFolders = dossierFolders;
                _unitOfWork.Repository <DossierFolder>().InsertRange(entity.DossierFolders);
            }

            if (entity.FascicleRoles != null)
            {
                HashSet <FascicleRole> fascicleRoles = new HashSet <FascicleRole>();
                FascicleRole           fascicleRole;
                Role role;
                foreach (FascicleRole item in entity.FascicleRoles)
                {
                    fascicleRole = new FascicleRole();
                    role         = _unitOfWork.Repository <Role>().Find(item.Role.EntityShortId);
                    if (role != null && !fascicleRoles.Any(f => f.Role.EntityShortId == role.EntityShortId))
                    {
                        fascicleRole.Role     = role;
                        fascicleRole.Fascicle = entity;
                        fascicleRole.IsMaster = item.IsMaster;
                        fascicleRole.AuthorizationRoleType = item.AuthorizationRoleType;

                        switch (entity.FascicleType)
                        {
                        case FascicleType.Activity:
                        {
                            fascicleRole.AuthorizationRoleType = AuthorizationRoleType.Responsible;
                            break;
                        }

                        case FascicleType.Procedure:
                        case FascicleType.Period:
                        {
                            if (item.IsMaster)
                            {
                                fascicleRole.AuthorizationRoleType = AuthorizationRoleType.Responsible;
                            }
                            break;
                        }
                        }
                        fascicleRoles.Add(fascicleRole);
                    }
                }
                entity.FascicleRoles = fascicleRoles;
                _unitOfWork.Repository <FascicleRole>().InsertRange(entity.FascicleRoles);
            }

            if (!string.IsNullOrEmpty(entity.MetadataValues))
            {
                ICollection <MetadataValueModel>   metadataValueModels   = JsonConvert.DeserializeObject <ICollection <MetadataValueModel> >(entity.MetadataValues);
                MetadataDesignerModel              metadataDesignerModel = JsonConvert.DeserializeObject <MetadataDesignerModel>(entity.MetadataDesigner);
                ICollection <MetadataValue>        metadataValues        = new List <MetadataValue>();
                ICollection <MetadataValueContact> metadataContactValues = new List <MetadataValueContact>();
                foreach (MetadataValueModel metadataValueModel in metadataValueModels.Where(x => metadataDesignerModel.ContactFields.Any(xx => xx.KeyName == x.KeyName)))
                {
                    metadataContactValues.Add(CreateMetadataContactValue(metadataValueModel, entity));
                }

                MetadataValue metadataValue;
                foreach (MetadataValueModel metadataValueModel in metadataValueModels.Where(x => !metadataDesignerModel.ContactFields.Any(xx => xx.KeyName == x.KeyName)))
                {
                    metadataValue          = MetadataValueService.CreateMetadataValue(metadataDesignerModel, metadataValueModel);
                    metadataValue.Fascicle = entity;
                    metadataValues.Add(metadataValue);
                }
                entity.SourceMetadataValues  = metadataValues;
                entity.MetadataValueContacts = metadataContactValues;
                _unitOfWork.Repository <MetadataValue>().InsertRange(entity.SourceMetadataValues);
                _unitOfWork.Repository <MetadataValueContact>().InsertRange(entity.MetadataValueContacts);
            }
            _unitOfWork.Repository <FascicleLog>().Insert(CreateLog(entity, FascicleLogType.Insert, "Inserimento nuovo fascicolo", CurrentDomainUser.Account));

            _unitOfWork.Repository <FascicleFolder>().Insert(new FascicleFolder
            {
                UniqueId = entity.UniqueId,
                Fascicle = entity,
                Name     = "Tutti i documenti",
                Category = null,
                Status   = FascicleFolderStatus.Active,
                Typology = FascicleFolderTypology.Root
            });
            return(base.BeforeCreate(entity));
        }