private static bool ArchiveDocument(Upsilab.Data.Model.SignatureTransaction signatureTransaction)
        {
            bool bOK = true; //TODO

            DTPClient dtpClient = new DTPClient(signatureTransaction.idDTPTransaction);

            //1- Update missionDocument table
            //signatoryTransaction.Status = ReportBL.Status.Completed.ToString(); //If signed by all signatories
            DocumentBL.Status docStatus = DocumentBL.Status.Completed;
            DocumentSignatureTransactionBL.UpdateTransactionStatus(signatureTransaction.idSignatureTransaction, docStatus);

            //2- Reduice firm credit after signature + mise au coffre
            //TODO : don't archive, sign doc if credit is not sufficient
            try
            {
                //var firmSDG = Upsilab.Business.Configuration.FirmInstitutionBL.GetFirmInstitutionParentByIdUser(signatureTransaction.idUserCreated);
                var firmSDG = Configuration.FirmInstitutionBL.GetFirmInstitutionParentByIdFirm(signatureTransaction.idFirmInstitution.Value);

                CreditOperationBL.OperationType operationType = CreditOperationBL.OperationType.UNKNOWN;//TODO
                if (signatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.CONVENTION.ToString())
                {
                    operationType = CreditOperationBL.OperationType.SIGNATURE_SDG_CONVENTION;
                }
                else if (signatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.AVENANT.ToString())
                {
                    operationType = CreditOperationBL.OperationType.SIGNATURE_SDG_AVENANT;
                }

                CreditOperationBL.SubstractCredit(firmSDG.idFirmInstitution, operationType.ToString(), signatureTransaction.idUserCreated);
            }
            catch { }

            //3- Save signed document to the server
            var docDocType = ElectronicSafeDocumentBL.DocumentType.DOC.ToString();
            var documentsToSign = (from doc in signatureTransaction.Document
                                   where doc.DocumentType != docDocType && doc.DocumentSignatory.Count > 0
                                   select doc).ToList();

            //TODO - TEST--------------------------------
            //documentsToSign = documentsToSign.Where(x => x.DocumentType == "CPART").ToList();
            //--------------------------------------------

            for (int i = 0; i < documentsToSign.Count; i++)
            {
                try
                {
                    var document = documentsToSign.ElementAt(i);

                    //Document to sign
                    var dtpDocType = (i == 0) ? DTPClient.DocumentTypes.CONTRACT.ToString() : string.Format("{0}{1}", DTPClient.APPENDIX, i);

                    var relativePath = string.Empty;
                    var documentName = ElectronicSafeDocumentBL.BuildDocumentName(document.DocumentType, document.idDocument);
                    var fullPath = ElectronicSafeDocumentBL.BuildSignatureDocumentPath(signatureTransaction.FirmInstitution.FirmInstitutionName, signatureTransaction.FirmInstitution.idFirmInstitution, document.DocumentType.ToDocumentTypeEnum(), false, out relativePath); //CF

                    Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(dtpDocType);

                    if (dtpDoc != null)
                    {
                        //Save physically
                        dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                        //TODO : Save document to ElectronicSafe table
                        var documentLabel = LanguageContentBL.Translate(document.DocumentType.ToLower());

                        //Particular case for "AVENANT"
                        if (signatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.AVENANT.ToString())
                        {
                            documentLabel = document.Designation;
                        }

                        ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, document.DocumentType, documentLabel, relativePath, signatureTransaction.idFirmInstitution.Value, signatureTransaction.idDTPTransaction, null, false, null, null, signatureTransaction.idSignatureTransaction);
                    }
                }
                catch (Exception ex)
                {
                    Log.Log.AppendException(ex);
                }
            } 
      
            //4- Save to coffre document of type "DOC", doc not signed (documents de complétude)
            var clientD3S = new D3SClient();

            var documentsNotSigned = (from doc in signatureTransaction.Document
                                      where doc.DocumentType == docDocType
                                      select doc).ToList();

            foreach (var document in documentsNotSigned)
            {
                try
                {
                    //1- Copy to directory
                    var sourceFilePath = FileManager.GetFileFromUploadDirectory(document.Location, document.Name);

                    var relativePath = string.Empty;
                    var fullPath = ElectronicSafeDocumentBL.BuildSignatureDocumentPath(signatureTransaction.FirmInstitution.FirmInstitutionName, signatureTransaction.FirmInstitution.idFirmInstitution, ElectronicSafeDocumentBL.DocumentType.DOC, false, out relativePath); //CF
                    var destFileName = ElectronicSafeDocumentBL.BuildDocumentName(document.Label, document.idDocument);
                    var destFilePath = Path.Combine(fullPath, destFileName);

                    if (!System.IO.File.Exists(destFilePath))
                    {
                        System.IO.File.Copy(sourceFilePath, destFilePath);

                        //2- Send to dictao
                        var dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(sourceFilePath.Replace(document.Name, string.Empty),
                            document.Name, clientD3S);

                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            var documentLabel = document.DocumentCategory != null ? document.DocumentCategory.Label : document.Name.Split('.')[0];
                            ElectronicSafeDocumentBL.SaveDocumentToDB(destFileName, document.DocumentType, documentLabel, relativePath, signatureTransaction.idFirmInstitution.Value, dictaoId, clientD3S, false, document.IdDocumentCategory, null, signatureTransaction.idSignatureTransaction);
                        }

                    }

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


            //5- If all is ok, finish / close transaction
            dtpClient.FinishTransaction();

            IList<string> documentTypesToExcludeOnArchive = null; //TODO

            //6- Archive transaction : TODO : asynchrone ?
            try
            {
                string businessId = string.Format("{0}-{1}", DOCUMENT, signatureTransaction.idSignatureTransaction);
                dtpClient.ArchiveTransaction(string.Empty, string.Empty, string.Empty, businessId, documentTypesToExcludeOnArchive);
            }
            catch { }


            return bOK;
        }
        private string SendCGVToCoffreFort(CustomerProspect customer)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeByCode(ElectronicSafeDocumentBL.DocumentType.CG.ToString());
            string error = string.Empty;

            try
            {
                //TODO : mise au coffre pour le conseiller ?
                if (customer.User.IsEndUser())
                {
                    string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.CG.ToString(), customer);
                    string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                    string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, "CG_client_final.pdf");

                    // 1- File to save to coffre fort
                    string filenameCGS = "CG_client_final.pdf"; //by default FR ?                    
                    
                    if (ConfigurationManager.ExtranetHostCode == PageLanguageHelper.HostCode.BE.ToString())
                    {
                        filenameCGS = "BE_CG_client_final.pdf";
                    }

                    string pathOriginalFileName = Server.MapPath(string.Format("~/Documents/{0}", filenameCGS));
                    byte[] fileBin = System.IO.File.ReadAllBytes(pathOriginalFileName);

                    string pathFilename = System.IO.Path.Combine(documentFullPath, sFilename);
                    System.IO.File.WriteAllBytes(pathFilename, fileBin);

                    // 2- Upload file to DICTAO server
                    D3SClient clientD3S = new D3SClient();
                    string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                    // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_CONDITION_GENERALE"
                    if (!string.IsNullOrEmpty(dictaoId))
                    {
                        //var firmInstitution = SessionManager.GetFirmInstitutionSession();
                        //Guid idFirmInstitution = (firmInstitution != null) ? firmInstitution.idFirmInstitution : customer.idFirmInstitution;

                        CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_CONDITION_GENERALE.ToString(), customer.idUserCreated, customer.idCustomer);

                        // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                        ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, ElectronicSafeDocumentBL.DocumentType.CG.ToString(), LanguageDataPage.GetContent("conditions_generales"), documentPath, customer.idCustomer, dictaoId, clientD3S);
                    }
                    else
                    {
                        error = LanguageDataPage.GetContent("doc_non_envoye_au_cfe");
                    }
                }

            }
            catch (Exception ex)
            {
                Business.Log.Log.AppendException(ex);
                error = ex.Message;
            }

            return error;
        }
        public ActionResult DocFileUploadRM(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {

            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;

            if (objESDoc.idCustomer.HasValue)
            {
                CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);
                MissionDocument missionRapport = MissionDocumentBL.GetLatestMissionDocumentByIdCustomer(objESDoc.idCustomer.Value, false);

                DateTime selectedDate = Convert.ToDateTime(Request.Params["datepicker5"].ToString());
                objESDoc.DocumentLabel = "Rapport_écrit_de_mission_" + customer.User.UserFirstName + "_" + customer.User.UserName + "_" + selectedDate.ToShortDateString();
                if (uploadFile.ContentLength > 0)
                {
                    string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.RM.ToString(), customer);
                    string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                    string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, uploadFile.FileName);

                    // 1- Sauvegarde dans le repertoire
                    string filePath = System.IO.Path.Combine(documentFullPath, sFilename);
                    uploadFile.SaveAs(filePath);

                    // 2- Upload file to DICTAO server
                    D3SClient clientD3S = new D3SClient();
                    string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                    // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_DIVERS_DOCUMENTS"
                    if (!string.IsNullOrEmpty(dictaoId))
                    {
                        //var firmInstitution = SessionManager.GetFirmInstitutionSession();
                        //Guid idFirmInstitution = (firmInstitution != null) ? firmInstitution.idFirmInstitution : customer.idFirmInstitution;

                        CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_MANUELLE_DOCUMENT_MISSION.ToString(), customer.idUserCreated, customer.idCustomer);

                        //4- Update date/status de la lettre de mission
                        customer.DateLastUpdateMission = selectedDate;
                        customer.MissionStatus = RegulatoryDocumentModel.Status.Completed.ToString();
                        customer.IsMissionOriginal = false;
                        CustomerProspectBL.Update(customer);

                        //5- Sauvegarde dans la base (table ElectronicSafeDocument)
                        ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, ElectronicSafeDocumentBL.DocumentType.RM.ToString(), objESDoc.DocumentLabel, documentPath, customer.idCustomer, dictaoId, clientD3S, true);

                        //6-  Update missionDocument table
                        missionRapport.Status = RegulatoryDocumentModel.Status.Completed.ToString();
                        missionRapport.Archived = true;
                        missionRapport.IsOriginal = false;
                        missionRapport.idDictao = dictaoId;
                        missionRapport.DateUpdated = DateTime.Now;
                        MissionDocumentBL.UpdateMissionDocument(missionRapport);
                    }
                    else
                    {
                        throw new Exception(LanguageData.GetContent("doc_non_envoyé_veuillez_reessayer"));
                    }
                }
            }

            return RedirectToAction("Index", "Client");
        }
        public ActionResult AddVigilanceMeasure(IEnumerable<HttpPostedFileBase> files)
        {
            try
            {
                string titre = Request.Form["titre"];
                string dateMeasure = Request.Form["date"];
                string contenu = Request.Form["contenu"];
                string idCustomerPosted = Request.Form["idCustomer"];
                string idLABStudyPosted = Request.Form["idLABStudy"];
                Guid idCustomer = Guid.Empty;
                Guid.TryParse(idCustomerPosted, out idCustomer);

                Guid idLABStudy = Guid.Empty;
                Guid.TryParse(idLABStudyPosted, out idLABStudy);
                bool doAction = false;
                List<string> uploadedFiles = new List<string>();

                if (idCustomer != Guid.Empty)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(idCustomer);
                    if (files != null)
                    {
                        int i = 0;
                        foreach (var file in files)
                        {
                            //Check file contenttype
                            //if (file != null && file.ContentType.CompareTo("application/pdf") == 0)
                            if (file != null && FileManager.IsPDF(file.FileName))
                            {
                                string sDocTypePrefix = ElectronicSafeDocumentBL.DocumentType.MV.ToString();
                                string fullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(sDocTypePrefix, customer);
                                string fileName = ElectronicSafeDocumentBL.BuildDocumentName(sDocTypePrefix, customer.idCustomer, file.FileName);
                                fileName = fileName.Replace(".pdf", string.Format("_{0}.pdf", i)); //make unique the filename

                                // 1- Sauvegarde dans le repertoire
                                string filePath = System.IO.Path.Combine(fullPath, fileName);
                                file.SaveAs(filePath);

                                // upload réussi
                                doAction = true;

                                //Add file to list
                                uploadedFiles.Add(filePath);
                            }
                            i++;
                        }
                    }

                    if (doAction)
                    {
                        string sDocTypePrefix = ElectronicSafeDocumentBL.DocumentType.MV.ToString();
                        string docRelPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(sDocTypePrefix, customer);
                        string fileName = ElectronicSafeDocumentBL.BuildDocumentName(sDocTypePrefix, customer.idCustomer, "mesures_vigilance.pdf");
                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, docRelPath);
                        string pahtFileName = System.IO.Path.Combine(documentFullPath, fileName);

                        VigilanceMeasure newVigilanceMeasure = new VigilanceMeasure()
                        {
                            idVigilanceMeasure = GuidHelper.GenerateGuid(),
                            DateCreated = DateTime.Now,
                            idLABStudy = idLABStudy,
                            Title = titre,
                            DateMeasure = Convert.ToDateTime(dateMeasure),
                            Content = contenu,
                        };

                        // ETAPE à Suivre    
                        /*
                         * En cliquant sur "Enregistrer", l'application va :
                        1 - Générer et compléter la page d'entete (voir modèle joint)
                        2 - Générer une page avec les informations collectées via le formulaire (Titre, Date, Contenu)
                        3 - Merger l'ensemble avec les fichiers PDF joints
                        */
                        LABPdfGenerationBL.GenerateVigilanceMeasure(newVigilanceMeasure, uploadedFiles, pahtFileName);

                        /*
                        4 - Envoyer le tout au coffre fort électronique
                         * 
                         * Important !!!
                            La mise au coffre d'une mesure de vigilance complémentaire ou renforcée doit débiter "3 crédits" 
                            Elle doit figurer dans les logs sous la forme "Mise au coffre d'une mesure de vigilance"
                         * */

                        // 4.1- Upload file to DICTAO server
                        D3SClient clientD3S = new D3SClient();
                        string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, fileName, clientD3S);

                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_MESURE_VIGILANCE.ToString(), customer.idUserCreated, customer.idCustomer);

                            // 4.2- Sauvegarde dans la base (table ElectronicSafeDocument)
                            Guid idElectronicSafeDoc = ElectronicSafeDocumentBL.SaveDocumentToDB(fileName, sDocTypePrefix, string.Format("Mesures de vigilance {0}", DateTime.Now.ToString("dd/MM/yyyy")), docRelPath, idCustomer, dictaoId, clientD3S, (customer != null) ? true : false);

                            // 4.3- Sauvegarde dans la base (table VigilanceMeasure)
                            newVigilanceMeasure.idElectronicSafeDocument = idElectronicSafeDoc;

                            VigilanceMeasureBL.CreateVigilanceMeasure(newVigilanceMeasure);

                            // 5- Update de CustomerProspect
                            customer.DateVigilanceMeasureLast = Convert.ToDateTime(dateMeasure);
                            customer.NbVigilanceMeasure = 1;
                            CustomerProspectBL.Update(customer);
                        }
                        else
                        {
                            ErrorMessage = LanguageData.GetContent("vigilance_mise_au_coffre_erreur");
                        }
                    }
                    else
                    {
                        ErrorMessage = LanguageData.GetContent("vigilance_joindre_fichier");
                    }
                }
                else
                {
                    ErrorMessage = LanguageData.GetContent("vigilance_id_client_inexistant");
                }
            }
            catch (Exception ex)
            {
                Upsilab.Business.Log.Log.AppendException(ex);
                ErrorMessage = string.Format("{0} : <br /> {1}", LanguageData.GetContent("vigilance_mise_au_coffre_erreur"), ex.Message);
            }

            return RedirectToAction("SendToCoffreFort");
        }
        public ActionResult UploadToCoffre(ElectronicSafeDocument electronicSafeDocument, HttpPostedFileBase uploadFile)
        {
            DocumentType docType = DocumentTypeBL.GetDocumentTypeById(electronicSafeDocument.idDocumentType);
            string error = string.Empty;
            Guid idCustomerOrUser = Guid.Empty;
            Upsilab.Data.Model.User currentUser = SessionManager.GetUserSession();
            var LanguageData = PageLanguageHelper.GetLanguageContent("User", "CoffreFortController");
            int? idDocCateg = null;

            try
            {
                if (electronicSafeDocument.idCustomer.HasValue)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(electronicSafeDocument.idCustomer.Value);
                    if (customer == null && currentUser.IsEndUser())
                    {
                        customer = SessionManager.GetCustomerProspectSession();
                    }

                    idCustomerOrUser = (customer == null) ? currentUser.idUser : customer.idCustomer;

                    if (uploadFile.ContentLength > 0 )
                    {
                        var ext = Path.GetExtension(uploadFile.FileName);
                        if (ext.ToLower() != ".pdf")
                        {
                            error = "Seulement le fichier pdf est valide.";
                            throw new Exception(error);
                            return RedirectToAction("Liste", new { documentTypeCode = docType.DocumentNamePrefix });
                        }

                        if (uploadFile.ContentLength > 5000000)
                        {
                            error = "La taille maximale autorisée pour les fichiers est de 5 MO.";
                            throw new Exception(error);
                            return RedirectToAction("Liste", new { documentTypeCode = docType.DocumentNamePrefix });
                        }

                        string documentPath = string.Empty;
                        if (customer != null)
                        {
                            documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.DocumentNamePrefix, customer);
                        }
                        else
                        {
                            documentPath = ElectronicSafeDocumentBL.BuildUserDocumentPath(docType.DocumentNamePrefix, currentUser); //TODO : to test
                        }

                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                        string filename = ElectronicSafeDocumentBL.BuildDocumentName(docType.DocumentNamePrefix, idCustomerOrUser, uploadFile.FileName);

                        // 1- Sauvegarde dans le repertoire
                        string filePath = System.IO.Path.Combine(documentFullPath, filename);
                        uploadFile.SaveAs(filePath);

                        // 2- Upload file to DICTAO server
                        D3SClient clientD3S = new D3SClient();
                        string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, filename, clientD3S);

                        // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_DIVERS_DOCUMENTS"
                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            CreditOperationBL.OperationType creditOperationType;

                            switch (docType.DocumentNamePrefix)
                            {
                                case "BS":
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break; //TODO
                                case "FIL":
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break; //TODO
                                case "DOC":
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break;
                                default:
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break;
                            }

                            CreditOperationBL.SubstractCredit(customer.idFirmInstitution, creditOperationType.ToString(), customer.idUserCreated, customer.idCustomer);

                            string sIdDocumentCategory = Request.Params["idDocumentCategory"]; // TODO on n'a pas pu recupérer immediatement avec electronicSafeDocument.idDocumentCategory donc j'ai fait comme ça
                            int iIdDocumentCategory = 0;
                            if (!string.IsNullOrEmpty(sIdDocumentCategory))
                            {
                                Int32.TryParse(sIdDocumentCategory, out iIdDocumentCategory);
                            }

                            if (iIdDocumentCategory != 0)
                            {
                                idDocCateg = iIdDocumentCategory;
                            }

                            // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                            ElectronicSafeDocumentBL.SaveDocumentToDB(filename, docType.DocumentNamePrefix, electronicSafeDocument.DocumentLabel, documentPath, idCustomerOrUser, dictaoId, clientD3S, (customer != null) ? true : false, idDocCateg);

                            // 5- Update date du DER
                            if (docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.FIL.ToString())
                            {
                                DateTime selectedDate = DateTime.Now;
                                DateTime.TryParse(Request.Params["documentDate"].ToString(), out selectedDate);

                                if (selectedDate == DateTime.MinValue)
                                {
                                    selectedDate = DateTime.Now;
                                }

                                customer.DateLastUpdateDer = selectedDate;
                                customer.DerStatus = Upsilab.Business.SignatureDocument.DocumentBL.Status.Completed.ToString();
                                customer.IsDerOriginal = false;
                                CustomerProspectBL.Update(customer);
                            }

                        }
                        else
                        {
                            error = LanguageData.GetContent("CoffreFort_doc_n_a_pas_pu_etre_envoye");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Business.Log.Log.AppendException(ex);
                error = ex.Message;
            }

            if (!string.IsNullOrEmpty(error))
            {
                SessionManager.Set<string>(ERROR_UPLOAD_DOWLOAD_SESSION, error); // Remove session value in "liste"
            }

            // Redirect to "liste"
            object rootValues = new { documentTypeCode = docType.DocumentNamePrefix };

            if (idDocCateg != 0)
            {
                rootValues = new { documentTypeCode = docType.DocumentNamePrefix, idDocumentCategory = idDocCateg };
            }

            return RedirectToAction("Liste", rootValues);
        }
        private void SaveSignedDocumentToCoffreFort(Guid  idSignatureTransaction, int idSubscriptionFile)
        {
            var clientD3S = new D3SClient();
            var numeroDossier = idSubscriptionFile.ToString("D8");           
            var firmFournisseur = SessionManager.GetFirmInstitutionSession();
            var currentUser = SessionManager.GetUserSession();
            var subscriptionFile = FrDossierBL.GetInfoLiteById(idSubscriptionFile);
         
            List<Document> listDocument = DocumentBL.GetDocuments(idSignatureTransaction);

            //check docs valid
            Func<List<Document>, bool> ValidityDocument = docs =>
            {
                bool isValid = true;

                if (docs != null && docs.Any())
                {
                    foreach (Document x in docs)
                    {
                        if (x.DocumentCategory!=null)
                        {
                            if (x.DocumentCategory.IsMandatory &&
                                              (string.IsNullOrEmpty(x.Location) || string.IsNullOrEmpty(x.Name)))
                            {
                                isValid = false;
                                break;
                            }
                            else if (x.DocumentCategory.IsRenseignerDateExp && !x.DateExpiration.HasValue)
                            {
                                isValid = false;
                                break;
                            } 
                        }
                    }
                }
                return isValid;
            };

            bool isDocumentValid = ValidityDocument(listDocument);
            
            if (!isDocumentValid)
            {
                var error = "Certains documents sont obligatoires, veuillez les renseigner avant d'envoyer au coffre.";
                throw new Exception(error);
            }
            else
            {
                List<Document> listDocumentValid =
                    listDocument.Where(x => !string.IsNullOrEmpty(x.Location) && !string.IsNullOrEmpty(x.Name)).ToList();


                try
                {
                    bool isSendValid = true;
                    
                    foreach (Document document in listDocumentValid)
                    {
                        //1- Copy to directory
                        var sourceDocumentLocation = System.IO.Path.Combine(Server.MapPath("~/uploads").Replace(@"fournisseur\uploads", @"user\uploads"), document.Location);
                        var sourceFilePath = System.IO.Path.Combine(sourceDocumentLocation, document.Name);

                        var ext = Path.GetExtension(document.Name);
                        var documentRelativePath = string.Empty;
                        var destDocumentFullPath = ElectronicSafeDocumentBL.BuildSubscriptionFileDocumentsPath(idSubscriptionFile, false, out documentRelativePath);
                        var destFilePath = System.IO.Path.Combine(destDocumentFullPath, document.Name);

                        if (!System.IO.File.Exists(destFilePath))
                        {
                            if (!System.IO.File.Exists(sourceFilePath))
                            {
                                sourceFilePath = sourceFilePath.SendFournisseurSourceFilePathUploadsToUser();

                                if (!System.IO.File.Exists(sourceFilePath))
                                {
                                    sourceFilePath = sourceFilePath.SendUserSourceFilePathUploadsToFournisseur();
                                }
                            }

                            System.IO.File.Copy(sourceFilePath, destFilePath);
                        }

                        //2- Send to dictao
                        var dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(sourceDocumentLocation,
                            document.Name, clientD3S);
                        
                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            //var documentLabel = x.DocumentCategory.Label;
                            var documentLabel = document.DocumentCategory != null ? document.DocumentCategory.Label : document.Name.Split('.')[0];
                            
                            if (document.DocumentType == ElectronicSafeDocumentBL.DocumentType.SF.ToString())
                            {
                                documentLabel = "Bulletin de souscription"; //TODO : multilingue
                            }

                            ElectronicSafeDocumentBL.SaveDocumentToDB(document.Name, document.DocumentType, documentLabel,
                                documentRelativePath, subscriptionFile.IdCustomerProspect, dictaoId, clientD3S, false, null, idSubscriptionFile);
                        }
                        else
                        {
                            var error = "Le document n'a pas pu être envoyé au coffre fort électronique. Veuillez réessayer.";
                            throw new Exception(error);
                        }
                    }

                    //If ok, substruct credit and update status to completed
                    if (isSendValid)
                    {
                        CreditOperationBL.SubstractCredit(firmFournisseur.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_MANUELLE_SF.ToString(), currentUser.idUser, null, idSubscriptionFile); //TODO

                        //5- Sauvegarde dans la base (table signatureTransaction)
                        var signatureTransaction = FrDossierBL.GetSignatureTransaction(idSubscriptionFile);

                        signatureTransaction.Status = SignatureTransactionBL.Status.Completed.ToString();

                        SignatureTransactionBL.UpdateSignatureTransaction(signatureTransaction);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public ActionResult DocFileUploadPM(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;

            try
            {
                if (objESDoc.idCustomer.HasValue)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);
                    DateTime selectedDate = Convert.ToDateTime(Request.Params["datepicker5"].ToString());
                    objESDoc.DocumentLabel = "Receuil_" + customer.User.UserFirstName + "_" + customer.User.UserName + "_" + selectedDate.ToShortDateString();
                    if (uploadFile.ContentLength > 0)
                    {
                        string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.RC.ToString(), customer);
                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                        string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, uploadFile.FileName);

                        // 1- Sauvegarde dans le repertoire
                        string filePath = System.IO.Path.Combine(documentFullPath, sFilename);
                        uploadFile.SaveAs(filePath);

                        // 2- Upload file to DICTAO server
                        D3SClient clientD3S = new D3SClient();
                        string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                        // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_RECUEIL"
                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            //var firmInstitution = SessionManager.GetFirmInstitutionSession();
                            //Guid idFirmInstitution = (firmInstitution != null) ? firmInstitution.idFirmInstitution : customer.idFirmInstitution;

                            CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_RECUEIL.ToString(), customer.idUserCreated, customer.idCustomer);

                            // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                            ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, ElectronicSafeDocumentBL.DocumentType.RC.ToString(), objESDoc.DocumentLabel, documentPath, customer.idCustomer, dictaoId, clientD3S, true);

                            // 5- Sauvegarde dans la base (table ConfidentialityAgreement)
                            Guid idReport = Guid.Empty;

                            SessionManager.Get<Guid>(ReportBL.IdReportSessionKey, out idReport);
                            Report objCurrentReport = ReportBL.GetReportById(idReport);
                            objCurrentReport.Status = ReportBL.Status.Completed.ToString();
                            objCurrentReport.IsOriginal = false;
                            objCurrentReport.Profile = Request.Params["cbProfil"].ToString();
                            objCurrentReport.DateUpdated = DateTime.Now;
                            objCurrentReport.idDictao = dictaoId;

                            ReportBL.UpdateReport(objCurrentReport);

                            // 6- Sauvegarde dans CustomerProspect
                            customer.DateUpdatedLast = selectedDate;
                            customer.DateUpdatedNext = customer.DateUpdatedLast.Value.AddYears(1);
                            customer.RiskProfile = Request.Params["cbProfil"].ToString();
                            customer.CurrentReportStatus = ReportBL.Status.Completed.ToString();
                            customer.IsReportOriginal = false;
                            customer.HasCompletedReport = true;
                            if (customer.NbElectronicSafeDocument.HasValue)
                                customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                            else
                                customer.NbElectronicSafeDocument = 1;
                            CustomerProspectBL.Update(customer);
                        }
                        else
                        {
                            error = LanguageData.GetContent("doc_non_envoye_au_coffre");
                            Business.Log.Log.AppendException(new Exception(error));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Business.Log.Log.AppendException(ex);
            }

            if (!string.IsNullOrEmpty(error))
            {
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, error); // Remove session value in "liste"
            }
            else
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, "OK");
            return RedirectToAction("SentToCoffreFort");

            // ViewBag.Error = error;
            //  return RedirectToAction("TitulairePM");

        }
        public ActionResult DocFileUpload(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;
            bool isCustomer = true;

            try
            {
                if (objESDoc.idCustomer.HasValue)
                {
                    var customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);
                    isCustomer = customer.IsCustomer;

                    if (uploadFile.ContentLength > 0)
                    {
                        string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), customer);
                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                        string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, uploadFile.FileName);

                        // 1- Sauvegarde dans le repertoire
                        string filePath = System.IO.Path.Combine(documentFullPath, sFilename);
                        uploadFile.SaveAs(filePath);

                        // 2- Upload file to DICTAO server
                        var clientD3S = new D3SClient();
                        string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                        // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_MANUELLE_ENGAGEMENT_CONFIDENTIALITE"
                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            using (var db = new UpsilabEntities())
                            {
                                //var firmInstitution = SessionManager.GetFirmInstitutionSession();
                                //Guid idFirmInstitution = (firmInstitution != null) ? firmInstitution.idFirmInstitution : customer.idFirmInstitution;

                                CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_MANUELLE_CRTO.ToString(), customer.idUserCreated, customer.idCustomer);

                                // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                                ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), objESDoc.DocumentLabel, documentPath, customer.idCustomer, dictaoId, clientD3S);

                                // 5- Sauvegarde dans la base (table ConfidentialityAgreement)
                                string dateSignatureConseiller = Request.Form["DateSignatureConseiller"];
                                string dateSignatureClient = Request.Form["DateSignatureClient"];

                                var dDateSignatureConseiller = new DateTime();
                                var dDateSignatureClient = new DateTime();

                                if (!string.IsNullOrEmpty(dateSignatureConseiller)) DateTime.TryParse(dateSignatureConseiller, out dDateSignatureConseiller);
                                if (!string.IsNullOrEmpty(dateSignatureClient)) DateTime.TryParse(dateSignatureClient, out dDateSignatureClient);

                                var objConvRto = new ConventionRTO()
                                {
                                    idConventionRTO = GuidHelper.GenerateGuid(),
                                    Status = Business.Report.ReportBL.Status.Completed.ToString(),
                                    DateCreated = DateTime.Now,
                                    //DateUpdated = ,
                                    idDictao = dictaoId,
                                    SignedByCustomer = true,
                                    DateSignatureCustomer = dDateSignatureClient,
                                    SignedByAdviser = true,
                                    DateAdviserSignature = dDateSignatureConseiller,
                                    Archived = true,
                                };


                                db.ConventionRTO.Attach(objConvRto);
                                db.ObjectStateManager.ChangeObjectState(objConvRto, System.Data.EntityState.Added);
                                db.SaveChanges();

                                customer.idConventionRTO = objConvRto.idConventionRTO;
                                CustomerProspectBL.Update(customer);
                            }


                        }
                        else
                        {
                            error = LanguageData.GetContent("conv_rto_doc_impossible_a_envoyer_au_cfe");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
                error = ex.Message;
            }

            //----
            if (!string.IsNullOrEmpty(error))
            {
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, error); // Remove session value in "index"
            }

            return RedirectToAction("Index", "ConventionRTO", new { _isCustomer = isCustomer });
            //----            
        }
        public ActionResult DocFileUpload(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;
            bool isCustomer = this.IsClient;
            bool isPasseport = false;

            if (Upsilab.Business.Utility.SessionManager.Exists(ISPASSEPORT))
            {
                Upsilab.Business.Utility.SessionManager.Get<bool>(ISPASSEPORT, out isPasseport);
            }

            try
            {
                if (objESDoc.idCustomer.HasValue)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);

                    if (uploadFile!=null && uploadFile.ContentLength > 0)
                    {
                        string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(objDoctype.DocumentNamePrefix, customer);
                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                        string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, uploadFile.FileName);

                        // 1- Sauvegarde dans le repertoire
                        string filePath = System.IO.Path.Combine(documentFullPath, sFilename);
                        uploadFile.SaveAs(filePath);

                        // 2- Upload file to DICTAO server
                        D3SClient clientD3S = new D3SClient();
                        string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                        // 3- Mise à jour de customerProspect
                        string dateExpiration = Request.Params["DateExpiration"];
                        string dateEmission = string.Empty;
                        if (!isPasseport)
                            dateEmission = Request.Params["DateEmission"];

                        DateTime dDateExpiration = new DateTime();
                        if (!string.IsNullOrEmpty(dateExpiration))
                        {
                            DateTime.TryParse(dateExpiration, out dDateExpiration);
                        }

                        DateTime dDateEmission = new DateTime();
                        if (!string.IsNullOrEmpty(dateEmission))
                        {
                            DateTime.TryParse(dateEmission, out dDateEmission);
                        }

                        if (isPasseport)
                        {
                            customer.PasseportFileName = sFilename;

                            if (dDateExpiration != null)
                            {
                                customer.PasseportDateExpired = dDateExpiration;
                            }

                            //if (dDateEmission != null)
                            //{
                            //    customer.PasseportEmissionDate = dDateEmission;
                            //}
                        }
                        else
                        {
                            customer.CNIFileName = sFilename;
                            if (dDateExpiration != null)
                            {
                                customer.CNIDateExpired = dDateExpiration;
                            }

                            if (dDateEmission != null && dDateEmission != DateTime.MinValue)
                            {
                                customer.CNIEmissionDate = dDateEmission;
                            }
                        }
                        CustomerProspectBL.Update(customer);

                        // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                        string docLabel = isPasseport ? "Passeport" : "CNI"; //objESDoc.DocumentLabel
                        ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, objDoctype.DocumentNamePrefix, docLabel, documentPath, customer.idCustomer, dictaoId, clientD3S);
                    }
                    else // changement des dates uniquement
                    {
                        string dateExpiration = Request.Params["DateExpiration"];
                        string dateEmission = string.Empty;
                        if (!isPasseport)
                            dateEmission = Request.Params["DateEmission"];

                        DateTime dDateExpiration = new DateTime();
                        if (!string.IsNullOrEmpty(dateExpiration))
                        {
                            DateTime.TryParse(dateExpiration, out dDateExpiration);
                        }

                        DateTime dDateEmission = new DateTime();
                        if (!string.IsNullOrEmpty(dateEmission))
                        {
                            DateTime.TryParse(dateEmission, out dDateEmission);
                        }

                        if (isPasseport)
                        {

                            if (dDateExpiration != null)
                            {
                                customer.PasseportDateExpired = dDateExpiration;
                            }
                        }
                        else
                        {
                            if (dDateExpiration != null)
                            {
                                customer.CNIDateExpired = dDateExpiration;
                            }

                            if (dDateEmission != null && dDateEmission != DateTime.MinValue)
                            {
                                customer.CNIEmissionDate = dDateEmission;
                            }
                        }
                        CustomerProspectBL.Update(customer);
                    }
                }
            }
            catch (Exception ex)
            {
                Business.Log.Log.AppendException(ex);
                error = ex.Message;
            }

            if (!string.IsNullOrEmpty(error))
            {
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, error); // Remove session value in "index"
            }

            return RedirectToAction("Index", "CNIPasseport", new { client = this.IsClient.ToString() });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <param name="clientD3S"></param>
        /// <returns></returns>
        public static string SendToDictaoCoffreFort(string filePath, string fileName, D3SClient clientD3S)
        {
            System.IO.FileStream fileStream = null;
            string dictaoId = string.Empty;

            try
            {
                // Lecture du fichier en Stream
                fileStream = new System.IO.FileStream(System.IO.Path.Combine(filePath, fileName), System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // Upload file to DICTAO server
                if (clientD3S == null)
                {
                    clientD3S = new D3SClient();
                }

                //Use WS or Streaming : WS if size < 1MO
                double sizeMO = fileStream.Length / 1024 / 1024;
                string[] arrFilename = fileName.Split('.');

                if (sizeMO < 1)
                {
                    dictaoId = clientD3S.WriteWS(fileName, fileName, null, null, null, null, arrFilename[1], fileStream);
                }
                else
                {
                    dictaoId = clientD3S.WriteInStreamingMode(fileName, fileName, null, null, null, null, arrFilename[1], fileStream);
                }
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

            return dictaoId;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="documentName"></param>
        /// <param name="documentType"></param>
        /// <param name="documentLabel"></param>
        /// <param name="documentLocation"></param>
        /// <param name="customerOrFirmInstitutionId"></param>
        /// <param name="dictaoId"></param>
        /// <param name="clientD3S">Set if D3S, null if DTP</param>
        /// <returns>ID ElectronicSafeDocuement</returns>
        public static Guid SaveDocumentToDB(string documentName, string documentType, string documentLabel, string documentLocation, Guid? customerOrFirmInstitutionId, string dictaoId, D3SClient clientD3S = null, bool customerDocument = true, int? idDocumentCategory = null, int? idSubscriptionFile = null, Guid? idSignatureTransaction = null)
        {
            //TODO : Gerer idCustomerOrUser
            Upsilab.Data.Model.DocumentType objDocumentType = DocumentTypeBL.GetDocumentTypeByCode(documentType);

            ElectronicSafeDocument electronicSafeDoc = new ElectronicSafeDocument()
            {
                idElectronicSafeDocument = Guid.NewGuid(),
                idDocumentType = objDocumentType.idDocumentType,
                idCustomer = (customerDocument) ? customerOrFirmInstitutionId : (Guid?)null,
                idFirmInstitution = (!customerDocument) ? customerOrFirmInstitutionId : (Guid?)null,
                idDocumentCategory = idDocumentCategory,
                IdSubscriptionFile = idSubscriptionFile,
                IdSignatureTransaction = idSignatureTransaction,
                idDictao = dictaoId,

                DocumentName = documentName,
                DocumentLabel = documentLabel,
                DocumentLocation = documentLocation,
                Signed = (clientD3S == null) ? true : false, //DTP is for signature
                DateCreated = DateTime.Now,

            };

            //Generate "Fichier d'intégrité" before save
            ElectronicSafeDocumentBL.GenerateElectronicBufferPDF(electronicSafeDoc, clientD3S);

            using (UpsilabEntities db = new UpsilabEntities())
            {
                db.ElectronicSafeDocument.AddObject(electronicSafeDoc);
                db.SaveChanges();
            }

            //List<string> excludedType = new List<string>() { "RC", "LAB", "RM", "LM" }; // l'incrementation du NbElectronicSafeDocument pour ces docs se font ailleurs
            // mise à jour des infos sur le client
            //if (customerDocument && !excludedType.Contains(documentType)) // OLD Test
            if (customerDocument)
            {
                var customer = CustomerProspectBL.GetCustomerProspectById(customerOrFirmInstitutionId.Value);
                if (customer.NbElectronicSafeDocument.HasValue)
                    customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                else
                    customer.NbElectronicSafeDocument = 1;
                CustomerProspectBL.Update(customer);
            }

            return electronicSafeDoc.idElectronicSafeDocument;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="electronicSafeDocument"></param>
        /// <param name="clientD3S">Set if D3S, null if DTP</param>
        public static void GenerateElectronicBufferPDF(ElectronicSafeDocument electronicSafeDocument, D3SClient clientD3S = null)
        {
            //Generate "Fichier d'intégrité" before save
            string pathBuffer = string.Format(@"{0}\tampon\", electronicSafeDocument.DocumentLocation);
            string filenameBuffer = string.Format(@"tampon_{0}.pdf", electronicSafeDocument.DocumentName.Split('.')[0]);
            string fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, pathBuffer);
            bool isExists = System.IO.Directory.Exists(fullPath);

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(fullPath);
            }

            bool D3S = true;
            if (electronicSafeDocument.Signed) //it's a DTP archive
            {
                D3S = false;
            }

            // Il se peut que ReadDeposit renvoie une exception, dans tel cas, générer le fichier d'attestation plus tard
            try
            {
                if (clientD3S == null)
                {
                    clientD3S = new D3SClient();
                }

                Deposit objDeposit = clientD3S.ReadDeposit(D3S, electronicSafeDocument.idDictao);
                ElectronicSafeDocumentBL.GenerateElectronicBufferPDF(objDeposit, fullPath, filenameBuffer);

                electronicSafeDocument.ElectronicBufferName = string.Concat(pathBuffer, filenameBuffer);
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }
        }
        public void ExportToCoffre()
        {
            D3SClient clientD3S = null;
            var documentFullPath = string.Empty;

            _Log.Log("To Coffre fort");
            if (string.IsNullOrEmpty(SSDirectory))
            {
                _Log.Log("Le repertoire n'existe pas");
                return;
            }
            //
            //Read directory
            //
            var allClientsDirectory = System.IO.Directory.GetDirectories(SSDirectory);
            if (allClientsDirectory == null || allClientsDirectory.Count() == 0)
            {
                _Log.Log("Repertoire vide");
                return;
            }

            foreach (var clientdir in allClientsDirectory)
            {
                try
                {
                    _Log.Log(string.Format("Repertoire = {0}", clientdir));
                    //
                    //Recuperation IdClient
                    //                                        
                    var customer = GetCustomerIDByDirectoryName(clientdir);
                    if (customer == null)
                    {
                        _Log.Log(string.Format("{0} n'est pas un client de {1}", clientdir, EmailCGP));
                        continue;
                    }
                    //
                    //
                    //
                    var clientfiles = System.IO.Directory.GetFiles(clientdir);
                    foreach (var clientfile in clientfiles)
                    {
                        try
                        {
                            var currentfile = new System.IO.FileInfo(System.IO.Path.Combine(string.Format("{0}//{1}", SSDirectory, clientdir), clientfile));
                            if (currentfile.Length <= 0)
                                continue;
                            //
                            //                    

                            _Log.Log(string.Format("--Fichier = {0}", clientfile));
                            var fileNameNoExtension = currentfile.Name.Replace(currentfile.Extension, string.Empty);
                            //
                            //Recuperation DocumentType
                            //
                            _Log.Log(string.Format("---- Récuperation DocumentType {0}", clientfile));
                            var doctype = GetDocumentTypeByFilename(fileNameNoExtension);
                            _Log.Log(string.Format("------ DocumentType {0} prefix = {1}", doctype.DocumentTypeName, doctype.DocumentNamePrefix));


                            //
                            //Recuperation Documentcategorie
                            //
                            _Log.Log(string.Format("---- Récuperation IdDocumentCategory {0}", clientfile));
                            var idDocCategory = GetDocumentCategoryIDByFileName(fileNameNoExtension);
                            _Log.Log(string.Format("---- IdDocumentCategory {0} = {1}", clientfile, idDocCategory));

                            // 2- Upload file to DICTAO server

                            _Log.Log(string.Format("Envoi {0} to Dictao", currentfile.Name));
                            clientD3S = new D3SClient();
                            string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(currentfile.DirectoryName, currentfile.Name, clientD3S);
                            _Log.Log(string.Format("{0} envoyé", currentfile.Name));

                            //
                            //Copy File
                            //         
                            _Log.Log(string.Format("---- Copy Fichier {0} = {1}", clientfile, idDocCategory));
                            var documentLabel = currentfile.Name.Replace(currentfile.Extension, string.Empty); //nom du fichier sans extension
                            var documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(doctype.DocumentNamePrefix, customer, false);
                            documentFullPath = System.IO.Path.Combine(CoffreFortRootPath, documentPath);
                            System.IO.File.Move(currentfile.FullName, System.IO.Path.Combine(documentFullPath, currentfile.Name));

                            //
                            //
                            // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_DIVERS_DOCUMENTS"
                            if (!string.IsNullOrEmpty(dictaoId))
                            {
                                CreditOperationBL.OperationType creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; //Tojours soustraire un credit

                                _Log.Log(string.Format("Gestion Crédit : Soustraction de crédits"));
                                CreditOperationBL.SubstractCredit(IdFirmInstitution, creditOperationType.ToString(), IdUser, customer.idCustomer);

                                // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                                _Log.Log(string.Format("Sauvegarde dans la base (table ElectronicSafeDocument)"));
                                ElectronicSafeDocumentBL.SaveDocumentToDB(currentfile.Name, doctype.DocumentNamePrefix, documentLabel, documentPath, customer.idCustomer, dictaoId, clientD3S, (customer != null) ? true : false, idDocCategory);
                            }
                        }
                        catch (Exception ex)
                        {
                            _Log.Log(string.Format("{0}", ex.Message));
                            Business.Log.Log.AppendException(ex);
                        }
                    }
                }
                catch (Exception e)
                {
                    _Log.Log(string.Format("{0}", e.Message));
                    Business.Log.Log.AppendException(e);
                }
            }
        }