Пример #1
0
        private ICollection <BiblosDocumentInfo> FillUDSDocuments(Helpers.UDS.Document document)
        {
            if (document == null || document.Instances == null)
            {
                return(new List <BiblosDocumentInfo>());
            }

            IList <BiblosDocumentInfo> docInfos = new List <BiblosDocumentInfo>();

            foreach (DocumentInstance instance in document.Instances)
            {
                IList <BiblosDocumentInfo> bibDocs = BiblosDocumentInfo.GetDocuments(Guid.Parse(instance.StoredChainId));
                foreach (BiblosDocumentInfo doc in bibDocs)
                {
                    docInfos.Add(doc);
                }
            }

            return(docInfos.ToList());
        }
Пример #2
0
        private int countAttachments(Protocol protocol)
        {
            if (protocol.IdAttachments.GetValueOrDefault(0) > 0)
            {
                try
                {
                    var chain  = new UIDChain(protocol.Location.ProtBiblosDSDB, protocol.IdAttachments.Value);
                    var result = BiblosDocumentInfo.GetDocuments(chain);

                    if (!result.IsNullOrEmpty())
                    {
                        return(result.Count);
                    }
                }
                catch (Exception ex)
                {
                    string message = "countAttachments: " + ex.Message;
                    throw new Exception(message, ex);
                }
            }
            return(0);
        }
