protected override ProcessFascicleWorkflowRepository BeforeCreate(ProcessFascicleWorkflowRepository entity) { if (entity.DossierFolder != null) { entity.DossierFolder = _unitOfWork.Repository <DossierFolder>().Find(entity.DossierFolder.UniqueId); } if (entity.Process != null) { entity.Process = _unitOfWork.Repository <Process>().Find(entity.Process.UniqueId); } if (entity.WorkflowRepository != null) { entity.WorkflowRepository = _unitOfWork.Repository <WorkflowRepository>().Find(entity.WorkflowRepository.UniqueId); } _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, $"Inserimento di entità '{typeof(ProcessFascicleWorkflowRepository).Name}' con ID {entity.UniqueId}", typeof(ProcessFascicleWorkflowRepository).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
protected override Message BeforeCreate(Message entity) { short messageLocationId = _parameterEnvService.MessageLocationId; Location messageLocation = _unitOfWork.Repository <Location>().Find(messageLocationId); if (messageLocation != null) { entity.Location = messageLocation; } if (entity.MessageAttachments != null && entity.MessageAttachments.Count > 0) { _unitOfWork.Repository <MessageAttachment>().InsertRange(entity.MessageAttachments); } if (entity.MessageContacts != null && entity.MessageContacts.Count > 0) { foreach (MessageContact item in entity.MessageContacts) { if (item.MessageContactEmail != null) { _unitOfWork.Repository <MessageContactEmail>().InsertRange(item.MessageContactEmail); } } _unitOfWork.Repository <MessageContact>().InsertRange(entity.MessageContacts); } if (entity.MessageEmails != null && entity.MessageEmails.Count > 0) { _unitOfWork.Repository <MessageEmail>().InsertRange(entity.MessageEmails); } if (entity.MessageLogs != null && entity.MessageLogs.Count > 0) { _unitOfWork.Repository <MessageLog>().InsertRange(entity.MessageLogs); } return(base.BeforeCreate(entity)); }
protected override ProcessFascicleTemplate BeforeCreate(ProcessFascicleTemplate entity) { entity.StartDate = DateTimeOffset.UtcNow; entity.EndDate = null; if (entity.DossierFolder != null) { entity.DossierFolder = _unitOfWork.Repository <DossierFolder>().Find(entity.DossierFolder.UniqueId); } if (entity.DossierFolder != null) { entity.DossierFolder.Status = DossierFolderStatus.Folder; _unitOfWork.Repository <DossierFolder>().Update(entity.DossierFolder); } if (entity.Process != null) { entity.Process = _unitOfWork.Repository <Process>().Find(entity.Process.UniqueId); } _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, $"Inserimento tipologia atto {entity.Name}", typeof(ProcessFascicleTemplate).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
protected override FascicleDocumentUnit BeforeCreate(FascicleDocumentUnit entity) { short?idCategory = null; if (entity.Fascicle != null) { entity.Fascicle = _unitOfWork.Repository <Fascicle>().GetByUniqueId(entity.Fascicle.UniqueId, optimization: false); idCategory = entity.Fascicle.Category.EntityShortId; } if (entity.FascicleFolder != null) { entity.FascicleFolder = _unitOfWork.Repository <FascicleFolder>().Find(entity.FascicleFolder.UniqueId); } if (entity.FascicleFolder == null && idCategory.HasValue) { entity.FascicleFolder = _unitOfWork.Repository <FascicleFolder>().GetByCategoryAndFascicle(entity.Fascicle.UniqueId, idCategory.Value, optimization: false).FirstOrDefault(); } if (entity.DocumentUnit != null) { entity.DocumentUnit = _unitOfWork.Repository <DocumentUnit>().GetByIdWithCategory(entity.DocumentUnit.UniqueId).SingleOrDefault(); } entity.ReferenceType = ReferenceType.Reference; if (entity.Fascicle.FascicleType != FascicleType.Activity) { entity = AutomaticFascicleDetection(entity); } entity.Fascicle.LastChangedDate = DateTimeOffset.UtcNow; FascicleLog fascicleLog = FascicleService.CreateLog(entity.Fascicle, entity.ReferenceType.Equals(ReferenceType.Fascicle) ? FascicleLogType.UDInsert : FascicleLogType.UDReferenceInsert, string.Format("Inserimento ({0}) {1} n. {2} in fascicolo n. {3}", entity.ReferenceType.Equals(ReferenceType.Fascicle) ? EnumHelper.GetDescription(ReferenceType.Fascicle) : EnumHelper.GetDescription(ReferenceType.Reference), LogDocumentNameHelper.GetAttributeDescription(GetType()), entity.UniqueId, entity.Fascicle == null ? string.Empty : entity.Fascicle.Title), CurrentDomainUser.Account); _unitOfWork.Repository <FascicleLog>().Insert(fascicleLog); PrepareDocumentUnitLog(entity, fascicleLog); if (entity.Fascicle != null) { ReferenceType referenceType = (entity.ReferenceType == ReferenceType.Fascicle) ? ReferenceType.Reference : ReferenceType.Fascicle; IEnumerable <Fascicle> fascicles = AssociatedFascicles(entity.DocumentUnit, referenceType); if (fascicles.Any()) { IEnumerable <Fascicle> fascicleToLinks = fascicles.Where(f => (!f.FascicleLinks.Any() || !f.FascicleLinks.Any(fl => fl.FascicleLinked.UniqueId == entity.Fascicle.UniqueId))); ICollection <FascicleLink> fascicleLinks = new HashSet <FascicleLink>(); foreach (Fascicle item in fascicleToLinks) { fascicleLinks.Add(new FascicleLink() { Fascicle = item, FascicleLinked = entity.Fascicle, FascicleLinkType = FascicleLinkType.Automatic }); fascicleLinks.Add(new FascicleLink() { Fascicle = entity.Fascicle, FascicleLinked = item, FascicleLinkType = FascicleLinkType.Automatic }); } _unitOfWork.Repository <FascicleLink>().InsertRange(fascicleLinks); } } return(base.BeforeCreate(entity)); }
public IHttpActionResult GetAuthorizedDossiers(ODataQueryOptions <Dossier> options, ODataActionParameters parameter) { return(CommonHelpers.ActionHelper.TryCatchWithLoggerGeneric <IHttpActionResult>(() => { DossierFinderModel finder = parameter[ODataConfig.ODATA_FINDER_PARAMETER] as DossierFinderModel; IDictionary <string, string> metadataValues = finder.MetadataValues.ToDictionary(d => d.KeyName, d => _metadataFilterFactory.CreateMetadataFilter(d).ToFilter()); ICollection <DossierTableValuedModel> dossierResults = _unitOfWork.Repository <Dossier>().GetAuthorized(Username, Domain, finder.Skip, finder.Top, finder.Year, finder.Number, finder.Subject, finder.IdContainer, finder.StartDateFrom, finder.StartDateTo, finder.EndDateFrom, finder.EndDateTo, finder.Note, finder.IdMetadataRepository, finder.MetadataValue, metadataValues, finder.IdCategory, finder.DossierType, finder.Status); ICollection <DossierModel> dossierModels = _mapperUnitOfwork.Repository <IDomainMapper <DossierTableValuedModel, DossierModel> >().MapCollection(dossierResults); return Ok(dossierModels); }, _logger, LogCategories)); }
private async Task <WorkflowResult> StartWorkflowJson(WorkflowStart content) { WorkflowResult validationResult = new WorkflowResult(); WorkflowRepository workflowRepository = _unitOfWork.Repository <WorkflowRepository>().GetByName(content.WorkflowName); if (workflowRepository == null) { throw new DSWValidationException("Evaluate start workflow validation error", new List <ValidationMessageModel>() { new ValidationMessageModel { Key = "WorkflowStart", Message = $"Impossibile avviare il workflow '{content.WorkflowName}' in quanto non esiste nel repositories dei workflow validi." } }, null, DSWExceptionCode.VA_RulesetValidation); } WorkflowInstance workflowInstance = new WorkflowInstance() { Status = WorkflowStatus.Todo, WorkflowRepository = workflowRepository, Json = workflowRepository.Json, Subject = workflowRepository.Name }; WorkflowProperty prop; foreach (KeyValuePair <string, WorkflowArgument> item in content.Arguments) { prop = _workflowArgumentMapper.Map(item.Value, new WorkflowProperty()); prop.WorkflowType = WorkflowType.Workflow; workflowInstance.WorkflowProperties.Add(prop); } WorkflowProperty _dsw_p_WorkflowStartMotivationRequired = workflowInstance.WorkflowProperties.SingleOrDefault(f => f.Name == WorkflowPropertyHelper.DSW_PROPERTY_WORKFLOW_START_MOTIVATION_REQUIRED); WorkflowProperty _dsw_p_InstanceSubject = workflowInstance.WorkflowProperties.SingleOrDefault(f => f.Name == WorkflowPropertyHelper.DSW_PROPERTY_INSTANCE_SUBJECT); WorkflowProperty _dsw_v_Workflow_ActiveInstanceSubjectUnique = workflowInstance.WorkflowProperties.SingleOrDefault(f => f.Name == WorkflowPropertyHelper.DSW_VALIDATION_INSTANCE_ACTIVE_SUBJECT_UNIQUE); WorkflowProperty _dsw_v_Workflow_StartValidations = workflowInstance.WorkflowProperties.SingleOrDefault(f => f.Name == WorkflowPropertyHelper.DSW_VALIDATION_WORKFLOW_START); WorkflowProperty _dsw_p_ReferenceModel = workflowInstance.WorkflowProperties.SingleOrDefault(f => f.Name == WorkflowPropertyHelper.DSW_PROPERTY_REFERENCE_MODEL); if (_dsw_v_Workflow_StartValidations != null && !string.IsNullOrEmpty(_dsw_v_Workflow_StartValidations.ValueString)) { Dictionary <DSWEnvironmentType, WorkflowRuleDefinition> deserializedWorkflowStartValidation = JsonConvert.DeserializeObject <Dictionary <DSWEnvironmentType, WorkflowRuleDefinition> >(_dsw_v_Workflow_StartValidations.ValueString); Guid fascicleId = JsonConvert.DeserializeObject <WorkflowReferenceModel>(_dsw_p_ReferenceModel.ValueString).ReferenceId; #region Intermediate Validations if (!(deserializedWorkflowStartValidation is Dictionary <DSWEnvironmentType, WorkflowRuleDefinition>)) { throw new DSWValidationException("Evaluate start workflow validation error", new List <ValidationMessageModel>() { new ValidationMessageModel { Key = "WorkflowStart", Message = $"Impossibile avviare il workflow '{content.WorkflowName}' in quanto le definizioni delle regole di avvio non sono valide (struttura non valida)." } }, null, DSWExceptionCode.VA_RulesetValidation); } if (deserializedWorkflowStartValidation.Keys.FirstOrDefault().ToString() != EnumHelper.GetDescription(DSWEnvironmentType.Fascicle)) { throw new DSWValidationException("Evaluate start workflow validation error", new List <ValidationMessageModel>() { new ValidationMessageModel { Key = "WorkflowStart", Message = $"Impossibile avviare il workflow '{content.WorkflowName}' in quanto il motore supporta definizioni solo per il modulo Fascicoli (environment non supportato)." } }, null, DSWExceptionCode.VA_RulesetValidation); } #endregion List <ValidationMessageModel> errorResult = new List <ValidationMessageModel>(); ICollection <WorkflowRule> deserializedWorkflowRules = deserializedWorkflowStartValidation[DSWEnvironmentType.Fascicle].Rules; await ValidateWorkflowRules(fascicleId, errorResult, deserializedWorkflowRules); } if (_dsw_p_InstanceSubject != null) { workflowInstance.Subject = _dsw_p_InstanceSubject.ValueString; _logger.WriteDebug(new LogMessage($"SET INSTANCE SUBJECT: {workflowInstance.Subject}"), LogCategories); } if (_dsw_p_WorkflowStartMotivationRequired != null && _dsw_p_WorkflowStartMotivationRequired.ValueBoolean.HasValue && _dsw_p_WorkflowStartMotivationRequired.ValueBoolean.Value) { WorkflowProperty dsw_p_Subject = workflowInstance.WorkflowProperties.SingleOrDefault(f => f.Name == WorkflowPropertyHelper.DSW_PROPERTY_SUBJECT); if (dsw_p_Subject == null || string.IsNullOrEmpty(dsw_p_Subject.ValueString)) { throw new DSWValidationException("Evaluate start workflow validation error", new List <ValidationMessageModel>() { new ValidationMessageModel { Key = "WorkflowStart", Message = $"Impossibile avviare il flusso di lavoro se non è stata fornita una motivazione" } }, null, DSWExceptionCode.VA_RulesetValidation); } } if (_dsw_v_Workflow_ActiveInstanceSubjectUnique != null && _dsw_v_Workflow_ActiveInstanceSubjectUnique.ValueBoolean.HasValue && _dsw_v_Workflow_ActiveInstanceSubjectUnique.ValueBoolean.Value) { if (_unitOfWork.Repository <WorkflowInstance>().CountActiveInstances(workflowInstance.WorkflowRepository.UniqueId, workflowInstance.Subject) > 0) { throw new DSWValidationException("Evaluate start workflow validation error", new List <ValidationMessageModel>() { new ValidationMessageModel { Key = "WorkflowStart", Message = $"Impossibile avviare un nuovo flusso di lavoro in cui l'oggetto '{workflowInstance.Subject}' è stato come unico attivo. Completare i restanti flussi di lavoro attivi." } }, null, DSWExceptionCode.VA_RulesetValidation); } } _unitOfWork.BeginTransaction(); Guid instanceId = Guid.NewGuid(); workflowInstance = await _workflowInstanceService.CreateAsync(workflowInstance); await PopulateActivityAsync(workflowInstance, instanceId, workflowInstance.WorkflowRepository, workflowInstance.WorkflowProperties.Where(f => !f.Name.Equals(WorkflowPropertyHelper.DSW_ACTION_ACTIVITY_MANUAL_COMPLETE))); bool result = await _unitOfWork.SaveAsync(); _unitOfWork.BeginTransaction(); workflowInstance.Status = WorkflowStatus.Progress; if (!workflowInstance.InstanceId.HasValue) { workflowInstance.InstanceId = instanceId; } workflowInstance = await _workflowInstanceService.UpdateAsync(workflowInstance); result = await _unitOfWork.SaveAsync(); validationResult.InstanceId = workflowInstance.InstanceId; validationResult.IsValid = true; _logger.WriteInfo(new LogMessage($"Assing workflowInstance.InstanceId [{workflowInstance.InstanceId}] for {workflowInstance.WorkflowRepository.Name}"), LogCategories); return(validationResult); }
public async Task <IHttpActionResult> Post([FromBody] BuildActionModel model, Guid idRepository) { return(await WebApiHelpers.ActionHelper.TryCatchWithLoggerAsync(async() => { UDSRepository repository = _unitOfWork.Repository <UDSRepository>().Find(idRepository); if (repository != null && model != null && !string.IsNullOrEmpty(model.Model)) { UDSRelationModel relationModel = JsonConvert.DeserializeObject <UDSRelationModel>(model.Model); ICollection <UDSRole> rolesToManage = GetEntityRoles(relationModel.Roles, repository); ICollection <UDSUser> usersToManage = GetEntityUsers(relationModel.Users, repository); ICollection <UDSPECMail> pecMailsToManage = GetEntityPECMails(relationModel.PECMails, repository); ICollection <UDSMessage> messagesToManage = GetEntityMessages(relationModel.Messages, repository); ICollection <UDSDocumentUnit> documentUnitsToManage = GetEntityDocumentUnits(relationModel.DocumentUnits, repository); ICollection <UDSContact> contactsToManage = GetEntityContacts(relationModel.Contacts, repository); ICollection <UDSCollaboration> collaborationsToManage = GetEntityCollaborations(relationModel.Collaborations, repository); if (model.BuildType == BuildActionType.Build) { _unitOfWork.BeginTransaction(); await BuildUDSRoleAsync(rolesToManage); await BuildUDSUserAsync(usersToManage); await BuildUDSPECMailAsync(pecMailsToManage); await BuildUDSMessageAsync(messagesToManage); await BuildUDSDocumentUnitAsync(documentUnitsToManage); await BuildUDSContactAsync(contactsToManage); await BuildUDSCollaborationAsync(collaborationsToManage); await _unitOfWork.SaveAsync(); } if (model.BuildType == BuildActionType.Synchronize) { _unitOfWork.BeginTransaction(); await SynchroniseUDSRoleAsync(rolesToManage, model.ReferenceId, repository); await SynchroniseUDSUserAsync(usersToManage, model.ReferenceId, repository); await SynchroniseUDSPECMailAsync(pecMailsToManage, model.ReferenceId, repository); await SynchroniseUDSMessageAsync(messagesToManage, model.ReferenceId, repository); await SynchroniseUDSDocumentUnitAsync(documentUnitsToManage, model.ReferenceId, repository); await SynchroniseUDSContactAsync(contactsToManage, model.ReferenceId, repository); await SynchroniseUDSCollaborationAsync(collaborationsToManage, model.ReferenceId, repository); await _unitOfWork.SaveAsync(); } } return Ok(model); }, BadRequest, Content, InternalServerError, _logger, LogCategories)); }
protected override Tenant BeforeCreate(Tenant entity) { if (entity.TenantAOO != null) { entity.TenantAOO = _unitOfWork.Repository <TenantAOO>().Find(entity.TenantAOO.UniqueId); } if (entity.Configurations != null && entity.Configurations.Count > 0) { foreach (TenantConfiguration item in entity.Configurations) { item.Tenant = entity; } } if (entity.Containers != null) { HashSet <Container> containers = new HashSet <Container>(); Container container = null; foreach (Container item in entity.Containers) { container = _unitOfWork.Repository <Container>().Find(item.EntityShortId); if (container != null) { containers.Add(container); } } entity.Containers = containers; } if (entity.Roles != null) { HashSet <Role> roles = new HashSet <Role>(); Role role = null; foreach (Role item in entity.Roles) { role = _unitOfWork.Repository <Role>().Find(item.EntityShortId); if (role != null) { roles.Add(role); } } entity.Roles = roles; } if (entity.PECMailBoxes != null) { HashSet <PECMailBox> pecMailBoxes = new HashSet <PECMailBox>(); PECMailBox pecMailBox = null; foreach (PECMailBox item in entity.PECMailBoxes) { pecMailBox = _unitOfWork.Repository <PECMailBox>().Find(item.EntityShortId); if (pecMailBox != null) { pecMailBoxes.Add(pecMailBox); } } entity.PECMailBoxes = pecMailBoxes; } if (entity.TenantWorkflowRepositories != null) { HashSet <TenantWorkflowRepository> tenantWorkflowRepositories = new HashSet <TenantWorkflowRepository>(); TenantWorkflowRepository tenantWorkflowRepository = null; foreach (TenantWorkflowRepository item in entity.TenantWorkflowRepositories) { tenantWorkflowRepository = _unitOfWork.Repository <TenantWorkflowRepository>().Find(item.UniqueId); if (tenantWorkflowRepository != null) { tenantWorkflowRepositories.Add(tenantWorkflowRepository); } } entity.TenantWorkflowRepositories = tenantWorkflowRepositories; } if (entity.Contacts != null) { HashSet <Contact> tenantContacts = new HashSet <Contact>(); Contact tenantContact = null; foreach (Contact item in entity.Contacts) { tenantContact = _unitOfWork.Repository <Contact>().Find(item.EntityId); if (tenantContact != null) { tenantContacts.Add(tenantContact); } } entity.Contacts = tenantContacts; } _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, string.Concat("Inserimento OU ", entity.TenantName), typeof(TenantConfiguration).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
protected override TemplateDocumentRepository BeforeCreate(TemplateDocumentRepository entity) { _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, string.Concat("Inserimento deposito documentale ", entity.Name), typeof(TemplateDocumentRepository).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
public IHttpActionResult GetAvailableProtocolLogs(ODataQueryOptions <Conservation> options, int skip, int top) { return(CommonHelpers.ActionHelper.TryCatchWithLoggerGeneric <IHttpActionResult>(() => { ICollection <ConservationLogModel> logResults = _unitOfWork.Repository <Conservation>().AvailableProtocolLogs(skip, top); return Ok(logResults); }, _logger, LogCategories)); }
public IHttpActionResult GetAtVisionSignCollaborations(ODataQueryOptions <Collaboration> options) { return(CommonHelpers.ActionHelper.TryCatchWithLoggerGeneric(() => { ICollection <CollaborationTableValuedModel> results = _unitOfWork.Repository <Collaboration>().GetProposed($"{Domain}\\{Username}"); return Ok(_mapperTableValue.MapCollection(results)); }, _logger, LogCategories)); }
protected override DocumentUnit BeforeCreate(DocumentUnit entity) { if (entity.Category != null) { entity.Category = _unitOfWork.Repository <Category>().Find(entity.Category.EntityShortId); } if (entity.Container != null) { entity.Container = _unitOfWork.Repository <Container>().Find(entity.Container.EntityShortId); } if (entity.Fascicle != null) { entity.Fascicle = _unitOfWork.Repository <Fascicle>().Find(entity.Fascicle.UniqueId); } if (entity.UDSRepository != null) { entity.UDSRepository = _unitOfWork.Repository <UDSRepository>().Find(entity.UDSRepository.UniqueId); } if (entity.TenantAOO != null) { entity.TenantAOO = _unitOfWork.Repository <TenantAOO>().Find(entity.TenantAOO.UniqueId); } if (entity.DocumentUnitChains != null && entity.DocumentUnitChains.Count > 0) { foreach (DocumentUnitChain item in entity.DocumentUnitChains) { item.DocumentUnit = entity; } _unitOfWork.Repository <DocumentUnitChain>().InsertRange(entity.DocumentUnitChains); } if (entity.DocumentUnitRoles != null && entity.DocumentUnitRoles.Count > 0) { foreach (DocumentUnitRole item in entity.DocumentUnitRoles) { item.DocumentUnit = entity; } _unitOfWork.Repository <DocumentUnitRole>().InsertRange(entity.DocumentUnitRoles); } if (entity.DocumentUnitUsers != null && entity.DocumentUnitUsers.Count > 0) { foreach (DocumentUnitUser item in entity.DocumentUnitUsers) { item.DocumentUnit = entity; } _unitOfWork.Repository <DocumentUnitUser>().InsertRange(entity.DocumentUnitUsers); } return(base.BeforeCreate(entity)); }
protected override WorkflowActivity BeforeCreate(WorkflowActivity entity) { if (entity.WorkflowInstance != null) { entity.WorkflowInstance = _unitOfWork.Repository <WorkflowInstance>().Find(entity.WorkflowInstance.UniqueId); } if (entity.WorkflowActivityLogs != null && entity.WorkflowActivityLogs.Count > 0) { foreach (WorkflowActivityLog item in entity.WorkflowActivityLogs) { item.Entity = entity; } _unitOfWork.Repository <WorkflowActivityLog>().InsertRange(entity.WorkflowActivityLogs); } if (entity.WorkflowProperties != null && entity.WorkflowProperties.Count > 0) { foreach (WorkflowProperty item in entity.WorkflowProperties) { item.WorkflowActivity = entity; } _unitOfWork.Repository <WorkflowProperty>().InsertRange(entity.WorkflowProperties); } if (entity.WorkflowAuthorizations != null && entity.WorkflowAuthorizations.Count > 0) { foreach (WorkflowAuthorization item in entity.WorkflowAuthorizations) { item.WorkflowActivity = entity; } _unitOfWork.Repository <WorkflowAuthorization>().InsertRange(entity.WorkflowAuthorizations); } return(base.BeforeCreate(entity)); }
protected override Protocol BeforeCreate(Protocol entity) { if (CurrentInsertActionType == InsertActionType.CreateProtocol) { entity.IdStatus = -5; Parameter parameter = _unitOfWork.Repository <Parameter>().GetParameters().First(); entity.Number = parameter.LastUsedNumber; parameter.LastUsedNumber++; _unitOfWork.Repository <Parameter>().Update(parameter); entity.Year = (short)DateTime.Now.Year; entity.ConservationStatus = "M"; entity.HasConservatedDocs = false; string identificationSdi = entity.AdvancedProtocol?.IdentificationSdi; string serviceCategory = entity.AdvancedProtocol?.ServiceCategory; entity.AdvancedProtocol = new AdvancedProtocol { Year = entity.Year, Number = entity.Number, IdentificationSdi = identificationSdi, ServiceCategory = serviceCategory }; _unitOfWork.Repository <AdvancedProtocol>().Insert(entity.AdvancedProtocol); entity.ProtocolLogs.Add(CreatProtocoloLog(entity, "PI", "Creato protocollo")); if (entity.Category != null) { entity.Category = _unitOfWork.Repository <Category>().Find(entity.Category.EntityShortId); } if (entity.Container != null) { entity.Container = _unitOfWork.Repository <Container>().Find(entity.Container.EntityShortId); } if (entity.Location != null) { entity.Location = _unitOfWork.Repository <Location>().Find(entity.Location.EntityShortId); } if (entity.AttachLocation != null) { entity.AttachLocation = _unitOfWork.Repository <Location>().Find(entity.AttachLocation.EntityShortId); } if (entity.TenantAOO != null) { entity.TenantAOO = _unitOfWork.Repository <TenantAOO>().Find(entity.TenantAOO.UniqueId); } if (entity.DocType != null) { entity.DocType = _unitOfWork.Repository <ProtocolDocumentType>().Find(entity.DocType.EntityShortId); } if (entity.ProtocolRoles != null && entity.ProtocolRoles.Count > 0) { foreach (ProtocolRole item in entity.ProtocolRoles) { if (item.Role != null) { item.Year = entity.Year; item.Number = entity.Number; item.Role = _unitOfWork.Repository <Role>().Find(item.Role.EntityShortId); entity.ProtocolLogs.Add(CreatProtocoloLog(entity, "PZ", $"Autorizzazione (Add): {item.Role.EntityShortId} {item.Role.Name}")); } } _unitOfWork.Repository <ProtocolRole>().InsertRange(entity.ProtocolRoles); } if (entity.ProtocolUsers != null && entity.ProtocolUsers.Count > 0) { foreach (ProtocolUser item in entity.ProtocolUsers) { entity.ProtocolLogs.Add(CreatProtocoloLog(entity, "PZ", $"Autorizzazione utente (Add): {item.Account}")); } _unitOfWork.Repository <ProtocolUser>().InsertRange(entity.ProtocolUsers); } if (entity.ProtocolContacts != null && entity.ProtocolContacts.Count > 0) { foreach (ProtocolContact item in entity.ProtocolContacts) { if (item.Contact != null) { item.Year = entity.Year; item.Number = entity.Number; item.Contact = _unitOfWork.Repository <Contact>().Find(item.Contact.EntityId); } } _unitOfWork.Repository <ProtocolContact>().InsertRange(entity.ProtocolContacts); } int incremental = 1; if (entity.ProtocolContactManuals != null && entity.ProtocolContactManuals.Count > 0) { foreach (ProtocolContactManual item in entity.ProtocolContactManuals) { item.Year = entity.Year; item.Number = entity.Number; item.EntityId = incremental++; } _unitOfWork.Repository <ProtocolContactManual>().InsertRange(entity.ProtocolContactManuals); } } return(base.BeforeCreate(entity)); }
public async Task <IHttpActionResult> Post(Guid authenticationId, string documentUnit, short year, int number) { return(await ActionHelper.TryCatchWithLoggerGeneric(async() => { _logger.WriteInfo(new LogMessage($"Token securities receive a request for authenticationId {authenticationId}, documentUnit {documentUnit}, year {year} and number {number}"), LogCategories); if (!DSWAuthorizationServerProvider.ValidAuthenticationList.Any(f => f == authenticationId)) { _logger.WriteWarning(new LogMessage($"AuthenticationId {authenticationId} is not valid"), LogCategories); throw new DSWSecurityException($"AuthenticationId {authenticationId} is not valid", null, DSWExceptionCode.SC_InvalidAccount); } DocumentUnit reference = null; switch (documentUnit) { case "Protocol": { reference = _unitOfWork.Repository <DocumentUnit>().GetByNumbering(year, number, (int)DSWEnvironmentType.Protocol, optimization: true); break; } default: { _logger.WriteWarning(new LogMessage($"AuthenticationId {authenticationId} has no valid documentUnit '{documentUnit}' name"), LogCategories); throw new DSWSecurityException($"AuthenticationId {authenticationId} is not valid", null, DSWExceptionCode.SC_InvalidAccount); } } if (reference == null) { _logger.WriteWarning(new LogMessage($"DocumentUnit {documentUnit} - {year}/{number} not found"), LogCategories); throw new DSWSecurityException($"DocumentUnit {documentUnit} - {year}/{number} not found", null, DSWExceptionCode.SC_InvalidAccount); } Guid currentToken = Guid.NewGuid(); DateTimeOffset creationDate = DateTimeOffset.UtcNow; DateTimeOffset expiryDate = creationDate.AddMilliseconds(30 * 1000); HostIdentify hostIdentify = new HostIdentify(Environment.MachineName, "Public WebAPI"); TokenSecurityModel tokenModel = new TokenSecurityModel() { AuthenticationId = authenticationId, ExpiryDate = expiryDate, Token = currentToken, Host = hostIdentify, DocumentUnitAuhtorized = new DocSuiteWeb.Model.Entities.DocumentUnits.DocumentUnitModel() { Environment = reference.Environment, UniqueId = reference.UniqueId, Year = reference.Year, Number = reference.Number.ToString(), Title = reference.Title } }; string username = "******"; if (WindowsIdentity.GetCurrent() != null) { username = WindowsIdentity.GetCurrent().Name; } IdentityContext identityContext = new IdentityContext(username); EventTokenSecurity eventTokenSecurity = new EventTokenSecurity(Guid.NewGuid(), currentToken, _parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, identityContext, tokenModel, null); _logger.WriteDebug(new LogMessage($"Generated token {currentToken} by {username} expiry on {expiryDate}"), LogCategories); string topicName = _messageConfiguration.GetConfigurations()[eventTokenSecurity.EventName].TopicName; string dynamicSubscriptionName = currentToken.ToString(); await _topicService.CreateSubscriptionAsync(topicName, dynamicSubscriptionName, currentToken.ToString(), eventTokenSecurity.EventName); ServiceBusMessage message = _cqrsMapper.Map(eventTokenSecurity, new ServiceBusMessage()); ServiceBusMessage response = await _topicService.SendToTopicAsync(message); return Ok(currentToken); }, _logger, LogCategories)); }
protected override Process BeforeCreate(Process entity) { entity.StartDate = DateTimeOffset.UtcNow; entity.ProcessType = ProcessType.Created; if (entity.Category != null) { entity.Category = _unitOfWork.Repository <Category>().Find(entity.Category.EntityShortId); } if (entity.Roles != null) { HashSet <Role> roles = new HashSet <Role>(); Role role = null; foreach (Role item in entity.Roles) { role = _unitOfWork.Repository <Role>().Find(item.EntityShortId); if (role != null) { roles.Add(role); } } entity.Roles = roles; } Dossier defaultDossier = new Dossier() { Subject = entity.Name, Note = entity.Note, StartDate = DateTimeOffset.UtcNow, DossierType = DossierType.Process, Status = DossierStatus.Open }; defaultDossier.Container = _unitOfWork.Repository <Container>().Find(_parameterEnvService.ProcessContainerId); defaultDossier.DossierRoles.Add(new DossierRole() { AuthorizationRoleType = AuthorizationRoleType.Responsible, Role = _unitOfWork.Repository <Role>().Find(_parameterEnvService.ProcessRoleId) }); defaultDossier.Category = entity.Category; defaultDossier = Task.Run <Dossier>(async() => { return(await _dossierService.CreateAsync(defaultDossier)); }).Result; entity.Dossier = defaultDossier; _logger.WriteDebug(new LogMessage($"Generated automatically new dossier {defaultDossier.Subject}({defaultDossier.UniqueId}) to process {entity.Name} ({entity.UniqueId})"), LogCategories); _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, $"Inserita raccolta dei procedimenti {entity.Name}", typeof(Process).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
protected override DossierFolder BeforeCreate(DossierFolder entity) { if (CurrentInsertActionType.HasValue && CurrentInsertActionType == Common.Infrastructures.InsertActionType.CloneProcessDetails) { //TODO: The UniqueId of the clicked folder which will server as the source folder is stored in JsonMetadata (should I move it?) DossierFolder sourceDossierFolder = ExtractSourceToClone(Guid.Parse(entity.JsonMetadata)); entity = CloneDossierFolder(sourceDossierFolder, entity); entity.JsonMetadata = "parent"; entity.Name = $"1-{entity.Name}"; //establish reorder in SQL after Entity Framework insert. _unitOfWork.Repository <DossierFolder>().Insert(entity); /*Load children inside sourceDossier Folder*/ List <DossierFolder> dossierChildren = _unitOfWork.Repository <DossierFolder>() .Query(x => x.DossierFolderPath.StartsWith(sourceDossierFolder.DossierFolderPath) && x.DossierFolderLevel > sourceDossierFolder.DossierFolderLevel && x.Status != DossierFolderStatus.Fascicle, true) .SelectAsQueryable().ToList(); AddClonedChildren(entity, dossierChildren); return(base.BeforeCreate(entity)); } if (entity.Dossier != null) { entity.Dossier = _unitOfWork.Repository <Dossier>().GetWithProcesses(entity.Dossier.UniqueId).SingleOrDefault(); } if (entity.Category != null) { entity.Category = _unitOfWork.Repository <Category>().Find(entity.Category.EntityShortId); } entity.Status = entity.Status == DossierFolderStatus.DoAction ? DossierFolderStatus.DoAction : DossierFolderStatus.InProgress; if (entity.Fascicle != null) { entity.Fascicle = _unitOfWork.Repository <Fascicle>().Find(entity.Fascicle.UniqueId); entity.Status = DossierFolderStatus.Fascicle; CreateOrUpdateFolderHystoryLog(entity); entity.Name = string.Concat(entity.Fascicle.Title, "-", entity.Fascicle.FascicleObject); _unitOfWork.Repository <DossierLog>().Insert(BaseDossierService <DossierLog> .CreateLog(entity.Dossier, entity, DossierLogType.FolderModify, string.Concat("Aggiornata la cartella '", entity.Name, "' con fascicolo associato '", entity.Fascicle.Title, "-", entity.Fascicle.FascicleObject, "'"), CurrentDomainUser.Account)); } _unitOfWork.Repository <DossierLog>().Insert(BaseDossierService <DossierLog> .CreateLog(entity.Dossier, entity, DossierLogType.FolderInsert, string.Concat("Creata cartella '", entity.Name, "' ", entity.Fascicle != null ? string.Concat(" con fascicolo associato '", entity.Fascicle.Title, "-", entity.Fascicle.FascicleObject, "'") : string.Empty), CurrentDomainUser.Account)); if (entity.DossierFolderRoles != null) { HashSet <DossierFolderRole> dossierFolderRoles = new HashSet <DossierFolderRole>(); foreach (DossierFolderRole item in entity.DossierFolderRoles) { dossierFolderRoles.Add(CreateDossierFolderRole(item, entity, _unitOfWork.Repository <Role>().Find(item.Role.EntityShortId))); } entity.DossierFolderRoles = dossierFolderRoles.Where(f => f != null).ToList(); _unitOfWork.Repository <DossierFolderRole>().InsertRange(entity.DossierFolderRoles); } if (entity.ParentInsertId.HasValue) { DossierFolder parentFolder = _unitOfWork.Repository <DossierFolder>().Find(entity.ParentInsertId); if (parentFolder != null && parentFolder.DossierFolderLevel > 1) { parentFolder.Status = DossierFolderStatus.Folder; _unitOfWork.Repository <DossierFolder>().Update(parentFolder); _unitOfWork.Repository <DossierLog>().Insert(BaseDossierService <DossierLog> .CreateLog(entity.Dossier, parentFolder, DossierLogType.FolderModify, string.Concat("Aggiornata la tipologia della cartella '", parentFolder.Name, "' da 'Cartella' a 'Cartella con sotto cartelle'"), CurrentDomainUser.Account)); } } if (entity.Dossier != null) { foreach (Process item in entity.Dossier.Processes.Where(f => f.ProcessType == ProcessType.Created)) { item.ProcessType = ProcessType.Defined; _unitOfWork.Repository <Process>().Update(item); } } return(base.BeforeCreate(entity)); }
protected override void AfterSave(FascicleDocumentUnit entity) { try { _logger.WriteDebug(new LogMessage(string.Concat("VecompSoftware.DocSuite.Private.WebAPI.Controllers.Entity.Fascicles.FascicleDocumentUnit.AfterSave with entity UniqueId ", entity.UniqueId)), LogCategories); ServiceBusMessage message = null; if (entity.ReferenceType == ReferenceType.Fascicle) { switch (entity.DocumentUnit.Environment) { case 1: { Collaboration collaboration = null; Guid? collaborationUniqueId = null; int? collaborationId = null; string collaborationTemplateName = string.Empty; Protocol protocol = _unitOfWork.Repository <Protocol>().GetByUniqueIdWithRole(entity.DocumentUnit.UniqueId).SingleOrDefault(); if (protocol != null) { collaboration = _unitOfWork.Repository <Collaboration>().GetByProtocol(protocol.Year, protocol.Number).SingleOrDefault(); if (collaboration != null) { collaborationId = collaboration.EntityId; collaborationUniqueId = collaboration.UniqueId; collaborationTemplateName = collaboration.TemplateName; } } message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Protocol, (categoryFascicle) => new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, collaborationUniqueId, collaborationId, collaborationTemplateName, new IdentityContext(_currentIdentity.FullUserName), protocol, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); break; } case 2: { Resolution resolution = _unitOfWork.Repository <Resolution>().GetFullByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); if (resolution.AdoptionDate.HasValue) { ResolutionModel resolutionModel = _mapper.Map(resolution, new ResolutionModel()); _mapper.FileResolution = _unitOfWork.Repository <FileResolution>().GetByResolution(resolution.EntityId).SingleOrDefault(); _mapper.ResolutionRoles = _unitOfWork.Repository <ResolutionRole>().GetByResolution(resolution.EntityId); message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Resolution, (categoryFascicle) => new CommandUpdateResolution(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), resolutionModel, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } break; } case 4: { DocumentSeriesItem documentSeriesItem = _unitOfWork.Repository <DocumentSeriesItem>().GetFullByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.DocumentSeries, (categoryFascicle) => new CommandUpdateDocumentSeriesItem(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, null, new IdentityContext(_currentIdentity.FullUserName), documentSeriesItem, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); break; } default: { if (entity.DocumentUnit.Environment >= 100) { UDSBuildModel commandModel = _mapperUnitOfwork.Repository <IDomainMapper <DocumentUnit, UDSBuildModel> >().Map(entity.DocumentUnit, new UDSBuildModel()); commandModel.UniqueId = entity.DocumentUnit.UniqueId; commandModel.UDSId = entity.DocumentUnit.UniqueId; commandModel.RegistrationDate = entity.DocumentUnit.RegistrationDate; commandModel.RegistrationUser = entity.DocumentUnit.RegistrationUser; message = GenerateMessage(entity.DocumentUnit.Category, entity.DocumentUnit.Environment, (categoryFascicle) => new CommandCQRSUpdateUDSData(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, entity.DocumentUnit.TenantAOO?.UniqueId ?? Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), commandModel, categoryFascicle, entity.DocumentUnit, null, null, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } break; } } } if (CurrentInsertActionType.HasValue) { message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Fascicle, (categoryFascicle) => { return(new CommandCreateFascicleDocumentUnit(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), entity)); }); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } if (CurrentDeleteActionType.HasValue) { message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Fascicle, (categoryFascicle) => { return(new CommandDeleteFascicleDocumentUnit(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), entity)); }); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } } catch (DSWException ex) { _logger.WriteError(ex, LogCategories); } base.AfterSave(entity); }
public IHttpActionResult GetByDateInterval(string dateFrom, string dateTo, string userName, short?idContainer, int?environment) { DateTimeOffset dateFromOffset = DateTimeOffset.ParseExact(dateFrom, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); DateTimeOffset dateToOffset = DateTimeOffset.ParseExact(dateTo, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); return(CommonHelpers.ActionHelper.TryCatchWithLoggerGeneric(() => { IQueryable <TransparentAdministrationMonitorLog> transparentAdministrationMonitorResults = _unitOfWork.Repository <TransparentAdministrationMonitorLog>() .GetByDateInterval(dateFromOffset, dateToOffset, userName, idContainer, environment); IQueryable <TransparentAdministrationMonitorLogModel> results = _mapperUnitOfwork.Repository <IDomainMapper <TransparentAdministrationMonitorLog, TransparentAdministrationMonitorLogModel> >().MapCollection(transparentAdministrationMonitorResults).AsQueryable(); return Ok(results); }, _logger, LogCategories)); }
public IHttpActionResult GetFascicleSummary(Guid uniqueId) { return(ActionHelper.TryCatchWithLoggerGeneric(() => { Fascicle fascicle = _unitOfWork.Repository <Fascicle>().GetByUniqueId(uniqueId); if (fascicle == null) { throw new ArgumentNullException("Fascicle not found"); } FascicleModel model = _mapper.Map <Fascicle, FascicleModel>(fascicle); ICollection <PrivateCommonModels.ContactTableValuedModel> contacts = _unitOfWork.Repository <Fascicle>().GetContacts(fascicle); List <FascicleContactModel> contactModels = _mapper.Map <ICollection <PrivateCommonModels.ContactTableValuedModel>, ICollection <FascicleContactModel> >(contacts).ToList(); model.Contacts = contactModels; FascicleFolder internetFolder = _unitOfWork.Repository <FascicleFolder>().GetInternetFolderByFascicle(uniqueId).SingleOrDefault(); if (internetFolder != null) { ICollection <DocumentUnitTableValuedModel> documentUnits = _unitOfWork.Repository <DocumentUnit>().GetFascicleDocumentUnitsPrivate(fascicle, internetFolder.UniqueId, Guid.Empty); ICollection <GenericDocumentUnitModel> genericDocumentUnits = _mapper.Map <ICollection <DocumentUnitTableValuedModel>, ICollection <GenericDocumentUnitModel> >(documentUnits).ToList(); model.DocumentUnits = genericDocumentUnits; } return Ok(new List <FascicleModel>() { model }.AsQueryable()); }, _logger, LogCategories)); }
public IHttpActionResult AvailableFascicles(ODataQueryOptions <FascicleModel> options, Guid uniqueId) { return(CommonHelpers.ActionHelper.TryCatchWithLoggerGeneric <IHttpActionResult>(() => { ICollection <FascicleTableValuedModel> availableFascicles = _unitOfWork.Repository <Fascicle>().GetAvailables(Username, Domain, uniqueId); ICollection <FascicleModel> mappedModels = _fascicleTableValuedModelMapper.MapCollection(availableFascicles); //IQueryable<FascicleModel> results = options.ApplyTo(mappedModels.AsQueryable()) as IQueryable<FascicleModel>; return Ok(mappedModels); }, _logger, LogCategories)); }
protected override TemplateCollaboration BeforeCreate(TemplateCollaboration entity) { if (entity.TemplateCollaborationUsers != null && entity.TemplateCollaborationUsers.Count > 0) { foreach (TemplateCollaborationUser item in entity.TemplateCollaborationUsers) { if (item.Role != null) { item.Role = _unitOfWork.Repository <Role>().Find(item.Role.EntityShortId); } } _unitOfWork.Repository <TemplateCollaborationUser>().InsertRange(entity.TemplateCollaborationUsers); } if (entity.TemplateCollaborationDocumentRepositories != null && entity.TemplateCollaborationDocumentRepositories.Count > 0) { foreach (TemplateCollaborationDocumentRepository item in entity.TemplateCollaborationDocumentRepositories) { //TODO: Gestire entità templatedocumentrepositories } _unitOfWork.Repository <TemplateCollaborationDocumentRepository>().InsertRange(entity.TemplateCollaborationDocumentRepositories); } if (entity.Roles != null && entity.Roles.Count > 0) { entity.Roles = entity.Roles.Select(r => _unitOfWork.Repository <Role>().Find(r.EntityShortId)).ToList(); } _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, string.Concat("Inserimento template collaborazione", entity.Name), typeof(TemplateCollaboration).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
protected override Collaboration BeforeCreate(Collaboration entity) { Incremental lastIncremental = _unitOfWork.Repository <Incremental>().GetLastCollaborationIncremental().SingleOrDefault(); if (lastIncremental != null) { lastIncremental.IncrementalValue = lastIncremental.IncrementalValue.HasValue ? lastIncremental.IncrementalValue.Value + 1 : 0; entity.EntityId = lastIncremental.IncrementalValue.Value; _unitOfWork.Repository <Incremental>().Update(lastIncremental); } short collaborationLocationId = _parameterEnvService.CollaborationLocationId; Location collaborationLocation = _unitOfWork.Repository <Location>().Find(collaborationLocationId); if (collaborationLocation != null) { entity.Location = _unitOfWork.Repository <Location>().Find(collaborationLocationId); } if (entity.WorkflowInstance != null) { entity.WorkflowInstance = _unitOfWork.Repository <WorkflowInstance>().Find(entity.WorkflowInstance.UniqueId); } if (entity.CollaborationSigns != null && entity.CollaborationSigns.Count > 0) { _unitOfWork.Repository <CollaborationSign>().InsertRange(entity.CollaborationSigns); } if (entity.CollaborationUsers != null && entity.CollaborationUsers.Count > 0) { foreach (CollaborationUser item in entity.CollaborationUsers) { if (item.Role != null) { item.Role = _unitOfWork.Repository <Role>().Find(item.Role.EntityShortId); } } _unitOfWork.Repository <CollaborationUser>().InsertRange(entity.CollaborationUsers); } if (entity.CollaborationVersionings != null && entity.CollaborationVersionings.Count > 0) { _unitOfWork.Repository <CollaborationVersioning>().InsertRange(entity.CollaborationVersionings); } if (entity.CollaborationLogs != null && entity.CollaborationLogs.Count > 0) { _unitOfWork.Repository <CollaborationLog>().InsertRange(entity.CollaborationLogs); } //TODO: da spostare nel BaseLogService CollaborationLog collaborationLog = new CollaborationLog() { LogType = CollaborationLogType.MODIFICA_SEMPLICE, LogDescription = CREATE_LOG_DESCRIPTION, SystemComputer = Environment.MachineName, Entity = entity }; _unitOfWork.Repository <CollaborationLog>().Insert(collaborationLog); return(base.BeforeCreate(entity)); }
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); }
protected override ResolutionKind BeforeCreate(ResolutionKind entity) { _unitOfWork.Repository <TableLog>().Insert(TableLogService.CreateLog(entity.UniqueId, null, TableLogEvent.INSERT, string.Concat("Inserimento tipologia atto ", entity.Name), typeof(ResolutionKind).Name, CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); string appId, kind, username, @params, authRule, year, number, uniqueId, token, user; appId = kind = username = @params = authRule = year = number = uniqueId = token = user = string.Empty; try { _logger.WriteDebug(new LogMessage("GrantResourceOwnerCredentials"), LogCategories); IFormCollection forms = await context.OwinContext.Request.ReadFormAsync(); appId = forms.Single(f => f.Key == "appId").Value.Single(); _logger.WriteDebug(new LogMessage(string.Concat("AppID-> ", appId)), LogCategories); kind = forms.Single(f => f.Key == "kind").Value.Single(); _logger.WriteDebug(new LogMessage(string.Concat("Kind-> ", kind)), LogCategories); username = forms.Single(f => f.Key == "username").Value.Single(); _logger.WriteDebug(new LogMessage(string.Concat("Username-> ", username)), LogCategories); authRule = forms.Single(f => f.Key == "authRule").Value.Single(); _logger.WriteDebug(new LogMessage(string.Concat("AuthRule-> ", authRule)), LogCategories); @params = forms.Single(f => f.Key == "params").Value.SingleOrDefault(); _logger.WriteDebug(new LogMessage(string.Concat("Params-> ", @params)), LogCategories); if (kind == "Protocol") { string[] keys = @params.Split('|'); year = keys.Single(f => f.StartsWith("year=")).Split('=').Last(); number = keys.Single(f => f.StartsWith("number=")).Split('=').Last(); uniqueId = _unitOfWork.Repository <Protocol>().GetByCompositeKey(short.Parse(year), int.Parse(number)).Single().UniqueId.ToString(); } if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token) { string[] keys = @params.Split('|'); token = keys.Single(f => f.StartsWith("token=")).Split('=').Last(); user = keys.Single(f => f.StartsWith("user="******"The AppId '{appId}' is not valid."), LogCategories); context.SetError("invalid_grant", $"The AppId {appId} is not valid."); context.Rejected(); return; } if (string.IsNullOrEmpty(kind)) { _logger.WriteWarning(new LogMessage($"The Kind '{kind}' is not valid."), LogCategories); context.SetError("invalid_grant", "The Kind is not valid."); context.Rejected(); return; } if (string.IsNullOrEmpty(username) || !ValidIntegrations.Any(f => f.Key == username)) { _logger.WriteWarning(new LogMessage($"The Username '{username}' is not valid."), LogCategories); context.SetError("invalid_grant", $"The Username {username} is not valid."); context.Rejected(); return; } if (string.IsNullOrEmpty(authRule)) { _logger.WriteWarning(new LogMessage($"The AuthRule '{authRule}' is not valid."), LogCategories); context.SetError("invalid_grant", "The AuthRule is not valid."); context.Rejected(); return; } currentIntegration = ValidIntegrations[username]; if (currentIntegration.Key != authenticationId || currentIntegration.Value != authRule) { _logger.WriteWarning(new LogMessage($"{username}: The configuration is not valid."), LogCategories); context.SetError("invalid_grant", "The configuration is not valid."); context.Rejected(); return; } if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_OAuth2 && (string.IsNullOrEmpty(year) || string.IsNullOrEmpty(number))) { _logger.WriteWarning(new LogMessage($"The protocols oauth2 params {year}/{number} is not valid."), LogCategories); context.SetError("invalid_grant", "The protocols oauth2 params is not valid."); context.Rejected(); return; } if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token && (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(year) || string.IsNullOrEmpty(number))) { _logger.WriteWarning(new LogMessage($"The protocols token params {user}/{token}/{year}/{number} is not valid."), LogCategories); context.SetError("invalid_grant", "The protocols token params is not valid."); context.Rejected(); return; } if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token) { string topicName = _messageConfiguration.GetConfigurations()["EventTokenSecurity"].TopicName; if (!await _topicService.SubscriptionExists(topicName, token)) { _logger.WriteWarning(new LogMessage($"AppId {appId} has no valid token {authenticationId}"), LogCategories); context.SetError($"AppId {appId} has not validate token {authenticationId}", "The protocols params is not valid."); context.Rejected(); return; } ServiceBusMessage serviceBusMessage = (await _topicService.GetMessagesAsync(topicName, token)).FirstOrDefault(); IEventTokenSecurity tokenSecurityModel = null; if (serviceBusMessage == null || (tokenSecurityModel = (IEventTokenSecurity)serviceBusMessage.Content) == null) { _logger.WriteWarning(new LogMessage($"AppId {appId} has no valid token"), LogCategories); context.SetError($"AppId {appId} has not validate token {token}", "The protocols params is not valid."); context.Rejected(); return; } if (tokenSecurityModel.ContentType.ContentTypeValue.DocumentUnitAuhtorized.UniqueId.ToString() != uniqueId) { _logger.WriteWarning(new LogMessage($"AppId {appId} token is not valid for protocol {uniqueId}-{year}/{number}"), LogCategories); context.SetError($"AppId {appId} token is not valid for protocol {uniqueId}-{year}/{number}", "The protocols params is not valid."); context.Rejected(); return; } Guid secureToken = tokenSecurityModel.ContentType.ContentTypeValue.Token; _logger.WriteDebug(new LogMessage($"SecureToken is {secureToken}"), LogCategories); } ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Kind, kind, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); identity.AddClaim(new Claim(CLAIM_ExternalViewer_AuthenticationRule, authRule, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); if (kind == "Protocol") { identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Year, year, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Number, number, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_UniqueId, uniqueId, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); if (authRule == VALUE_ExternalViewer_AuthenticationRule_Token) { identity.AddClaim(new Claim(CLAIM_ExternalViewer_Token_Hash, token, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); identity.AddClaim(new Claim(CLAIM_ExternalViewer_Token_User, user, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty)); } } context.Validated(identity); }
protected override Dossier BeforeCreate(Dossier entity) { _unitOfWork.Repository <DossierLog>().Insert(BaseDossierService <DossierLog> .CreateLog(entity, null, DossierLogType.Insert, string.Concat("Nuovo dossier '", entity.Subject, "'"), CurrentDomainUser.Account)); 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.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.DossierRoles != null) { HashSet <DossierRole> dossierRoles = new HashSet <DossierRole>(); foreach (DossierRole item in entity.DossierRoles) { dossierRoles.Add(CreateDossierRole(item, entity)); } entity.DossierRoles = dossierRoles.Where(f => f != null).ToList(); _unitOfWork.Repository <DossierRole>().InsertRange(entity.DossierRoles); } if (entity.DossierDocuments != null && entity.DossierDocuments.Count > 0) { _unitOfWork.Repository <DossierDocument>().InsertRange(entity.DossierDocuments); } 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.Dossier = entity; metadataValues.Add(metadataValue); } entity.SourceMetadataValues = metadataValues; entity.MetadataValueContacts = metadataContactValues; _unitOfWork.Repository <MetadataValue>().InsertRange(entity.SourceMetadataValues); _unitOfWork.Repository <MetadataValueContact>().InsertRange(entity.MetadataValueContacts); } if (entity.Category != null) { entity.Category = _unitOfWork.Repository <Category>().Find(entity.Category.EntityShortId); } else { UserLog userLog = _unitOfWork.Repository <UserLog>().GetBySystemUser(CurrentDomainUser.Account); Tenant currentTenant = _unitOfWork.Repository <Tenant>().GetByUniqueId(userLog.CurrentTenantId).FirstOrDefault(); entity.Category = _unitOfWork.Repository <Category>().GetDefaultCategoryByTenantAOOId(currentTenant.TenantAOO.UniqueId); } entity.Status = DossierStatus.Open; entity.Year = Convert.ToInt16(DateTime.UtcNow.Year); entity.Number = -1; int latestNumber = _unitOfWork.Repository <Dossier>().GetLatestNumber(entity.Year); entity.Number = ++latestNumber; DossierFolder rootNode = new DossierFolder { UniqueId = entity.UniqueId, Dossier = entity, Name = $"Dossier {entity.Year}/{entity.Number:0000000}" , Status = DossierFolderStatus.InProgress, }; _unitOfWork.Repository <DossierFolder>().Insert(rootNode); _unitOfWork.Repository <DossierLog>().Insert(BaseDossierService <DossierLog> .CreateLog(entity, rootNode, DossierLogType.FolderInsert, string.Concat("Creata cartella radice '", rootNode.Name, "'"), CurrentDomainUser.Account)); return(base.BeforeCreate(entity)); }