private void InsertProtocolLog(DocumentUnit entity, BiblosDocumentInfo documentInfo)
        {
            using (WindowsIdentity wi = (WindowsIdentity)HttpContext.Current.User.Identity)
                using (WindowsImpersonationContext wic = wi.Impersonate())
                    using (ExecutionContext.SuppressFlow())
                    {
                        ProtocolLog protocolLog = new ProtocolLog()
                        {
                            LogDescription = string.Format("\"{0}\" [{1}]", documentInfo.Name, documentInfo.DocumentId.ToString("N")),
                            Entity         = new Protocol(entity.UniqueId)
                        };

                        try
                        {
                            string actionType = EnumHelper.GetDescription(InsertActionType.ViewProtocolDocument);
                            //string actionType = "ViewProtocolDocument";
                            protocolLog = _httpClient.PostAsync(protocolLog, actionType).ResponseToModel <ProtocolLog>();
                        }
                        catch (Exception ex)
                        {
                            FileLogger.Error(LogName.FileLog, ex.Message, ex);
                            throw ex;
                        }
                        finally
                        {
                            wic.Undo();
                        }
                    }
        }
        public static int SaveJournalToBiblos(Location location, TempFileDocumentInfo document)
        {
            var uidDocument = document.ArchiveInBiblos(location.DocumentServer, location.ProtBiblosDSDB);
            // Questa chiamata potrebbe essere lenta con DB Biblos troppo grande (ENPACL)
            const int attemps       = 10;
            Exception lastException = null;

            for (var i = 0; i < attemps; i++)
            {
                try
                {
                    var bdi = new BiblosDocumentInfo(location.DocumentServer, uidDocument.DocumentId);
                    return(bdi.BiblosChainId);
                }
                catch (Exception ex)
                {
                    lastException = ex;
                    FileLogger.Error(LoggerName, string.Format("Tentativo di caricamento idBiblos #{0}/10 fallito per {1}", i, ex.Message), ex);
                    // Riposo il thread 1 minuto
                    Thread.Sleep(20000 * i);
                }
            }
            // Se sono qui significa che non sono riuscito a caricare il numero per 10 volte
            throw new Exception(String.Format("Impossibile caricare l'id Biblos per il registro corrente. GuidDocument = {0}", uidDocument), lastException);
        }
Example #3
0
        /// <summary>
        /// Crea un DeskDocumentResult da un DeskDocument
        /// </summary>
        public DeskDocumentResult CreateDeskDocumentDto(DeskDocument document, BiblosDocumentInfo biblosDocument, Location deskLocation, bool fromDb)
        {
            DeskDocumentVersion deskVersioning = null;
            DeskStoryBoard      lastStoryBoard = null;
            DeskDocumentResult  dto            = MapperDeskDocumentResult.MappingDTO(document);


            // Mappo gli oggetti di Biblos
            dto.Name               = biblosDocument.Name;
            dto.Size               = biblosDocument.Size;
            dto.IsSavedToBiblos    = true;
            dto.IsSigned           = biblosDocument.IsSigned;
            dto.BiblosSerializeKey = biblosDocument.Serialized;

            //Mappo commenti e versioning
            if (fromDb)
            {
                deskVersioning = DeskDocumentVersionFacade.GetLastVersionByIdDeskDocument(document.Id);
                lastStoryBoard = CurrentDeskStoryBoardFacade.GetLastStoryBoard(deskVersioning);
            }

            dto.LastVersion           = fromDb ? deskVersioning.Version : new decimal(1.0);
            dto.IdChainBiblos         = biblosDocument.ChainId;
            dto.IdDocumentBiblos      = biblosDocument.DocumentId;
            dto.IsJustInCollaboration = CurrentDeskCollaborationFacade.IsDocumentJustInCollaboration(document.Desk, dto.Name);

            dto.LastComment = fromDb && lastStoryBoard != null ? lastStoryBoard.Comment : string.Empty;

            return(dto);
        }