Пример #3
0
        /// <summary> Esegue gli invii per la PECMailBox passata per parametro. </summary>
        /// <param name="box">PECMailBox in cui cercare i messaggi da spedire.</param>
        public void Process(PECMailBox box, string password)
        {
            FileLogger.Info(_loggerName, string.Format("Avvio ciclo di invio per la casella {0} - {1}", box.Id, box.MailBoxName));

            // Gestisco la duplicazione delle PEC marchiate tali
            GenerateMultiplePecs(box);

            // Recupero da DB l'elenco delle PEC in uscita non ancora spedite (MailDate NULL). Carcio anche le PEC in stato Processing.
            bool          useStatusProcessing = true;
            IList <Int32> mail_ids            = _factory.PECMailFacade.GetOutgoingMails(box.Id, box.Configuration.MaxSendForSession, useStatusProcessing);

            FileLogger.Info(_loggerName, string.Format("Trovate {0} PEC da spedire.", mail_ids.Count));

            // Eseguo un ciclo sulle PEC da spedire fino al numero massimo di PEC gestibili per sessione di lavoro
            int successSendMail = 0;
            int errorSendMail   = 0;
            int counter         = 0;

            for (int index = 0; index < mail_ids.Count && counter < box.Configuration.MaxSendForSession; index++)
            {
                if (_cancelRequest())
                {
                    FileLogger.Info(_loggerName, "Blocco invio PEC per chiusura modulo invocata dall'utente.");
                    return;
                }

                // Avvio watch per verificare quanto ci impiega per singola mail
                //TODO : da mettere in debug mode
                Stopwatch watch = Stopwatch.StartNew();
                PECMail   mail  = MailStoreFacade.Factory.PECMailFacade.GetById(mail_ids[index]);

                if (mail.IsActive != ActiveType.Cast(ActiveType.PECMailActiveType.Active) && mail.IsActive != ActiveType.Cast(ActiveType.PECMailActiveType.Processing))
                {
                    FileLogger.Info(_loggerName, string.Format("Errore in lettura pecMail [{0}]. Lo status doveva essere 1. Possibile aggiornamento dati non previsto.", mail.Id));
                    return;
                }

                MailStoreFacade.Factory.TaskHeaderFacade.ActivatePECTaskProcess(mail);

                mail.IsActive = ActiveType.Cast(ActiveType.PECMailActiveType.Processing);
                _factory.PECMailFacade.Update(ref mail);
                FileLogger.Info(_loggerName, string.Format("Inizio processamento PEC [{0}] per invio. - Item #{1}", mail.Id, counter));

                // Preparo i dati per l'invio
                Guid      guid              = Guid.NewGuid();
                String    fullName          = string.Empty;
                IMail     iMailPec          = null;
                int       i                 = 0;
                Exception lastException     = null;
                String    errorLastSendMail = string.Empty;
                while (iMailPec == null && i < 5)
                {
                    // Salvo solamente gli errori dell'ultimo step esecuitivo
                    StringBuilder errorMessage = new StringBuilder();

                    try
                    {
                        iMailPec = PrepareEmlData(mail, guid, ref fullName, ref errorMessage);
                        if (iMailPec == null)
                        {
                            FileLogger.Error(_loggerName, string.Format("Tentativo di creazione eml {0}/5 saltato per massimo numero di elementi in Temp raggiunto per la PEC [{1}]", i + 1, mail.Id));
                        }
                    }
                    catch (Exception ex)
                    {
                        string errMsg = string.Format("Errore in fase di inserimento in Biblos per invio della PEC [{0}] - Tentativo {1}/5", mail.Id, i + 1);
                        errorMessage.Append(errMsg);
                        FileLogger.Error(_loggerName, errMsg, ex);
                        lastException = ex;

                        if (_cancelRequest())
                        {
                            String message = "Blocco invio PEC per chiusura modulo invocata dall'utente a causa di errore in fase di preparazione dati EML.";
                            errorMessage.Append(message);
                            _factory.PECMailLogFacade.Warning(ref mail, message);
                            FileLogger.Info(_loggerName, message);
                            return;
                        }

                        Thread.Sleep(1000 * 30);
                    }
                    finally
                    {
                        errorLastSendMail = errorMessage.ToString();
                        i++;
                    }
                }

                // Ho eseguito operazioni importanti per cui libero la memoria
                GC.Collect();

                // Se a questo punto non sono riuscito ad ottenere un oggetto iMail significa che ci sono problemi su Biblos o su FileSystem,
                // quindi notifico, blocco e procedo oltre
                if (iMailPec == null)
                {
                    String errorResult = string.Format("La PEC {0} della casella {1} - {2} non è stata correttamente inserita in Biblos per 5 volte. La PEC non è stata inviata ed è stata disattivata (isActive = 255) e dovrà essere riattivata previa verifica dell'errore.", mail.Id, box.Id, box.MailBoxName);
                    mail.IsActive = ActiveType.Cast(ActiveType.PECMailActiveType.Error);
                    _factory.PECMailFacade.UpdateOnly(ref mail);
                    _factory.PECMailLogFacade.Error(ref mail, string.Concat(errorResult, errorLastSendMail));
                    MailStoreFacade.SetPECMailTaskError(mail);
                    throw new Exception(errorResult, lastException);
                }

                // Se sono qui significa che tutti i dati su Biblos sono stati memorizzati
                // Spedisco la PEC via SMTP
                try
                {
                    if (SendMail(box, iMailPec, mail, guid, password))
                    {
                        // Se sono riuscito ad inviare allora salvo su Server via IMAP
                        successSendMail++;

                        try
                        {
                            //Aggiorno l'attributo MailDate per l'archivio di conservazione
                            BiblosDocumentInfo mainInfo = BiblosDocumentInfo.GetDocuments(mail.Location.ConservationServer, mail.IDMailContent).SingleOrDefault();
                            FileLogger.Info(_loggerName, "Tentativo di aggiornare attributo MailDate");
                            mainInfo.AddAttribute("MailDate", mail.MailDate.Value.ToString(new CultureInfo("it-IT")
                            {
                                DateTimeFormat = new DateTimeFormatInfo {
                                    ShortDatePattern = "dd/MM/yyyy"
                                }
                            }), true);
                            mainInfo.Update("BibloDS");
                            FileLogger.Info(_loggerName, string.Format("Attributi della PEC con ID {0} aggiornati.", mail.Id));
                        }
                        catch (Exception ex)
                        {
                            _factory.PECMailLogFacade.Error(ref mail, string.Format("Errore in fase di aggiornamento attributi conservazione: {0}", ex.Message));
                            _sendMessage(string.Format("Errore in fase di aggiornamento attributi conservazione: {0} - Stacktrace: {1}", ex.Message, _fullStacktrace(ex)));
                        }

                        try
                        {
                            mail.IsActive = ActiveType.Cast(ActiveType.PECMailActiveType.Active);
                            _factory.PECMailFacade.UpdateOnly(ref mail);

                            SaveMail(box, iMailPec, mail, password);
                        }
                        catch (Exception ex)
                        {
                            _factory.PECMailLogFacade.Error(ref mail, string.Format("Errore in fase di salvataggio mail su IMAP: {0}", ex.Message));
                            _sendMessage(string.Format("Errore in fase di salvataggio mail su IMAP: {0} - Stacktrace: {1}", ex.Message, _fullStacktrace(ex)));
                        }

                        MailStoreFacade.CompletePECMailTask(mail);
                        // Pulisco eventuali dati sporchi rimanenti
                        CleanEmlData(mail.Id, _parameters.TempFolder);
                    }
                    else
                    {
                        errorSendMail++;
                    }
                }
                catch (Exception ex)
                {
                    _factory.PECMailLogFacade.Error(ref mail, string.Format("Errore in fase di invio mail: {0}", ex.Message));
                    _sendMessage(string.Format("Errore in fase di invio mail: {0} - Stacktrace: {1}", ex.Message, _fullStacktrace(ex)));
                    MailStoreFacade.SetPECMailTaskError(mail);
                }

                // Fermo il Watch e registro il LOG
                watch.Stop();
                FileLogger.Info(_loggerName, string.Format("Fine processamento PEC [{0}] per invio. Gestione avvenuta in {1} millisecondi. Item #{2}", mail.Id, watch.ElapsedMilliseconds, counter));

                // Procedo con la PEC successiva
                counter++;

                // Fermo il thread per non sovraccaricare troppo i sistemi
                if (_parameters.SendSleep > 0)
                {
                    Thread.Sleep(1000 * _parameters.SendSleep);
                }
            }
            if (successSendMail > 0)
            {
                _factory.PECMailboxLogFacade.InsertLog(ref box, string.Format("PEC Inviate {0} con successo", successSendMail), PECMailBoxLogFacade.PecMailBoxLogType.Sent);
            }
            if (errorSendMail > 0)
            {
                _factory.PECMailboxLogFacade.InsertLog(ref box, string.Format("Ci sono {0} PecMail da controllare", errorSendMail), PECMailBoxLogFacade.PecMailBoxLogType.SentError);
            }

            FileLogger.Info(_loggerName, string.Format("Fine ciclo di invio per la casella {0} - {1}", box.Id, box.MailBoxName));
        }
