Esempio n. 1
0
        /// <summary>
        /// Metodo per il salvataggio di un DataSet in Serie AVCP
        /// </summary>
        /// <param name="pub">Oggetto da salvare</param>
        /// <param name="item">DocumentSeriesItem in cui deve essere salvato</param>
        /// <param name="username">Nome dell'operatore che esegue il savataggio</param>
        /// <returns>Restituisce l'oggetto contenente tutte le informazioni sull'importazione eseguita</returns>
        public SetDataSetResult SetDataSetPub(pubblicazione pub, DocumentSeriesItem item, string username, bool saveAlways)
        {
            if (pub == null)
            {
                throw new ArgumentNullException("pub", "Oggetto [pubblicazione] nullo");
            }

            // Creo l'oggetto di ritorno
            var tor = new SetDataSetResult();

            tor.Item = item;

            try
            {
                // Recupero il documento principale
                tor.Chain = FacadeFactory.Instance.DocumentSeriesItemFacade.GetMainChainInfo(tor.Item);
            }
            catch (Exception ex)
            {
                throw new SetDataSetResultException(tor, "Errore in fase di recupero documento catena principale.", ex);
            }

            try
            {
                // Verifico data ultimo aggiornamento
                tor.Step = 100;

                if (!saveAlways && !tor.Chain.Documents.IsNullOrEmpty() && tor.Chain.Attributes.ContainsKey(AttributeDataUltimoAggiornamento))
                {
                    DateTime lastUpdate = DateTime.MinValue;
                    if (!DateTime.TryParse(tor.Chain.Attributes[AttributeDataUltimoAggiornamento], out lastUpdate))
                    {
                        tor.Chain.AddAttribute(AttributeDataUltimoAggiornamento, pub.metadata.dataUltimoAggiornamentoDataset.ToString("s"));
                    }
                    tor.LastUpdate = lastUpdate;
                    FileLogger.Debug(LoggerName, string.Format("tor.LastUpdate = {0}", tor.LastUpdate.Date));
                    FileLogger.Debug(LoggerName, string.Format("pub.metadata.dataUltimoAggiornamentoDataset.Date = {0}", pub.metadata.dataUltimoAggiornamentoDataset.Date));

                    // Aggiorno solo se la data in arrivo è maggiore di quella salvata
                    if (pub.metadata.dataUltimoAggiornamentoDataset.Date <= tor.LastUpdate.Date)
                    {
                        tor.Updated = false;
                        return(tor);
                    }
                }
                tor.Updated = true;
            }
            catch (Exception ex)
            {
                throw new SetDataSetResultException(tor, "Errore in fase di verifica data ultimo aggiornamento.", ex);
            }

            try
            {
                // Aggiornamento necessario, eseguo eventaule Flush del documento
                tor.Step = 200;
                if (!tor.Chain.Documents.IsNullOrEmpty())
                {
                    FlushDocuments(tor.Item);
                    tor.Flushed = true;
                    // Ricarico la nuova catena creata
                    tor.Chain = FacadeFactory.Instance.DocumentSeriesItemFacade.GetMainChainInfo(tor.Item);
                }
            }
            catch (Exception ex)
            {
                throw new SetDataSetResultException(tor, "Errore in fase di Flush del documento.", ex);
            }

            try
            {
                // Salvo il documento nella catena
                tor.Step = 300;
                tor.SerializedDataSet = AVCPHelper.Serialize(pub);
                var doc = new MemoryDocumentInfo(tor.SerializedDataSet.ToBytes(), "dataset.xml", "");
                tor.Chain.AddDocument(doc);
            }
            catch (Exception ex)
            {
                throw new SetDataSetResultException(tor, "Errore in fase di salvataggio del documento in catena.", ex);
            }

            try
            {
                // Riporto i Metadati in Serie Documentale
                tor.Step = 400;

                tor.Chain.AddAttribute(AttributeUrlFile, string.Format(DocSuiteContext.Current.ProtocolEnv.AVCPDatasetUrlMask, tor.Item.Id));
                if (pub.metadata.dataUltimoAggiornamentoDataset != DateTime.MinValue)
                {
                    tor.Chain.AddAttribute(AttributeDataUltimoAggiornamento, pub.metadata.dataUltimoAggiornamentoDataset.ToString("s"));
                }
                if (pub.metadata.licenza != null)
                {
                    tor.Chain.AddAttribute(AttributeLicenza, pub.metadata.licenza.ToString());
                }
                tor.Chain.AddAttribute(AttributeAbstract, pub.metadata.@abstract);
                tor.Chain.AddAttribute(AttributeAnnoRiferimento, pub.metadata.annoRiferimento.ToString());
                tor.Chain.AddAttribute(AttributeTitolo, pub.metadata.titolo);
                if (pub.metadata.dataPubblicazioneDataset != DateTime.MinValue)
                {
                    tor.Chain.AddAttribute(AttributeDataPubblicazione, pub.metadata.dataPubblicazioneDataset.ToString("s"));
                }
                tor.Chain.AddAttribute(AttributeEntePubblicatore, pub.metadata.entePubblicatore);
            }
            catch (Exception ex)
            {
                throw new SetDataSetResultException(tor, "Errore in fase di impostazione attributi in catena.", ex);
            }

            try
            {
                // Eseguo il salvataggio dell'Item
                tor.Step = 500;
                FacadeFactory.Instance.DocumentSeriesItemFacade.UpdateDocumentSeriesItem(tor.Item, tor.Chain, username, $"Modificata registrazione AVCP {tor.Item.Year:0000}/{tor.Item.Number:0000000}");

                // Invio comando di update alle WebApi
                if (tor.Item.Status == DocumentSeriesItemStatus.Active)
                {
                    FacadeFactory.Instance.DocumentSeriesItemFacade.SendUpdateDocumentSeriesItemCommand(tor.Item);
                }

                tor.Saved = true;
            }
            catch (Exception ex)
            {
                throw new SetDataSetResultException(tor, "Errore in fase di salvataggio finale.", ex);
            }

            return(tor);
        }