Example #4
0
        /// <summary>
        /// Aggiunge un nuovo commento allo storyboard indicando l'azione eseguita e l'utente
        /// </summary>
        /// <param name="documentName"></param>
        /// <param name="desk"></param>
        /// <param name="roleUser"></param>
        /// <param name="docVersion"></param>
        /// <param name="boardType"></param>
        private void AddCommentStoryBoard(BiblosDocumentInfo biblosDoc, Desk desk, DeskRoleUser roleUser, DeskDocumentVersion docVersion, DeskStoryBoardType boardType)
        {
            string commentStringType = string.Empty;

            switch (boardType)
            {
            case DeskStoryBoardType.CheckInComment:
                commentStringType = checkInComment;
                break;

            case DeskStoryBoardType.CheckOutComment:
                commentStringType = checkOutComment;
                break;

            case DeskStoryBoardType.UndoCheckout:
                commentStringType = undoCheckOutComment;
                break;

            case DeskStoryBoardType.SignedDocument:
                commentStringType = SIGNED_DOCUMENT_LOG_FORMAT;
                break;

            case DeskStoryBoardType.RenameDocument:
                commentStringType = renameComment;
                break;
            }

            string comment = string.Format(commentStringType, _userName, biblosDoc.Name, biblosDoc.Version);

            CurrentDeskStoryBoardFacade.AddCommentToStoryBoard(comment, desk, roleUser, docVersion, boardType);
        }
Example #5
0
        public static DocumentInstance[] GetDocumentInstances(ICollection <DocumentInfo> documents)
        {
            IList <DocumentInstance> documentInstances = new List <DocumentInstance>();

            if (documents.Any())
            {
                BiblosDocumentInfo documentStored = null;
                foreach (DocumentInfo document in documents)
                {
                    if (document is BiblosPdfDocumentInfo)
                    {
                        documentStored = document.ArchiveInBiblos(CommonShared.CurrentWorkflowLocation.ProtBiblosDSDB, Guid.Empty);
                        documentInstances.Add(new DocumentInstance
                        {
                            IdDocumentToStore = documentStored.DocumentId.ToString(),
                            DocumentName      = document.Name,
                        });
                    }
                    else
                    {
                        documentInstances.Add(new DocumentInstance {
                            StoredChainId = ((BiblosDocumentInfo)document).DocumentId.ToString()
                        });
                    }
                }
            }
            return(documentInstances.ToArray());
        }
Example #6
0
        /// <summary>
        /// 1) Annulla estrazione del file da parte dell'utente.
        /// 2) Aggiorna l'ultimo utente che ha eseguito le operazioni sul file e la data.
        /// 3) Aggiunge un commento nello storyboard.
        /// </summary>
        /// <param name="desk"></param>
        /// <param name="roleUser"></param>
        /// <param name="docVersion"></param>
        /// <param name="idDeskDocument"></param>
        /// <param name="idDocument"></param>
        /// <param name="userId"></param>
        public void UndoCheckOut(Desk desk, DeskRoleUser roleUser, DeskDocumentVersion docVersion, Guid?idDeskDocument, Guid idDocument, string userId)
        {
            BiblosDocumentInfo.UndoCheckOutDocument(idDocument, userId);
            BiblosDocumentInfo undoDoc = BiblosDocumentInfo.GetDocumentByVersion(idDocument, null, null);

            UpdateDocumentLastChages(idDeskDocument);
            AddCommentStoryBoard(undoDoc, desk, roleUser, docVersion, DeskStoryBoardType.UndoCheckout);
        }