Пример #4
0
        /// <summary>
        /// Archivia gli allegati del protocollo.
        /// </summary>
        /// <param name="sessionId">Identificativo della sessione di lavoro.</param>
        /// <param name="protocol">Protocollo di riferimento.</param>
        /// <returns></returns>
        private IList <int> archiveAttachments(string sessionId, Protocol protocol)
        {
            if (!protocol.IdAttachments.HasPositiveValue())
            {
                return(null);
            }

            // Recupero gli allegati da Biblos.
            UIDLocation location = new UIDLocation(protocol.Location.ProtBiblosDSDB);
            IList <BiblosDocumentInfo> attachments = null;

            try
            {
                UIDChain attachmentsUid = new UIDChain(location, protocol.IdAttachments.Value);
                attachments = BiblosDocumentInfo.GetDocuments(attachmentsUid);
            }
            catch (Exception ex)
            {
                string message = "archiveAttachments: errore in recupero documenti da Biblos. {0} - {1}";
                message = string.Format(message, ex.Source, ex.Message);
                throw new Exception(message, ex);
            }

            if (attachments.IsNullOrEmpty())
            {
                return(null);
            }

            // Recupero il dizionario degli attributi.
            IDictionary <string, string> attributes = null;

            try
            {
                attributes = getAttachmentAttributes(protocol);
            }
            catch (Exception ex)
            {
                string message = "archiveAttachments: errore in recupero dizionario degli attributi. {0} - {1}";
                message = string.Format(message, ex.Source, ex.Message);
                throw new Exception(message, ex);
            }

            // Archivio gli allegati.
            IList <int> archived = new List <int>();
            int         counter  = 1;

            try
            {
                foreach (var item in attachments)
                {
                    attributes["Numero Allegato"] = counter.ToString();
                    var pid    = getProductId(item.Name);
                    var fields = attributes.Keys.ToArray();
                    var values = attributes.Values.ToArray();
                    int result = -1;

                    var message = string.Format("TopMedia Archive - sessionid: {0}, attachmenttype: {1}, fields: {2}, values: {3}, name: {4}, stream: {5}, pid: {6}",
                                                sessionId,
                                                DocSuiteContext.Current.ProtocolEnv.TopMediaParameters.AttachmentType,
                                                fields.Length, values.Length,
                                                item.Name, item.Stream.Length,
                                                pid);
                    FileLogger.Info("FileLog", message);
#if DEBUG
                    result = counter;
#else
                    result = Services.TopMedia.Service.Archive(sessionId, DocSuiteContext.Current.ProtocolEnv.TopMediaParameters.AttachmentType, fields, values, item.Name, item.Stream, pid);
#endif
                    FileLogger.Info("FileLog", "result: " + result.ToString());
                    archived.Add(result);
                    counter++;
                }
            }
            catch (Exception ex)
            {
                string message = "archiveAttachments: errore in archiviazione documento. {0} - {1}";
                message = string.Format(message, ex.Source, ex.Message);
                throw new Exception(message, ex);
            }
            return(archived);
        }
        public DocumentInfo GetDocumentUnitChainsDocuments(ICollection <DocumentUnitChain> documentUnitChains, IDictionary <Model.Entities.DocumentUnits.ChainType, string> seriesCaptionLabel, bool?forceAuthorization = null)
        {
            if (documentUnitChains != null && documentUnitChains.Count > 0)
            {
                DocumentUnit documentUnit = documentUnitChains.First().DocumentUnit;
                FolderInfo   mainFolder   = new FolderInfo
                {
                    Name = $"{documentUnit.DocumentUnitName} {documentUnit.Title}",
                    ID   = documentUnit.UniqueId.ToString()
                };

                FolderInfo           folderDoc;
                BiblosDocumentInfo[] docs;
                string folderName;
                foreach (DocumentUnitChain chain in documentUnitChains.Where(f => f.ChainType <= ChainType.UnpublishedAnnexedChain || f.ChainType == ChainType.DematerialisationChain).OrderBy(x => x.ChainType))
                {
                    docs      = null;
                    folderDoc = new FolderInfo
                    {
                        Parent = mainFolder
                    };
                    folderName = string.Empty;
                    switch (chain.ChainType)
                    {
                    case ChainType.MainChain:
                    {
                        folderName = "Documento";
                        if (documentUnit.Environment == (int)Data.DSWEnvironment.DocumentSeries && seriesCaptionLabel.ContainsKey(Model.Entities.DocumentUnits.ChainType.MainChain))
                        {
                            folderName = seriesCaptionLabel[Model.Entities.DocumentUnits.ChainType.MainChain];
                        }
                        folderDoc.Name = folderName;
                        break;
                    }

                    case ChainType.AttachmentsChain:
                    {
                        folderDoc.Name = "Allegati (parte integrante)";
                        break;
                    }

                    case ChainType.AnnexedChain:
                    {
                        folderName = "Annessi (non parte integrante)";
                        if (documentUnit.Environment == (int)Data.DSWEnvironment.DocumentSeries && seriesCaptionLabel.ContainsKey(Model.Entities.DocumentUnits.ChainType.AnnexedChain))
                        {
                            folderName = seriesCaptionLabel[Model.Entities.DocumentUnits.ChainType.AnnexedChain];
                        }
                        folderDoc.Name = folderName;
                        break;
                    }

                    case ChainType.UnpublishedAnnexedChain:
                    {
                        folderName = "Annessi non pubblicati";
                        if (documentUnit.Environment == (int)Data.DSWEnvironment.DocumentSeries && seriesCaptionLabel.ContainsKey(Model.Entities.DocumentUnits.ChainType.UnpublishedAnnexedChain))
                        {
                            folderName = seriesCaptionLabel[Model.Entities.DocumentUnits.ChainType.UnpublishedAnnexedChain];
                        }
                        folderDoc.Name = folderName;
                        break;
                    }

                    case ChainType.DematerialisationChain:
                    {
                        folderDoc.Name = "Attestazione di conformità";
                        break;
                    }

                    default:
                        break;
                    }
                    docs = BiblosDocumentInfo.GetDocuments(chain.IdArchiveChain).ToArray();
                    if (docs != null)
                    {
                        //TODO: attributi da non salvare in Biblos
                        foreach (BiblosDocumentInfo doc in docs)
                        {
                            doc.AddAttribute(BIBLOS_ATTRIBUTE_Environment, documentUnit.Environment.ToString());
                            doc.AddAttribute(BIBLOS_ATTRIBUTE_Year, documentUnit.Year.ToString());
                            doc.AddAttribute(BIBLOS_ATTRIBUTE_Number, documentUnit.Number.ToString());
                            doc.AddAttribute(BIBLOS_ATTRIBUTE_UniqueId, documentUnit.UniqueId.ToString());
                            if (chain.DocumentUnit != null && chain.DocumentUnit.UDSRepository != null)
                            {
                                UDSModel model = UDSModel.LoadXml(chain.DocumentUnit.UDSRepository.ModuleXML);
                                if (!model.Model.StampaConformeEnabled)
                                {
                                    doc.AddAttribute(BIBLOS_ATTRIBUTE_Disabled, bool.TrueString);
                                }
                            }
                            if (forceAuthorization.HasValue && forceAuthorization.Value)
                            {
                                doc.AddAttribute(BIBLOS_ATTRIBUTE_UserVisibilityAuthorized, bool.TrueString);
                            }
                        }
                        folderDoc.AddChildren(docs);
                    }
                }

                return(mainFolder);
            }
            return(null);
        }