public static string GetSignedDerDocument(Data.Model.DER der, ElectronicSafeDocumentBL.DocumentType ESDocumentType, bool isUrl)
        {
            string file = string.Empty;
            string filename = string.Empty;

            Data.Model.CustomerProspect customer = der.CustomerProspect;
            string docType = "";
            DTPClient.DocumentTypes dtpDocType = DTPClient.DocumentTypes.CONTRACT;

            switch (ESDocumentType)
            {
                case ElectronicSafeDocumentBL.DocumentType.FIL:
                    docType = ElectronicSafeDocumentBL.DocumentType.FIL.ToString();
                    dtpDocType = DTPClient.DocumentTypes.CONTRACT;
                    break;

                case ElectronicSafeDocumentBL.DocumentType.BS:
                    docType = ElectronicSafeDocumentBL.DocumentType.BS.ToString();
                    dtpDocType = DTPClient.DocumentTypes.APPENDIX1;
                    break;
            }

            string userPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType, customer, true);
            string destFullPath = System.IO.Path.Combine(ConfigurationManager.SignedDocumentRootPath, userPath, filename);
            filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, der.idDer, false);
            filename = string.Format("SIGNED_{0}", filename);

            //Download signed doc from dictao server
            if (!System.IO.File.Exists(System.IO.Path.Combine(destFullPath, filename)))
            {
                SignatureDocumentBL_4_1.GetSignedDocumentFromDictao(der.idDictao, destFullPath, filename, dtpDocType);
            }

            if (isUrl)
            {
                file = System.IO.Path.Combine(ConfigurationManager.SignedDocumentRootPath, userPath, filename);
                //file = Url.Content(string.Format("~/uploads/{0}/{1}", userPath, filename).Replace("\\", "/"));

            }
            else
            {
                file = System.IO.Path.Combine(destFullPath, filename);
            }

            return file;
        }
 public static List<Data.Model.Document> GetDocuments(Guid pIdTransaction, ElectronicSafeDocumentBL.DocumentType documentType)
 {
     using (UpsilabEntities context = new UpsilabEntities())
     {
         string docType = documentType.ToString();
         return context.Document.Include("DocumentCategory").Where(doc => doc.idSignatureTransaction == pIdTransaction && !string.IsNullOrEmpty(doc.DocumentType) &&
             doc.DocumentType == docType).ToList();
     }
 }
        public static Guid InsererDocument(Guid idTransaction, ElectronicSafeDocumentBL.DocumentType documentType, string name, string location, string designation, int pageCount = 0, DocumentBL.Status status = DocumentBL.Status.Created)
        {
            Guid id = Guid.NewGuid();
            var doc = new Upsilab.Data.Model.Document
            {
                idDocument = id,
                DateCreated = DateTime.Now,
                DocumentType = documentType.ToString().ToUpper().Trim(),
                Name = name,
                Location = location,
                Designation = designation,
                idSignatureTransaction = idTransaction,
				PageCount = pageCount,

                Status = status.ToString()
            };

            if (documentType == ElectronicSafeDocumentBL.DocumentType.AVENANT)
            {
                doc.Status = DocumentBL.Status.InProgress.ToString();
            }

            DocumentBL.AddDocument(doc);
            return id;
        }
        public static string GetSignedMissionDocument(MissionDocument missionDoc, ElectronicSafeDocumentBL.DocumentType ESDocumentType, bool isUrl)
        {
            string file = string.Empty;
            string filename = string.Empty;

            Data.Model.CustomerProspect customer = missionDoc.CustomerProspect;
            string docType = (missionDoc.IsLetter) ? ElectronicSafeDocumentBL.DocumentType.LM.ToString() : ElectronicSafeDocumentBL.DocumentType.RM.ToString();
            DTPClient.DocumentTypes dtpDocType = DTPClient.DocumentTypes.CONTRACT; //For LM and RM doc

            switch (ESDocumentType)
            {
                case ElectronicSafeDocumentBL.DocumentType.BS:
                    docType = ElectronicSafeDocumentBL.DocumentType.BS.ToString();
                    dtpDocType = DTPClient.DocumentTypes.APPENDIX1;
                    break;

                case ElectronicSafeDocumentBL.DocumentType.FIL:
                    docType = ElectronicSafeDocumentBL.DocumentType.FIL.ToString();
                    dtpDocType = DTPClient.DocumentTypes.APPENDIX2;
                    break;

                case ElectronicSafeDocumentBL.DocumentType.CRTO:
                    docType = docType + "_" + ElectronicSafeDocumentBL.DocumentType.CRTO;
                    dtpDocType = DTPClient.DocumentTypes.APPENDIX3;
                    break;
            }

            string userPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType, customer, true);
            string destFullPath = System.IO.Path.Combine(ConfigurationManager.SignedDocumentRootPath, userPath, filename);
            filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, missionDoc.idMissionDocument, false);
            filename = string.Format("SIGNED_{0}", filename);

            //Download signed doc from dictao server
            if (!System.IO.File.Exists(System.IO.Path.Combine(destFullPath, filename)))
            {
                GetSignedDocumentFromDictao(missionDoc.idDictao, destFullPath, filename, dtpDocType);
            }

            if (isUrl)
            {
                file = System.IO.Path.Combine(ConfigurationManager.SignedDocumentRootPath, userPath, filename);
                //file = Url.Content(string.Format("~/uploads/{0}/{1}", userPath, filename).Replace("\\", "/"));

            }
            else
            {
                file = System.IO.Path.Combine(destFullPath, filename);
            }

            return file;
        }
        public ActionResult DownloadSignedDocument(string id, ElectronicSafeDocumentBL.DocumentType docType)
        {
            bool isMissionLetter = true;

            try
            {
                MissionDocument missionDoc = MissionDocumentBL.GetMissionDocumentById(new Guid(id));

                if (missionDoc != null)
                {
                    isMissionLetter = missionDoc.IsLetter;
                    //from dtp 4.1 or dtp4.2 ?
                    string fileToDownload = string.Empty;

                    if (SignatureDocumentBL.GetDTPVersion(missionDoc.Status, missionDoc.idDTPUserAccess) == SignatureDocumentBL.DTPVersion.V4_1.ToString())
                    {
                        fileToDownload = SignatureDocumentBL_4_1.GetSignedMissionDocument(missionDoc, docType, false);
                    }
                    else
                    {
                        fileToDownload = SignatureDocumentBL.GetSignedMissionDocument(missionDoc, docType, false);
                    }

                    if (!string.IsNullOrEmpty(fileToDownload))
                    {
                        string[] tFilename = fileToDownload.Split(new char[] { '/', '\\' });

                        var contentDisposition = new System.Net.Mime.ContentDisposition
                        {
                            FileName = tFilename[tFilename.Length - 1],
                            // always prompt the user for downloading, set to true if you want 
                            Inline = false,
                        };

                        Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

                        return File(System.IO.File.ReadAllBytes(fileToDownload), "application/octet-stream");
                    }
                }

            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
            }

            string missionDocType = (isMissionLetter) ? MissionDocumentBL.DocumentType.LM.ToString() : MissionDocumentBL.DocumentType.RM.ToString();

            return ModelChoice(missionDocType);
        } 
        public ActionResult Liste(ElectronicSafeDocumentBL.DocumentType? documentTypeCode, string idDocumentCategory = null, string idSusbFile = null, string idFirmInstitution = null, string idDocument = null, string idProduct = null)
        {
            SessionManager.Set<List<SubscriptionFileViewModel>>(SUBSCRIPTION_FILE_DROPDOWN_PRODUIT,null);
            SessionManager.Set<SubscriptionFileViewModel>(SUBSCRIPTION_FILE_FIRST_SF_PRODUCT, null);
            SessionManager.Set<List<DocumentCategoryViewModel>>(DOCUMENTS_CGP, null);

            var tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(new List<ElectronicSafeDocument>(), new ElectronicSafeDocument());

            try
            {
                /*reinit session*/
               // SessionManager.Set<SubscriptionFileViewModel>(SUBSCRIPTION_FILE_OBJECT_SESSION, null);

                ViewBag.IsUserExist = "Ko";
                bool showCustomerCoffre = false;
                bool showDossierCoffre = false;
                bool showPieceJustificatif = false;
                bool showConventionCoffre = false;
                CustomerProspect customer = null;
                Upsilab.Data.Model.User userAdviser = null;
                DocumentType docType = null;

                Upsilab.Data.Model.User currentUser = SessionManager.GetUserSession();

                //Get customer
                Guid idCustomer = Guid.Empty;
                var idSubscriptionFiles = new List<int>();
                int idSubscriptionFileId = 0;
                SessionManager.Get<Guid>(CustomerProspectBL.CoffreFortCustomerIdSessionKey, out idCustomer);
                
                if (!string.IsNullOrEmpty(idSusbFile))
                {

                    Int32.TryParse(idSusbFile, out idSubscriptionFileId);
                    idSubscriptionFiles.Add(idSubscriptionFileId);

                    /*Get subscription file data*/
                    var subscriptionFileLite = FrDossierBL.GetInfoLiteById(idSubscriptionFileId);
                    /* Binding documents */
                    if (subscriptionFileLite != null)
                    {
                        subscriptionFileLite.PiecesJointes =
                            DocumentBL.GetDocumentsAndSignatureSubscriptionFile(idSubscriptionFileId);
                    }
                    SessionManager.Set<SubscriptionFileViewModel>(SUBSCRIPTION_FILE_OBJECT_SESSION, subscriptionFileLite);

                    /* subscriptions list for customer lab*/
                    var firmInstitutionForProduct = FrDossierBL.GetFirmInfoBySubscription(idSubscriptionFileId);
                    SessionManager.Set<List<FirmInstitutionViewModel>>(SUBSCRIPTION_FILE_OBJECT_LIST_SESSION, firmInstitutionForProduct); 
                }

                if (!string.IsNullOrEmpty(idFirmInstitution))
                {
                    Guid guidFirmInstitution = Guid.Empty;
                    Guid.TryParse(idFirmInstitution, out guidFirmInstitution);
                    idSubscriptionFiles = FrDossierBL.GetSubscriptionFilesIdByFirm(guidFirmInstitution);

                    SessionManager.Set<SubscriptionFileViewModel>(SUBSCRIPTION_FILE_OBJECT_SESSION, null);
                }

                showPieceJustificatif = !string.IsNullOrEmpty(idDocument);

                if (!string.IsNullOrEmpty(idProduct))
                {
                    Guid productGuid = Guid.Empty;
                    Guid.TryParse(idProduct, out productGuid);

                    var listSubFile = FrDossierBL.GetSubscriptionFileViewModelsByProduct(productGuid).ToList();
                    if (idCustomer != Guid.Empty)
                    {
                        listSubFile = listSubFile.Where(x => x.IdCustomerProspect.HasValue && x.IdCustomerProspect.Value == idCustomer).OrderBy(x => x.IdSubscriptionFile).ToList();
                        if (listSubFile.Any())
                        {
                            SessionManager.Set<List<SubscriptionFileViewModel>>(SUBSCRIPTION_FILE_DROPDOWN_PRODUIT,listSubFile);
                            int fstSubs = 0;
                            if (!string.IsNullOrEmpty(idSusbFile))
                            {
                                Int32.TryParse(idSusbFile, out fstSubs);
                            }
                            else
                            {
                                fstSubs = listSubFile.ElementAt(0).IdSubscriptionFile;
                            }


                            var subsFirst = FrDossierBL.GetInfoLiteById(fstSubs);
                            if (subsFirst != null)
                            {
                                subsFirst.PiecesJointes =
                                    DocumentBL.GetDocumentsAndSignatureSubscriptionFile(fstSubs);
                            }
                            SessionManager.Set<SubscriptionFileViewModel>(SUBSCRIPTION_FILE_FIRST_SF_PRODUCT, subsFirst);
                        }
                        
                    }
                    
                }

                //TODO
                //Pour le moment, seuls les clients ont une coffre fort
                if (idCustomer != Guid.Empty)
                {
                    showCustomerCoffre = true;  //coffre fort pour customer

                    var firmInstitutionForProduct = FrDossierBL.GetInfoLiteByCustomerLab(idCustomer);
                    SessionManager.Set<List<FirmInstitutionViewModel>>(SUBSCRIPTION_FILE_OBJECT_LIST_SESSION, firmInstitutionForProduct); 
                }
                else
                {
                    Guid idDoc = Guid.Empty;
                    

                    if (!string.IsNullOrEmpty(idSusbFile))
                    {
                        int idSubscriptionFile = 0;
                        Int32.TryParse(idSusbFile, out idSubscriptionFile);
                        Int32.TryParse(idSusbFile, out idSubscriptionFile);

                    }



                    if (idSubscriptionFiles.Any())
                    {
                        showDossierCoffre = true;
                    }
                    else if (!string.IsNullOrEmpty(idDocument))
                    {
                        Guid.TryParse(idDocument, out idDoc);
                        /* get customer order by idDocument : nullable*/
                        idCustomer = FrDossierBL.GetCustomerIdByDocument(idDoc);
                    }
                    else
                    {
                        //return RedirectToAction("Dashboard", "Home"); TODO
                    }
                }

                Guid idFirmInstitutionCGP = Guid.Empty;
                SessionManager.Get<Guid>(CONVENTION_FIRMINSTITUTION_CGP_ID, out idFirmInstitutionCGP);
                if (idFirmInstitutionCGP != Guid.Empty)
                {
                    showConventionCoffre = true;
                }

                if (showCustomerCoffre)
                {
                    if (idSubscriptionFiles.Any())
                    {
                        showDossierCoffre = true;
                    }
                    //Document type : let's take RC as default document type
                    if (!documentTypeCode.HasValue)
                    {
                        documentTypeCode = ElectronicSafeDocumentBL.DocumentType.RC;
                    }

                    //End user can't see the LAB study and Mesure de vigi
                    if (currentUser.IsEndUser()
                        && (documentTypeCode == ElectronicSafeDocumentBL.DocumentType.LAB || documentTypeCode == ElectronicSafeDocumentBL.DocumentType.MV))
                    {
                        documentTypeCode = ElectronicSafeDocumentBL.DocumentType.RC; //As default            
                    }

                    //Get customer and documenttype from db
                    string documentType = documentTypeCode.ToString();

                    using (var db = new UpsilabEntities())
                    {
                        int idDocCateg = 0;
                        docType = db.DocumentType.FirstOrDefault(d => d.DocumentNamePrefix == documentType);

                        if (!string.IsNullOrEmpty(idDocumentCategory))
                        {
                            Int32.TryParse(idDocumentCategory, out idDocCateg);
                        }

                        if (showDossierCoffre)
                        {
                            customer =
                                db.CustomerProspect.Include("User")
                                  .Include("User1")
                                  .Include("FirmInstitution")
                                  .FirstOrDefault(c => c.idCustomer == idCustomer);
                            tuple = GetDossierDocumentsWithLab(idSubscriptionFiles, customer, docType);

                            var lstLite = ElectronicSafeDocumentBL.GetDocumentsLite(customer != null
                                    ? customer.idCustomer
                                    : Guid.Empty);
                            ViewBag.RC_Count = ViewBag.LAB_Count = ViewBag.FIL_Count = ViewBag.BS_Count
                                = ViewBag.CG_Count = ViewBag.EC_Count = ViewBag.LM_Count = ViewBag.CRTO_Count
                                    = ViewBag.RM_Count = ViewBag.MV_Count = ViewBag.CNI_Count = ViewBag.DOC_Count = 0;
                            if (lstLite != null && idSubscriptionFiles.Count == 1)
                            {
                               // lstLite = lstLite.Where(x => x.IdSubscriptionFile == idSubscriptionFiles.ElementAt(0)).ToList();
                                ViewBag.RC_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.RC.ToString());
                                ViewBag.LAB_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.LAB.ToString());
                                ViewBag.FIL_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.FIL.ToString());
                                ViewBag.BS_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.BS.ToString());
                                ViewBag.CG_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.CG.ToString());
                                ViewBag.EC_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.EC.ToString());
                                ViewBag.LM_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.LM.ToString());
                                ViewBag.CRTO_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.CRTO.ToString());
                                ViewBag.RM_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.RM.ToString());
                                ViewBag.MV_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.MV.ToString());
                                ViewBag.CNI_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.CNI.ToString() || x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.PASSEPORT.ToString());
                                ViewBag.DOC_Count = lstLite.Count(x => (x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.DOC.ToString() || x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.AX.ToString()) && !x.idDocumentCategory.HasValue);
                            }

                            ViewBag.IsUserExist = "Ok";
                            
                        }
                        else if (showPieceJustificatif)
                        {

                            if (db.CustomerProspect.Any(x => x.idCustomer == idCustomer))
                            {
                                customer = db.CustomerProspect.Include("User").Include("User1").Include("FirmInstitution").FirstOrDefault(c => c.idCustomer == idCustomer); 
                            }

       

                            tuple = GetDossierDocumentsWithPJ(idDocument, customer);
                            ViewBag.IsUserExist = "Ok";
                            ViewBag.IsPiece = "Ok";
                        }
                        else if (showCustomerCoffre) //for customer
                        {
                            customer = db.CustomerProspect.Include("User").Include("User1").Include("FirmInstitution").FirstOrDefault(c => c.idCustomer == idCustomer);
                            tuple = GetCustomerDocuments(customer, docType, idDocCateg);

                            var lstLite = ElectronicSafeDocumentBL.GetDocumentsLite(customer != null
                                    ? customer.idCustomer
                                    : Guid.Empty);
                            ViewBag.RC_Count = ViewBag.LAB_Count = ViewBag.FIL_Count = ViewBag.BS_Count
                                = ViewBag.CG_Count = ViewBag.EC_Count = ViewBag.LM_Count = ViewBag.CRTO_Count
                                    = ViewBag.RM_Count = ViewBag.MV_Count = ViewBag.CNI_Count = ViewBag.DOC_Count = 0;
                            if (lstLite != null)
                            {
                                ViewBag.RC_Count = lstLite.Count(x =>x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.RC.ToString());
                                ViewBag.LAB_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.LAB.ToString());
                                ViewBag.FIL_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.FIL.ToString());
                                ViewBag.BS_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.BS.ToString());
                                ViewBag.CG_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.CG.ToString());
                                ViewBag.EC_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.EC.ToString());
                                ViewBag.LM_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.LM.ToString());
                                ViewBag.CRTO_Count = lstLite.Count(x =>x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.CRTO.ToString());
                                ViewBag.RM_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.RM.ToString());
                                ViewBag.MV_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.MV.ToString());
                                ViewBag.CNI_Count = lstLite.Count(x => x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.CNI.ToString() || x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.PASSEPORT.ToString());
                                ViewBag.DOC_Count = lstLite.Count(x => (x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.DOC.ToString() || x.DocumentType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.AX.ToString()) && !x.idDocumentCategory.HasValue);
                            }


                            ViewBag.IsUserExist = "Ok";
                        }
                        
                        else if (!currentUser.IsEndUser()) //for adviser
                        {
                            userAdviser = db.User.FirstOrDefault(u => u.idUser == currentUser.idUser);
                            tuple = GetAdviserDocuments(userAdviser, docType, idDocCateg);
                            ViewBag.IsUserExist = "Ok";
                        }
                    };
                }
                else if (showDossierCoffre)
                {
                    int idFirst = idSubscriptionFiles.Any() ? idSubscriptionFiles[0] : 0;
                    tuple = GetDossierDocuments(idFirst);
                    ViewBag.IsUserExist = "Ok";
                }
                else if (showPieceJustificatif)
                {

                    if (db.CustomerProspect.Any(x => x.idCustomer == idCustomer))
                    {
                        customer = db.CustomerProspect.Include("User").Include("User1").Include("FirmInstitution").FirstOrDefault(c => c.idCustomer == idCustomer);
                    }

                    // menu
                    var docsCgp = DocumentBL.GetDocumentsCgp(idFirmInstitutionCGP);
                    SessionManager.Set<List<DocumentCategoryViewModel>>(DOCUMENTS_CGP, docsCgp);

                    tuple = GetDossierDocumentsWithPJ(idDocument, customer);
                    ViewBag.IsUserExist = "Ok";
                    ViewBag.IsPiece = "Ok";
                }
                else if (showConventionCoffre)
                {
                    tuple = GetConventionDocuments(idFirmInstitutionCGP, documentTypeCode.Value);
                    ViewBag.IsUserExist = "Ok";
                    ViewBag.IsConvention = true;
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorAfterUpload = ex.Message;
            }
            finally
            {
                // Show upload error
                if (SessionManager.Exists(ERROR_UPLOAD_DOWLOAD_SESSION))
                {
                    string uploadError = string.Empty;
                    SessionManager.Get<string>(ERROR_UPLOAD_DOWLOAD_SESSION, out uploadError);
                    ViewBag.ErrorAfterUpload = uploadError;

                    SessionManager.Clear(ERROR_UPLOAD_DOWLOAD_SESSION);
                }

            }

            ViewBag.DocumentTypeCode = documentTypeCode;
            var isAgreg=false;
            SessionManager.Get<bool>("IsAgregateur", out isAgreg);
            ViewBag.IsAgreg = isAgreg;
            return View(tuple);
        }
        public Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument> GetConventionDocuments(Guid idFirmInstitutionCGP, ElectronicSafeDocumentBL.DocumentType documentType)
        {
            var tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(new List<ElectronicSafeDocument>(), new ElectronicSafeDocument());
            var LanguageData = PageLanguageHelper.GetLanguageContent("User", "CoffreFortController");

            try
            {
                // Get list of documents
                IList<ElectronicSafeDocument> lstElectronicSafeDocs = ElectronicSafeDocumentBL.GetConventionDocuments(idFirmInstitutionCGP, documentType);
                var docsCgp = DocumentBL.GetDocumentsCgp(idFirmInstitutionCGP);
                SessionManager.Set<List<DocumentCategoryViewModel>>(DOCUMENTS_CGP, docsCgp);

                // Build session menu avenants
                BuildMenuAvenantCGP(idFirmInstitutionCGP);

                // Build session menu conventions
                BuildMenuConventionsCGP(idFirmInstitutionCGP);

                tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(lstElectronicSafeDocs, new ElectronicSafeDocument());

            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                Business.Log.Log.AppendException(ex);
            }
            return tuple;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idSubcriptionFile">Id dossier</param>
        /// <returns></returns>
        public static IList<ElectronicSafeDocument> GetConventionDocuments(Guid idFirmInstitutionCGP, ElectronicSafeDocumentBL.DocumentType documentType)
        {
            using (UpsilabEntities db = new UpsilabEntities())
            {
                var docType = documentType.ToString();

                var query = db.ElectronicSafeDocument.Include("DocumentCategory")
                            //.Where(doc => doc.idFirmInstitution == idFirmInstitutionCGP
                            //              && doc.IdSignatureTransaction.HasValue
                            //              && doc.DocumentType.DocumentNamePrefix == docType)
                            .Where(doc => doc.IdSignatureTransaction.HasValue
                            && doc.SignatureTransaction.idFirmInstitution == idFirmInstitutionCGP
                            && doc.DocumentType.DocumentNamePrefix == docType)
                            .OrderByDescending(doc => doc.DateCreated)
                            .Select(doc => doc);

                return query.ToList();
            }
        }
        public ActionResult DownloadSignedDocument(string id, ElectronicSafeDocumentBL.DocumentType docType)
        {

            try
            {
                DER der = DerBL.GetDERById(new Guid(id));

                if (der != null)
                {
                    //from dtp 4.1 or dtp4.2 ?
                    string fileToDownload = string.Empty;

                    if (SignatureDocumentBL.GetDTPVersion(der.Status, der.idDTPUserAccess) == SignatureDocumentBL.DTPVersion.V4_1.ToString())
                    {
                        fileToDownload = SignatureDocumentBL_4_1.GetSignedDerDocument(der, docType, false);
                    }
                    else
                    {
                        fileToDownload = SignatureDocumentBL.GetSignedDerDocument(der, docType, false);
                    }

                    if (!string.IsNullOrEmpty(fileToDownload))
                    {
                        string[] tFilename = fileToDownload.Split(new char[] { '/', '\\' });

                        var contentDisposition = new System.Net.Mime.ContentDisposition
                        {
                            FileName = tFilename[tFilename.Length - 1],
                            // always prompt the user for downloading, set to true if you want 
                            Inline = false,
                        };

                        Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

                        return File(System.IO.File.ReadAllBytes(fileToDownload), "application/octet-stream");
                    }
                }

            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
            }

            

            return RedirectToAction("Index");
        }