Example #7
0
        /// <summary>
        /// Esegue l'estrazione del documento con lock esclusivo
        /// </summary>
        /// <param name="idDocument"></param>
        /// <param name="userId"></param>
        /// <param name="contentFormat"></param>
        /// <param name="returnContent"></param>
        /// <returns></returns>
        public BiblosDocumentInfo CheckOut(Desk desk, DeskRoleUser roleUser, DeskDocumentVersion docVersion, Guid?idDeskDocument, Guid idDocument, string userId, ContentFormat contentFormat, bool?returnContent)
        {
            BiblosDocumentInfo checkOutDoc = BiblosDocumentInfo.CheckOutDocument(idDocument, userId, contentFormat, returnContent);

            UpdateDocumentLastChages(idDeskDocument);
            AddCommentStoryBoard(checkOutDoc, desk, roleUser, docVersion, DeskStoryBoardType.CheckOutComment);
            return(checkOutDoc);
        }
Example #8
0
        /// <summary>
        /// Aggiorna il documento firmato in BiblosDs2010
        /// </summary>
        public BiblosDocumentInfo UpdateSignedDocument(Desk desk, DeskRoleUser roleUser, Guid idDeskDocument, BiblosDocumentInfo documentToUpdate, string userId)
        {
            DeskDocument        deskDocument    = this.GetById(idDeskDocument);
            BiblosDocumentInfo  documentUpdated = documentToUpdate.Update(userId);
            DeskDocumentVersion docVersion      = DeskDocumentVersionFacade.InsertDocumentVersion(documentUpdated.DocumentId, documentUpdated.Version, deskDocument);

            AddCommentStoryBoard(documentUpdated, desk, roleUser, docVersion, DeskStoryBoardType.SignedDocument);
            return(documentUpdated);
        }
Example #9
0
        /// <summary>
        /// CheckIn di una specifica versione del documento.
        /// </summary>
        /// <param name="idDocument"></param>
        /// <param name="docName"></param>
        /// <param name="content"></param>
        /// <param name="userId"></param>
        /// <param name="contentFormat"></param>
        /// <param name="version">Ritorna la versione corrente del documento appena inserito</param>
        /// <returns></returns>
        public BiblosDocumentInfo CheckIn(Desk desk, DeskRoleUser roleUser, Guid?idDeskDocument, Guid idDocument, string docName, byte[] content, string userId, ContentFormat contentFormat, decimal?version)
        {
            DeskDocument       deskDocument = GetById(idDeskDocument.Value, false);
            BiblosDocumentInfo newDoc       = BiblosDocumentInfo.CheckInDocument(idDocument, docName, content, userId, contentFormat, version);

            UpdateDocumentCheckIn(idDeskDocument, newDoc.DocumentId);
            decimal             newversion = version ?? newDoc.Version;
            DeskDocumentVersion docVersion = DeskDocumentVersionFacade.InsertDocumentVersion(newDoc.DocumentId, newversion, deskDocument);

            AddCommentStoryBoard(newDoc, desk, roleUser, docVersion, DeskStoryBoardType.CheckInComment);
            return(newDoc);
        }
