Exemplo n.º 1
0
        private void MoveToError(FileDocumentInfo document, string prefix, Exception ex)
        {
            var list = new List <FileDocumentInfo> {
                document
            };

            MoveToError(list, prefix, ex);
        }
        private void EvaluateBySignInfo(FileDocumentInfo document)
        {
            if (!document.Extension.Equals(".p7m"))
            {
                return;
            }

            SetSignInfo(document, "DataOraReferto", "Document/Signature/Details", "Date");            // Data e ora di firma.
            SetSignInfo(document, "MedicoRefertante", "Document/Signature/Subject", "NAME");          // Cognome e nome firmatario.
            SetSignInfo(document, "MedicoRefertanteDescrizione", "Document/Signature/Subject", "FC"); // Codice fiscale firmatario.
        }
Exemplo n.º 3
0
        protected XmlDocument GetSignInfo(FileDocumentInfo document)
        {
            if (!document.Extension.Eq(".p7m"))
            {
                throw new InvalidOperationException("Estensione non valida: " + document.Name);
            }

            object p7mStream   = document.Stream;
            var    encodedInfo = new P7Mmanager().ExtractXmlSignatureInfo(ref p7mStream, 0, 0, false);
            var    result      = new XmlDocument();

            result.LoadXml(encodedInfo);
            return(result);
        }
        private void SetSignInfo(FileDocumentInfo document, string key, string xpath, string name)
        {
            if (!document.Attributes.ContainsKey(key))
            {
                document.Attributes.Add(key, null);
            }

            if (!string.IsNullOrEmpty(document.Attributes[key]))
            {
                FileLogger.Info(LoggerName, "Attributo già valorizzato: " + key);
                return;
            }

            FileLogger.Info(LoggerName, "Valore mancante per attributo: " + key);
            var signInfo = GetSignInfo(document);
            var value    = signInfo.SelectNodes(xpath)[0].Attributes[name].Value;

            FileLogger.Info(LoggerName, "Valore recuperato da SignInfo: " + value);
            document.Attributes[key] = value;
        }
        private bool InsertResolution(JsonResolutionModel jsonModel)
        {
            FileLogger.Info(this.Name, "Inizio inserimento Atto");
            Guid       mainChainId              = Guid.Empty;
            Guid       attachmentsChainId       = Guid.Empty;
            Resolution resolution               = new Resolution();
            string     typeDescription          = string.Empty;
            string     typeContainerDescription = string.Empty;

            resolution.Id                = Facade.ParameterFacade.GetIdresolution();
            resolution.Status.Id         = (short)ResolutionStatusId.Attivo;
            resolution.Year              = jsonModel.Anno;
            resolution.ProposeDate       = jsonModel.DataAdozione.ToLocalTime().Date;
            resolution.ProposeUser       = DocSuiteContext.Current.User.FullUserName;
            resolution.AdoptionDate      = jsonModel.DataAdozione.ToLocalTime().Date;
            resolution.AdoptionUser      = DocSuiteContext.Current.User.FullUserName;
            resolution.Number            = jsonModel.Numero;
            resolution.PublishingDate    = jsonModel.DataAdozione.ToLocalTime().Date;
            resolution.PublishingUser    = DocSuiteContext.Current.User.FullUserName;
            resolution.EffectivenessDate = jsonModel.DataEsecutiva.ToLocalTime().Date;
            resolution.EffectivenessUser = DocSuiteContext.Current.User.FullUserName;
            resolution.InclusiveNumber   = jsonModel.Segnatura;
            resolution.ResolutionObject  = jsonModel.Oggetto;
            resolution.Type.Id           = jsonModel.DelDet;
            string[] splitted = jsonModel.Segnatura.Split('/');
            if (splitted.Length > 1 && splitted[1] != null)
            {
                resolution.ServiceNumber = (splitted.Length > 2 && splitted[2] != null) ? string.Concat(splitted[1], "/", splitted[2]) : splitted[1];
            }
            else
            {
                HandleFailure("InsertResolution - La segnatura dell'atto indicata nel file Json non è valida");
                return(false);
            }
            if (jsonModel.DelDet == 1)
            {
                typeDescription          = "Delibera";
                typeContainerDescription = "Delibere";
            }
            else
            {
                if (jsonModel.DelDet == 0)
                {
                    typeDescription          = "Determina";
                    typeContainerDescription = "Determine";
                }
                else
                {
                    HandleFailure("InsertResolution - Errore in elaborazione: la tipologia di atto selezionata non esiste");
                    return(false);
                }
            }
            IList <Container>      containers      = Facade.ContainerFacade.GetContainerByName(string.Concat(typeContainerDescription, " ", jsonModel.Proponente));
            IList <ResolutionKind> resolutionsKind = new ResolutionKindFacade(DocSuiteContext.Current.User.FullUserName).GetByName(jsonModel.TipologiaAtto);
            IList <Contact>        contacts        = GetProposerContacts(jsonModel.Proponente);
            IList <Role>           roles           = Facade.RoleFacade.GetByName(jsonModel.Proponente);
            Category category = Facade.CategoryFacade.GetById(Parameters.ImportResolutionCategoryId);

            if (containers != null && containers.Count() == 1)
            {
                resolution.Container = containers.First();
                resolution.Location  = resolution.Container.ReslLocation;
            }
            else
            {
                HandleFailure(string.Concat("InsertResolution - Errore in elaborazione del contenitore: il contenitore ", typeContainerDescription, " ", jsonModel.Proponente, " non esiste o non è univoco."));
                return(false);
            }
            if (contacts != null && contacts.Count() == 1)
            {
                resolution.AddProposer(contacts.First());
            }
            else
            {
                HandleFailure("InsertResolution - Errore in elaborazione del contatto selezionato: il contatto selezionato non esiste o non è univoco");
                return(false);
            }
            if (category != null)
            {
                resolution.Category = category;
            }
            else
            {
                HandleFailure("InsertResolution - Errore in elaborazione del classificatore: classificatore non trovato.");
                return(false);
            }

            if (resolutionsKind != null && resolutionsKind.Any() && resolutionsKind.Count() == 1)
            {
                resolution.ResolutionKind = resolutionsKind.First();
            }
            else
            {
                HandleFailure("InsertResolution - Errore in elaborazione della tipologia di atto: la tipologia di atto non esiste o non è univoca.");
                return(false);
            }

            resolution.WorkflowType = Facade.TabMasterFacade.GetFieldValue("WorkflowType", DocSuiteContext.Current.ResolutionEnv.Configuration, jsonModel.DelDet);
            string SignatureDocument   = String.Concat(DocSuiteContext.Current.ResolutionEnv.CorporateAcronym, " ", typeDescription, " ", jsonModel.Segnatura, " del ", jsonModel.DataAdozione.ToLocalTime().ToString("d"));
            string SignatureAttachment = String.Concat(SignatureDocument, " (Allegato)");

            try
            {
                FileLogger.Info(this.Name, "InsertResolution - Inizio caricamento documenti in Biblos.");
                string           mainDocumentPath = string.Concat(Parameters.ImportResolutionSourceFolder, jsonModel.MaindocumentPath);
                FileDocumentInfo fileDocumentInfo = new FileDocumentInfo(new FileInfo(mainDocumentPath));
                fileDocumentInfo.Signature = SignatureDocument;
                BiblosDocumentInfo storedDocumentInfo = fileDocumentInfo.ArchiveInBiblos(resolution.Location.DocumentServer, resolution.Location.ReslBiblosDSDB, Guid.Empty);
                mainChainId = storedDocumentInfo.ChainId;
                FileLogger.Info(this.Name, "InsertResolution - Documento principale salvato correttamente in Biblos.");

                int integerMainChainId       = storedDocumentInfo.BiblosChainId;
                int integerAttachmentChainId = -1;
                FileDocumentInfo attachment;

                string attachmentDocumentPath;
                foreach (string attachmentRelativePath in jsonModel.AttachmentsDocumentPath)
                {
                    attachmentDocumentPath = string.Concat(Parameters.ImportResolutionSourceFolder, attachmentRelativePath);
                    attachment             = new FileDocumentInfo(new FileInfo(attachmentDocumentPath));
                    attachment.Signature   = SignatureAttachment;
                    BiblosDocumentInfo attachmentDocumentInfo = attachment.ArchiveInBiblos(resolution.Location.DocumentServer, resolution.Location.ReslBiblosDSDB, attachmentsChainId);
                    attachmentsChainId       = attachmentDocumentInfo.ChainId;
                    integerAttachmentChainId = attachmentDocumentInfo.BiblosChainId;
                    FileLogger.Info(this.Name, "InsertResolution - Allegato salvato correttamente in Biblos.");
                }

                FileResolution fileResolution = new FileResolution();
                fileResolution.Id = resolution.Id;
                fileResolution.IdResolutionFile  = integerMainChainId;
                fileResolution.IdProposalFile    = integerMainChainId;
                fileResolution.IdAssumedProposal = integerMainChainId;
                if (integerAttachmentChainId > 0)
                {
                    fileResolution.IdAttachements = integerAttachmentChainId;
                }
                resolution.File = fileResolution;
                FileLogger.Info(this.Name, "InsertResolution - Fine caricamento documenti in Biblos.");
            }
            catch (Exception ex)
            {
                HandleFailure(string.Concat("InsertResolution - Errore in elaborazione del salvataggio dell'atto in Biblos: ", ex.Message));
                return(false);
            }

            resolution.ResolutionWorkflows = new List <ResolutionWorkflow>();
            resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 1, 0));
            resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 2, 0));
            resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 3, 0));
            resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 4, 1));

            IEnumerable <ResolutionKindDocumentSeries> resolutionDocumentSeries = resolution.ResolutionKind.ResolutionKindDocumentSeries;
            IList <BiblosChainInfo>      documents;
            DocumentSeriesItem           documentSeriesItem;
            ResolutionDocumentSeriesItem resolutionDocumentSeriesItem;

            using (NHibernate.ITransaction transaction = NHibernateSession.BeginTransaction())
            {
                try
                {
                    FileLogger.Info(this.Name, "InsertResolution - Inizio transaction.");
                    Facade.ResolutionFacade.SaveWithoutTransaction(ref resolution);
                    FileLogger.Info(this.Name, "InsertResolution - Inserimento autorizzazioni atto.");
                    if (contacts.First().Role != null)
                    {
                        Facade.ResolutionRoleFacade.AddRole(resolution, contacts.First().Role.Id, DocSuiteContext.Current.ResolutionEnv.AuthorizInsertType, false);
                    }
                    foreach (ResolutionKindDocumentSeries item in resolutionDocumentSeries)
                    {
                        documents                         = new List <BiblosChainInfo>();
                        documentSeriesItem                = new DocumentSeriesItem();
                        resolutionDocumentSeriesItem      = new ResolutionDocumentSeriesItem();
                        documentSeriesItem.Status         = DocumentSeriesItemStatus.Draft;
                        documentSeriesItem.DocumentSeries = Facade.DocumentSeriesFacade.GetById(item.DocumentSeries.Id);
                        documentSeriesItem.Subject        = resolution.ResolutionObject;
                        documentSeriesItem.Category       = resolution.Category;
                        documentSeriesItem.IdMain         = mainChainId;

                        Facade.DocumentSeriesItemFacade.SaveDocumentSeriesItem(documentSeriesItem, resolution.Year.Value,
                                                                               new BiblosChainInfo(new List <DocumentInfo>()), null, null, DocSuiteContext.Current.User.FullUserName,
                                                                               DocumentSeriesItemStatus.Draft, string.Concat("Inserimento bozza di ", item.DocumentSeries.Name), false);

                        if (roles != null && roles.Any() && roles.Count() == 1)
                        {
                            Facade.DocumentSeriesItemRoleFacade.AddOwnerRole(documentSeriesItem, roles.First(), false);
                        }
                        else
                        {
                            HandleFailure("InsertResolution - Errore in elaborazione della tipologia di atto: la tipologia di atto non esiste o non è univoca.");
                            return(false);
                        }

                        resolutionDocumentSeriesItem.IdDocumentSeriesItem = documentSeriesItem.Id;
                        resolutionDocumentSeriesItem.Resolution           = resolution;
                        Facade.ResolutionDocumentSeriesItemFacade.SaveWithoutTransaction(ref resolutionDocumentSeriesItem);
                    }
                    transaction.Commit();

                    //TODO:Invio comando di creazione Resolution alle WebApi
                    // facadeFactory.ResolutionFacade.SendCreateResolutionCommand(resolution);

                    FileLogger.Info(this.Name, "InsertResolution - Transaction completata con successo.");
                }
                catch (Exception ex)
                {
                    FileLogger.Error(this.Name, String.Format("InsertResolution - Errore in salvataggio di atto: Message: {0} - StackTrace: {1}", ex.Message, ex.StackTrace));
                    transaction.Rollback();
                }
            }
            Facade.ResolutionLogFacade.Log(resolution, ResolutionLogType.RI, string.Concat("Inserimento atto n.", resolution.InclusiveNumber));
            return(true);
        }