Esempio n. 2
0
        public void ElaborateDocument(HttpContext context)
        {
            Guid idResolution = context.Request.QueryString.GetValueOrDefault("UniqueId", Guid.Empty);

            byte[] stream = { };

            try
            {
                Resolution resolution = GetResolution(idResolution);
                if (!CheckValidity(context, resolution))
                {
                    return;
                }
                string cached_file_path = Path.Combine(CachePath, string.Concat(resolution.UniqueId.ToString(), ".pdf"));
                if (!File.Exists(cached_file_path))
                {
                    DocumentUnitChain documentChain = GetDocumentUnitChain(idResolution, ChainType.MainOmissisChain);
                    if (documentChain == null)
                    {
                        documentChain = GetDocumentUnitChain(idResolution, ChainType.MainChain);
                    }

                    if (documentChain == null)
                    {
                        ElaborateException(context);
                        return;
                    }

                    IList <BiblosDocumentInfo> documents = BiblosDocumentInfo.GetDocumentsLatestVersion(string.Empty, documentChain.IdArchiveChain);
                    if (documents == null || !documents.Any())
                    {
                        ElaborateException(context);
                        return;
                    }

                    IEnumerable <byte[]> streams = documents.Select(f => !ViewLockedPdf ? f.GetPdfStream() : Services.StampaConforme.Service.ConvertToSimplePdf(f.Stream, "pdf"));

                    if (MergeAllChainDocuments)
                    {
                        //recupero gli allegati
                        DocumentUnitChain attachmentsChain = GetDocumentUnitChain(idResolution, ChainType.AttachmentOmissisChain);
                        if (attachmentsChain == null)
                        {
                            attachmentsChain = GetDocumentUnitChain(idResolution, ChainType.AttachmentsChain);
                        }

                        if (attachmentsChain != null)
                        {
                            IList <BiblosDocumentInfo> attachmentDocuments = BiblosDocumentInfo.GetDocumentsLatestVersion(string.Empty, attachmentsChain.IdArchiveChain);
                            if (attachmentDocuments != null && attachmentDocuments.Any())
                            {
                                streams = streams.Concat(attachmentDocuments.Select(f => !ViewLockedPdf ? f.GetPdfStream() : Services.StampaConforme.Service.ConvertToSimplePdf(f.Stream, "pdf")));
                            }
                        }

                        //recupero il frontalino di pubblicazione
                        DocumentUnitChain frontespieceChain = GetDocumentUnitChain(idResolution, ChainType.FrontespizioChain);
                        if (frontespieceChain != null)
                        {
                            IList <BiblosDocumentInfo> frontespieceDocuments = BiblosDocumentInfo.GetDocumentsLatestVersion(string.Empty, frontespieceChain.IdArchiveChain);
                            if (frontespieceDocuments != null && frontespieceDocuments.Any())
                            {
                                streams = streams.Concat(frontespieceDocuments.Select(f => !ViewLockedPdf ? f.GetPdfStream() : Services.StampaConforme.Service.ConvertToSimplePdf(f.Stream, "pdf")));
                            }
                        }
                    }


                    stream = MergePDF(streams);
                    if (ViewLockedPdf)
                    {
                        using (MemoryDocumentInfo mdi = new MemoryDocumentInfo(stream, cached_file_path))
                        {
                            stream = mdi.GetPdfLocked(documents.First().Signature, PdfWatermark);
                        }
                    }

                    if (!Encoding.Default.GetString(stream, 0, 4).Equals("%PDF"))
                    {
                        throw new Exception("Il pdf non può essere visualizzato a causa di un errore di conversione.", new Exception("Lo stream non inizia con '%PDF'"));
                    }
                    File.WriteAllBytes(cached_file_path, stream);
                }
                else
                {
                    stream = File.ReadAllBytes(cached_file_path);
                }

                ElaborateStream(context, stream, string.Empty);
            }
            catch (Exception ex)
            {
                FileLogger.Error(LogName.BiblosServiceLog, ex.Message, ex);
                ElaborateException(context);
                return;
            }
        }