Example #10
0
        public bool IsEmlArchiviedInBiblos(MailInfo mailInfo)
        {
            FileLogger.Info(_loggerName, "Verifica presenza PECMail in biblos.");

            PECMail            pecMail     = FacadeFactory.Instance.PECMailFacade.GetById(mailInfo.IDPECMail);
            BiblosDocumentInfo originalEml = FacadeFactory.Instance.PECMailFacade.GetPecMailContent(pecMail);

            if (originalEml != null)
            {
                string originalEmlChecksum = GetString(originalEml.Checksum);
                if (originalEmlChecksum.CompareTo(mailInfo.EmlHash) == 0)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #11
0
        public static BiblosDocumentInfo[] FillUDSDocuments(Helpers.UDS.Document document)
        {
            if (document == null || document.Instances == null)
            {
                return(new BiblosDocumentInfo[] { });
            }

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

            foreach (DocumentInstance instance in document.Instances)
            {
                bibDocs = BiblosDocumentInfo.GetDocumentsLatestVersion(Guid.Parse(instance.StoredChainId));
                foreach (BiblosDocumentInfo doc in bibDocs)
                {
                    docInfos.Add(doc);
                }
            }
            return(docInfos.ToArray());
        }
        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());
        }
        public void ElaborateDocument(HttpContext context)
        {
            Guid documentId = context.Request.QueryString.GetValueOrDefault("Id", Guid.Empty);

            byte[] stream = { };

            try
            {
                if (documentId == null)
                {
                    ElaborateException(context);
                }

                BiblosDocumentInfo documentInfo = BiblosDocumentInfo.GetDocumentByVersion(string.Empty, documentId, null, null);
                if (documentInfo == null)
                {
                    ElaborateException(context);
                }

                stream = documentInfo.GetPdfStream();
                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'"));
                }
                DocumentUnit documentUnit = GetProtocolId(documentInfo.ChainId);

                if (documentUnit != null)
                {
                    InsertProtocolLog(documentUnit, documentInfo);
                    //throw new Exception(string.Concat("DocumentUnit con IdArchiveChain ", documentInfo.ChainId, " non trovata."), new Exception("DocumentUnit non trovata."));
                }

                ElaborateStream(context, stream, string.Empty);
            }
            catch (Exception ex)
            {
                FileLogger.Error(LogName.BiblosServiceLog, ex.Message, ex);
                ElaborateException(context);
            }
        }
Example #14
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);
        }
        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);
        }
Example #16
0
        /// <summary>
        /// Aggiorna il documento firmato in BiblosDs2010
        /// </summary>
        public BiblosDocumentInfo UpdateSignedDocument(Desk desk, DeskRoleUser roleUser, DeskDocumentResult document, BiblosDocumentInfo documentToUpdate, string userId)
        {
            Guid idDeskDocument = document.IdDeskDocument.Value;

            return(this.UpdateSignedDocument(desk, roleUser, idDeskDocument, documentToUpdate, userId));
        }