Exemplo n.º 6
0
        public virtual void ImportDocuments()
        {
            InitializeFolders();
            var xmlPath = CurrentStack.First();

            FileLogger.Info(LoggerName, "Importazione documenti per: " + xmlPath);
            var xmlInfo = new FileDocumentInfo(new FileInfo(xmlPath));

            try
            {
                var deserialized = DeserializeXml(xmlPath);
                FileLogger.Info(LoggerName, "Deserializzato in: " + deserialized.GetType().ToString());

                var documents = GetDocumentInfos(deserialized);
                if (documents.IsNullOrEmpty())
                {
                    throw new InvalidCastException("Nessun documento trovato per: " + xmlInfo.Name);
                }
                FileLogger.Info(LoggerName, "Documenti trovati: " + documents.Count.ToString());
                SaveToBiblos(documents, deserialized);
                FileLogger.Info(LoggerName, "Salvataggio in Biblos completato.");
                var disposable = documents;
                disposable.Add(xmlInfo);
                MoveToBackup(disposable, Path.GetFileNameWithoutExtension(xmlInfo.Name));
                FileLogger.Info(LoggerName, "Importazione documenti completata.");
            }
            catch (FileNotFoundException fnf)
            {
                FileLogger.Warn(LoggerName, "Uno o più documenti mancanti o non validi.", fnf);
                if (!IsExpired(xmlInfo.FileInfo, Parameters.PostponeMissingExpires))
                {
                    return;
                }

                var message = string.Format("Documenti mancanti per {0} del {1} da più di {2} giorni.", xmlInfo.Name, xmlInfo.FileInfo.CreationTime, Parameters.PostponeMissingExpires);
                var expired = new Exception(message, fnf);
                FileLogger.Error(LoggerName, "Importazione documenti interrotta.", expired);
                MoveToError(xmlInfo, Path.GetFileNameWithoutExtension(xmlInfo.Name), expired);
            }
            catch (EndpointNotFoundException enf)
            {
                var temp = new Exception("Servizio Biblos non disponibile.", enf);
                FileLogger.Warn(LoggerName, temp.Message, temp);
                OnParsingError(temp.ToVerboseString());
            }
            catch (SignatureDocumentValidationException sdve)
            {
                FileLogger.Error(LoggerName, "Importazione documenti interrotta.", sdve);
                if (sdve.ToRetry)
                {
                    FileLogger.Warn(LoggerName, string.Format(@"Il server di validazione firme ha restituito un errore temporaneo per il documento {0}. 
                                                                    Il documento verrà lasciato nella directory corrente per provare nuovamente l'importazione.", xmlInfo.Name));
                    return;
                }
                FileDocumentInfo         document  = new FileDocumentInfo(new FileInfo(sdve.FilePath));
                IList <FileDocumentInfo> documents = new List <FileDocumentInfo>()
                {
                    document,
                    xmlInfo
                };
                MoveToRejected(documents, Path.GetFileNameWithoutExtension(xmlInfo.Name), sdve);
            }
            catch (Exception ex)
            {
                FileLogger.Error(LoggerName, "Importazione documenti interrotta.", ex);
                MoveToError(xmlInfo, Path.GetFileNameWithoutExtension(xmlInfo.Name), ex);
            }
            finally
            {
                FileLogger.Info(LoggerName, "Rimozione dallo stack: " + xmlPath);
                CurrentStack.Remove(xmlPath);
            }
        }
        protected override IList <FileDocumentInfo> GetDocumentInfos(DocumentoSanitarioType deserialized)
        {
            var documentPath = Path.Combine(ParserInputFolder, deserialized.Componente.Filename);

            if (!string.IsNullOrEmpty(Parameters.ExtensionWhiteList))
            {
                var fileName  = Path.GetFileName(documentPath).ToLowerInvariant();
                var whiteList = Parameters.ExtensionWhiteList.ToLowerInvariant().Split('|');
                if (!whiteList.Any(e => documentPath.EndsWith(e)))
                {
                    throw new InvalidOperationException("Estensione non valida per: " + documentPath);
                }
            }

            var document = new FileDocumentInfo(new FileInfo(documentPath));

            if (Parameters.SignatureValidationEnabled)
            {
                ValidateResultModel validateResult = _dssService.Validate(document.Name, document.Stream);
                if (!validateResult.IsValid)
                {
                    throw new SignatureDocumentValidationException(document.FileInfo.FullName, validateResult.ErrorMessages, validateResult.ToRetry);
                }
            }

            var attributes = new List <IDictionary <string, string> > {
                GetPropertiesDictionary(deserialized.Chiave)
            };

            if (deserialized.Componente != null)
            {
                attributes.Add(GetPropertiesDictionary(deserialized.Componente));
            }
            if (deserialized.Dati != null)
            {
                attributes.Add(GetPropertiesDictionary(deserialized.Dati));
            }
            if (deserialized.Revisione != null)
            {
                attributes.Add(GetPropertiesDictionary(deserialized.Revisione));
            }

            var result = new Dictionary <string, string>();

            foreach (var item in attributes)
            {
                result = result
                         .Concat(item.Where(a => !result.ContainsKey(a.Key)))
                         .ToDictionary(a => a.Key, a => a.Value);
            }

#if DEBUG
            result["Numero"] = Guid.NewGuid().ToString("N");
            FileLogger.Info(LoggerName, "#if DEBUG: modificato attributo Numero in: " + result["Numero"]);

            var flattened = result.Select(d => string.Format("{0}: {1}", d.Key, d.Value));
            var output    = string.Join("\r\n", flattened);
#endif

            document.AddAttributes(result);
            EvaluateBySignInfo(document);

            return(new List <FileDocumentInfo> {
                document
            });
        }