Esempio n. 3
0
        public override void SingleWork()
        {
            IList <DSWMessage> messages = Facade.MessageFacade.GetMessagesToSend(DSWMessage.MessageTypeEnum.Email, DSWMessage.MessageStatusEnum.Active).Take(Parameters.MaxMailsForSession).ToList();

            FileLogger.Info(Name, string.Format("Trovati {0} messaggi da spedire.", messages.Count));
            foreach (DSWMessage message in messages)
            {
                if (Cancel)
                {
                    FileLogger.Info(Name, "Chiusura modulo invocata dall'utente.");
                    return;
                }

                FileLogger.Info(Name, String.Format("Inizio elaborazione messaggio [{0}]", message.Id));
                try
                {
                    MailMessage            item           = new MailMessage();
                    MailAddress            originalSender = null;
                    IList <MessageContact> mittente       = Facade.MessageContactFacade.GetByMessage(message, MessageContact.ContactPositionEnum.Sender) ?? new List <MessageContact>();
                    FileLogger.Debug(Name, String.Format("Numero mittenti: {0}", mittente.Count));
                    MessageContactEmail mittenteEmail = null;

                    if (mittente.Any())
                    {
                        mittenteEmail = Facade.MessageContactEmailFacade.GetByContact(mittente.First());
                    }

                    if (mittenteEmail != null)
                    {
                        item.From      = new MailAddress(mittenteEmail.Email, mittenteEmail.Description);
                        originalSender = item.From;
                    }

                    FileLogger.Debug(Name, String.Format("Parameters.Sender: {0}", Parameters.Sender));
                    if (!string.IsNullOrEmpty(Parameters.Sender))
                    {
                        item.From = new MailAddress(Parameters.Sender);
                        if (mittenteEmail != null)
                        {
                            item.ReplyToList.Add(new MailAddress(mittenteEmail.Email, mittenteEmail.Description));
                        }
                    }
                    FileLogger.Debug(Name, String.Format("item.From = {0}", item.From));
                    if (item.From == null)
                    {
                        throw new ArgumentNullException("Email sender is not specified");
                    }


                    IList <MessageContact> destinatari = Facade.MessageContactFacade.GetByMessage(message) ?? new List <MessageContact>();
                    FileLogger.Debug(Name, string.Format("Numero destinatari: {0}", destinatari.Count));
                    MessageContactEmail messageContactEmail = null;
                    foreach (MessageContact messageContact in destinatari)
                    {
                        messageContactEmail = Facade.MessageContactEmailFacade.GetByContact(messageContact);
                        if (!string.IsNullOrEmpty(messageContactEmail.Email) && messageContact.ContactPosition != MessageContact.ContactPositionEnum.Sender)
                        {
                            switch (messageContact.ContactPosition)
                            {
                            case MessageContact.ContactPositionEnum.Recipient:
                            {
                                item.To.Add(new MailAddress(messageContactEmail.Email, messageContactEmail.Description));
                                break;
                            }

                            case MessageContact.ContactPositionEnum.RecipientCc:
                            {
                                item.CC.Add(new MailAddress(messageContactEmail.Email, messageContactEmail.Description));
                                break;
                            }

                            case MessageContact.ContactPositionEnum.RecipientBcc:
                            {
                                item.Bcc.Add(new MailAddress(messageContactEmail.Email, messageContactEmail.Description));
                                break;
                            }

                            default:
                                break;
                            }
                            FileLogger.Debug(Name, $"Aggiunto destinatario {messageContactEmail.Description} ({messageContactEmail.Email}) in {messageContact.ContactPosition}");
                        }
                    }


                    MessageEmail email = Facade.MessageEmailFacade.GetByMessage(message);

                    item.Subject = !string.IsNullOrEmpty(email.Subject) ? email.Subject : Parameters.DefaultSubject;
                    item.Subject = string.IsNullOrEmpty(item.Subject) ? item.Subject : item.Subject.Replace("\r\n", String.Empty).Replace("\n", String.Empty);
                    FileLogger.Debug(Name, "item.Subject = " + item.Subject);

                    item.Body = !string.IsNullOrEmpty(email.Body) ? email.Body : Parameters.DefaultBody;
                    FileLogger.Debug(Name, "item.Body = " + item.Body);

                    item.IsBodyHtml = true;

                    var allegati = Facade.MessageAttachmentFacade.GetByMessageAsDocumentInfoListForceStream(message);

                    FileLogger.Debug(Name, String.Format("Numero allegati: {0}", allegati.Count));
                    foreach (var allegato in allegati)
                    {
                        FileLogger.Debug(Name, string.Format("Signature documento {0}.", allegato.Signature));
                        item.Attachments.Add(new Attachment(new MemoryStream(allegato.Stream), FileHelper.ReplaceUnicode(FileHelper.ConvertUnicodeToAscii(allegato.Name)), allegato.IsCompliantPrint ? MediaTypeNames.Application.Pdf : MediaTypeNames.Application.Octet));
                        FileLogger.Debug(Name, string.Format("Allegato {0} aggiunto.", FileHelper.ReplaceUnicode(FileHelper.ConvertUnicodeToAscii(allegato.Name))));
                    }

                    // Impostazione Priority
                    item.Priority = email.Priority;
                    _mailClient   = new MailClient(
                        Parameters.ServerType.ToString(),
                        Parameters.Server, Parameters.ServerPort,
                        Parameters.AuthenticationType,
                        Parameters.UserName, Parameters.UserPassword, Parameters.UserDomain);

                    // In caso di modalità DEBUG modifico i destinatari con quello di default:
                    if (Parameters.DebugModeEnabled)
                    {
                        // Creo una nuova mail alla quale aggiungo come allegato la mail originale
                        var debugMail = new MailMessage
                        {
                            Subject = String.Format("Inoltro messaggio per DEBUG {0} -> ", email.Subject),
                            From    = item.From,
                            Body    = "In allegato la mail che sarebbe stata spedita."
                        };

                        // Aggiungo il destinatario di debug
                        debugMail.To.Add(new MailAddress(Parameters.DebugModeAddress, "DEBUG ADDRESS"));

                        // Aggiungo la mail come allegato
                        debugMail.Attachments.Add(item.ToAttachment(new DirectoryInfo(Parameters.TempFolder)));

                        // Sostituisco item con il debugMail
                        item = debugMail;

                        FileLogger.Info(Name, string.Format("Modificato l'indirizzo di invio della mail con l'indirizzo {0}.", Parameters.DebugModeAddress));
                    }
                    var emlData = _mailClient.Send(item,
                                                   !String.IsNullOrEmpty(Parameters.TempFolder) ? new DirectoryInfo(Parameters.TempFolder) : null, true,
                                                   email.IsDispositionNotification, originalSender == null ? item.From : originalSender);
                    // Salvo in Biblos l'eml inviato
                    if (message.Location != null)
                    {
                        var emlDocument = new MemoryDocumentInfo(emlData, "Messaggio.eml")
                        {
                            Signature = "*"
                        }.ArchiveInBiblos(message.Location.DocumentServer, message.Location.ProtBiblosDSDB);
                        email.EmlDocumentId = emlDocument.DocumentId;
                    }
                    email.SentDate = DateTime.Now;
                    Facade.MessageEmailFacade.Update(ref email);

                    OnSent(message);

                    FileLogger.Info(Name, string.Format("Fine elaborazione messaggio [{0}].", message.Id));
                }
                catch (Exception ex)
                {
                    OnError(message, ex);
                }
                finally
                {
                    // Attendo sempre 15 secondi tra un invio e il successivo
                    Thread.Sleep(Parameters.SleepBetweenSends * 1000);
                }
            }
            NHibernateSessionManager.Instance.CloseTransactionAndSessions();
            _mailClient = null;
        }