Example #17
0
        private IMail GetMailMessage(Guid guid, PECMail pecMail)
        {
            MailBuilder builder = new MailBuilder();

            foreach (MailBox mailBox in MailStringToList(pecMail.MailSenders))
            {
                builder.From.Add(mailBox);
            }
            foreach (MailBox mailBox in MailStringToList(pecMail.MailRecipients))
            {
                builder.To.Add(mailBox);
            }
            foreach (MailBox mailBox in MailStringToList(pecMail.MailRecipientsCc))
            {
                builder.Cc.Add(mailBox);
            }

            builder.Subject = string.IsNullOrEmpty(pecMail.MailSubject) ? string.Empty : StringHelper.ReplaceCrLf(pecMail.MailSubject);

            // Crea il corpo del messaggio di default (non è richiesto dall'Interoperabilità) o lo legge da base dati, se indicato
            builder.Text = (string.IsNullOrEmpty(pecMail.MailBody))
                               ? string.Format("Invio protocollo \"{0}\" ({1}/{2})", pecMail.MailSubject, pecMail.Number, pecMail.Year)
                               : pecMail.MailBody;

            builder.MessageID = guid.ToString();

            if (!string.IsNullOrEmpty(pecMail.Segnatura))
            {
                // Estrae la segnatura dalla base dati e la allega alla mail in uscita
                MimeData xmlSegnatura = builder.AddAttachment(Encoding.GetEncoding(1252).GetBytes(pecMail.Segnatura));
                xmlSegnatura.ContentType = new ContentType(MimeType.Text, MimeSubtype.Xml);
                xmlSegnatura.ContentId   = "Segnatura.xml";
                xmlSegnatura.FileName    = "Segnatura.xml";
            }

            // Estrae i relativi allegati da base dati (documento ed allegati)
            if ((pecMail.Attachments != null) && (pecMail.Attachments.Count > 0))
            {
                byte[] attachmentByteArray;
                foreach (PECMailAttachment attachment in pecMail.Attachments)
                {
                    try
                    {
                        attachmentByteArray = null;
                        string attachmentName = FileHelper.ReplaceUnicode(FileHelper.ConvertUnicodeToAscii(attachment.AttachmentName));
                        if (pecMail.Location != null && !string.IsNullOrEmpty(pecMail.Location.DocumentServer) && attachment.IDDocument != Guid.Empty)
                        {
                            // Allora utilizzo l'idDocument
                            BiblosDocumentInfo doc = new BiblosDocumentInfo(pecMail.Location.DocumentServer, attachment.IDDocument);
                            attachmentByteArray = doc.Stream;
                            FileLogger.Debug(_loggerName, string.Format("Caricamento allegato {0} della PEC {1} inserito da DSW8 utilizzando l'IDDocument", attachmentName, pecMail.Id));
                        }
                        else
                        {
                            throw new Exception("L'allegato non contiene nè un idBiblos valido nè uno stream valido e pertanto non può essere inviato.");
                        }
                        MimeData document = builder.AddAttachment(attachmentByteArray);
                        if (attachmentName.EndsWith(FileHelper.EML, StringComparison.InvariantCultureIgnoreCase))
                        {
                            document.ContentType = new ContentType(MimeType.Message, MimeSubtype.Rfc822);
                        }
                        else
                        {
                            document.ContentType = new ContentType(MimeType.Application, MimeSubtype.OctetStream);
                        }
                        document.ContentId = attachmentName;
                        document.FileName  = attachmentName;
                    }
                    catch (Exception ex)
                    {
                        FileLogger.Error(_loggerName, string.Format("Errore in aggiunta allegati alla PECMail [{0}].", pecMail.Id), ex);
                    }
                }
            }

            // Estrae il messaggio di ritorno dalla base dati, se presente e lo allega alla mail in uscita
            if (pecMail.MessaggioRitornoName != null && pecMail.MessaggioRitornoStream != null)
            {
                MimeData messaggioRitornoStream = builder.AddAttachment(Encoding.GetEncoding(1252).GetBytes(pecMail.MessaggioRitornoStream));
                messaggioRitornoStream.ContentType = new ContentType(MimeType.Text, MimeSubtype.Xml);
                messaggioRitornoStream.ContentId   = pecMail.MessaggioRitornoStream;
                messaggioRitornoStream.FileName    = pecMail.MessaggioRitornoStream;
            }

            if (pecMail.MailPriority.HasValue)
            {
                switch (pecMail.MailPriority)
                {
                case -1:
                    builder.Priority = MimePriority.NonUrgent;
                    break;

                case 1:
                    builder.Priority = MimePriority.Urgent;
                    break;

                default:
                    builder.Priority = MimePriority.Normal;
                    break;
                }
            }
            else
            {
                builder.Priority = MimePriority.Normal;
            }

            return(builder.Create());
        }
Example #18
0
        private void RecoverEnvelopeAttachments(IEnumerable <PECMailBox> boxes)
        {
            var boxName = string.Empty;

            try
            {
                foreach (var box in boxes)
                {
                    boxName = string.Format("{0} - {1}", box.Id, box.MailBoxName);

                    if (CancelRequest())
                    {
                        FileLogger.Info(Name, "Chiusura modulo invocata dall'utente.");
                        return;
                    }

                    FileLogger.Info(Name, "Recupero Envelope in corso...");
                    // Recupero l'elenco delle PEC da riprocessare
                    NHibernatePECMailFinder finder = new NHibernatePECMailFinder
                    {
                        Actives      = true,
                        MailDateFrom = !Parameters.RecoverEnvelopeAttachmentStartDate.Equals(default(DateTime)) ? (DateTime?)Parameters.RecoverEnvelopeAttachmentStartDate : null,
                        MailDateTo   = !Parameters.RecoverEnvelopeAttachmentEndDate.Equals(default(DateTime)) ? (DateTime?)Parameters.RecoverEnvelopeAttachmentEndDate : null,
                        MailboxIds   = new[] { box.Id },
                    };
                    List <PECMail> pecMails = finder.DoSearch().Where(pecMail =>
                                                                      pecMail.Direction != (short)DocSuiteWeb.Data.PECMailDirection.Outgoing &&
                                                                      pecMail.IDMailContent != Guid.Empty &&
                                                                      !pecMail.LogEntries.Any(pml => pml.Type.Eq(PECMailLogType.Reprocessed.ToString()))).
                                              Take(box.Configuration.MaxReadForSession).ToList();
                    FileLogger.Info(Name, string.Format("Trovate {0} pec da riprocessare", pecMails.Count));
                    foreach (PECMail pecMail in pecMails)
                    {
                        PECMail currentPecMail = pecMail;
                        // Recupero la PEC dal server di conservazione
                        BiblosDocumentInfo originalEml = FacadeFactory.Instance.PECMailFacade.GetPecMailContent(currentPecMail);
                        if (originalEml == null)
                        {
                            continue;
                        }
                        BiblosDocumentInfo originalEnvelope = new BiblosDocumentInfo(currentPecMail.Location.DocumentServer, currentPecMail.IDEnvelope);

                        FileLogger.Info(Name, string.Format("Estrazione eml originale GUID_Chain_EML {0} PEC [{1}] da riprocessare - EML name [{2}]", currentPecMail.IDMailContent, currentPecMail.Id, originalEml.Name));
                        try
                        {
                            Guid  originalEnvelopeId = currentPecMail.IDEnvelope;
                            IMail envelope           = new MailBuilder().CreateFromEml(originalEml.Stream);
                            FileLogger.Debug(Name, "Generata busta da EML");
                            envelope.RemoveAttachments();
                            FileLogger.Debug(Name, "Rimossi allegati con successo, archiviazione in corso...");
                            MailStoreFacade.Factory.PECMailFacade.ArchiveEnvelope(ref currentPecMail,
                                                                                  envelope.Render(), originalEnvelope.Name);
                            MailStoreFacade.Factory.PECMailFacade.UpdateNoLastChange(ref currentPecMail);
                            FileLogger.Info(Name,
                                            string.Format(
                                                "Aggiornamento Envelope avvenuto correttamente: nuovo GUID_Chain [{0}]",
                                                currentPecMail.IDEnvelope));
                            MailStoreFacade.Factory.PECMailLogFacade.InsertLog(ref currentPecMail, string.Format("Ricalcolata busta: guidPrecedente [{0}] -> guidRicalcolato [{1}]", originalEnvelopeId, currentPecMail.IDEnvelope), PECMailLogType.Reprocessed);
                        }
                        catch (Exception ex)
                        {
                            FileLogger.Error(Name, "Errore in fase di ricalcolo busta.", ex);
                            SendMessage(
                                string.Format("Errore in fase di ricalcolo busta per la PEC {1} - Guid: [{2}].{0}Stacktrace: {3}", Environment.NewLine, pecMail.Id, pecMail.IDEnvelope, FullStacktrace(ex)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FileLogger.Error(Name, string.Format("Errore in [RecoverEnvelopeAttachments] - Casella [{0}].", boxName), ex);
                SendMessage(string.Format("Errore in [RecoverEnvelopeAttachments] - Casella [{0}]. \nErrore: {1} \nStacktrace: {2}", boxName, ex.Message, FullStacktrace(ex)));
            }
            finally
            {
                // Libero le risorse
                NHibernateManager.NHibernateSessionManager.Instance.CloseTransactionAndSessions();
                GC.Collect(GC.MaxGeneration);
            }
        }
Example #19
0
        /// <summary>
        /// Archivia il documento di un protocollo.
        /// </summary>
        /// <param name="sessionId">Identificativo della sessione di lavoro.</param>
        /// <param name="protocol">Protocollo di riferimento.</param>
        /// <returns></returns>
        private int archiveDocument(string sessionId, Protocol protocol)
        {
            if (!protocol.IdDocument.HasValue || protocol.IdDocument < 1)
            {
                throw new Exception("archiveDocument: IdDocument del protocollo mancante o non valido.");
            }

            // Recupero il documento da Biblos.
            DocumentInfo document = null;

            try
            {
                document = new BiblosDocumentInfo(protocol.Location.ProtBiblosDSDB, protocol.IdDocument.Value);
            }
            catch (Exception ex)
            {
                string message = "archiveDocument: errore in recupero documento da Biblos. {0} - {1}";
                message = string.Format(message, ex.Source, ex.Message);
                throw new Exception(message, ex);
            }

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

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

            // Archivio il documento.
            int archived = -1;

            try
            {
                var pid    = getProductId(document.Name);
                var fields = attributes.Keys.ToArray();
                var values = attributes.Values.ToArray();

                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,
                                            document.Name, document.Stream.Length,
                                            pid);
                FileLogger.Info("FileLog", message);
#if DEBUG
                archived = 123;
#else
                archived = Services.TopMedia.Service.Archive(sessionId, DocSuiteContext.Current.ProtocolEnv.TopMediaParameters.DocumentType, fields, values, document.Name, document.Stream, pid);
                Services.TopMedia.Service.TryLogout(sessionId);
#endif
                FileLogger.Info("FileLog", "archived: " + archived.ToString());
            }
            catch (Exception ex)
            {
                string message = "archiveDocument: errore in archiviazione documento. {0} - {1}";
                message = string.Format(message, ex.Source, ex.Message);
                throw new Exception(message, ex);
            }
            return(archived);
        }
Example #20
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));
        }
        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);
        }
Example #22
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;
            }
        }
Example #23
0
 /// <summary>
 /// Verifica se un documento è in checkout
 /// </summary>
 /// <param name="idDocument"></param>
 /// <returns></returns>
 public bool IsCheckOut(Guid idDocument)
 {
     return(BiblosDocumentInfo.IsCheckOutDocument(idDocument));
 }
Example #24
0
 /// <summary>
 /// Verifica l'utente che ha eseguito il checkout
 /// </summary>
 /// <param name="idDocument"></param>
 /// <returns></returns>
 public string IdUserCheckOut(Guid?idDeskDocument, Guid idDocument)
 {
     return(BiblosDocumentInfo.IdUserCheckOutDocument(idDocument));
 }
Example #25
0
 /// <summary>
 /// Crea un DeskDocumentResult da un DeskDocument
 /// </summary>
 public DeskDocumentResult CreateDeskDocumentDto(DeskDocument document, BiblosDocumentInfo biblosDocument, bool fromDb)
 {
     return(this.CreateDeskDocumentDto(document, biblosDocument, document.Desk.Container.DeskLocation, fromDb));
 }
Example #26
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);
        }
Example #27
0
 public BiblosDocumentInfo GetLastDocumentVersion(DeskDocumentResult document)
 {
     return(BiblosDocumentInfo.GetDocumentByVersion(document.IdDocumentBiblos.Value, null, true));
 }
Example #28
0
 /// <summary>
 /// Crea un DeskDocumentResult da un DeskDocument non salvato sul DB
 /// </summary>
 public DeskDocumentResult CreateDeskDocumentDto(DeskDocument document, BiblosDocumentInfo biblosDocument, Location deskLocation)
 {
     return(this.CreateDeskDocumentDto(document, biblosDocument, deskLocation, false));
 }
Example #29
0
 public void RenameDoc(Desk desk, DeskRoleUser roleUser, DeskDocumentVersion docVersion, BiblosDocumentInfo document, string userId)
 {
     Service.UpdateDocument(document, DocSuiteContext.Current.User.FullUserName);
     AddCommentStoryBoard(document, desk, roleUser, docVersion, DeskStoryBoardType.RenameDocument);
 }