Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Ionic.Zip;
- using PaperSoft.Mobile.BusinessService.ViewModel.Operations.EForm;
- using PaperSoftBusiness;
- using PaperSoftClassification;
- using PaperSoftData;
- using PaperSoftDocumentImporterLibrary.Helpers;
- using PaperSoftDocumentImporterLibrary.Mobile;
- using PaperSoftKernelAPI.Entities.Operations.EForm;
- using PaperSoftKernelAPI.Services.Factories;
- using PaperSoftSuportAPI.PapersoftHelperAPI;
- using PaperSoftTemplates;
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Runtime.Serialization.Json;
- using System.ServiceModel;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Security.Cryptography.X509Certificates;
- using Org.BouncyCastle.Bcpg.OpenPgp;
- using Org.BouncyCastle.Crypto;
- using Org.BouncyCastle.Crypto.Parameters;
- using Org.BouncyCastle.Math;
- using Org.BouncyCastle.OpenSsl;
- using Org.BouncyCastle.Security;
- using Org.BouncyCastle.Utilities.IO;
- using System.Security.Cryptography;
- using System.Diagnostics;
- using RestSharp;
- using PaperSoft.MobileBaseService;
- namespace PaperSoftDocumentImporterLibrary
- {
- public class ImportMobileFileToPps
- {
- private ServiceParameters sp;
- public List<PpsEformImporterViewModel> ListPpsOpEForm { get; set; }
- public ImportMobileFileToPps(ServiceParameters sParams)
- {
- FileImportResult.Init();
- sp = sParams;
- }
- #region Zip Decryption
- public void DoZipDecipher()
- {
- //BasicHttpBinding binding = new BasicHttpBinding();
- //EndpointAddress address = new EndpointAddress(sp.PpsVMEndPoint);
- // PpsVMServiceReference.ServiceClient service = new PpsVMServiceReference.ServiceClient();//binding, address);
- // var a = service.GetOperationEForm(ObjectId.Parse("55cc5d41005f7215f4214862"));
- List<FileInfo> lstFileDecipher = Helpers.Helpers.GetDirectoryFiles(sp.FolderInput, System.IO.SearchOption.TopDirectoryOnly, "*.PGP");
- List<FileInfo> lstFileDecipherProcessed = new List<FileInfo>();
- foreach (FileInfo fi in lstFileDecipher)
- {
- try
- {
- string operationId = fi.Name.Split('_')[0]; //operationId
- X509Certificate2 cert = new X509Certificate2(sp.CertificateFilePath, sp.CertificateFilePassword, X509KeyStorageFlags.Exportable);
- //X509Certificate2 cert = GetCertificateFromLocalMachine(sp.CertificateSerialNumber);
- AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private;
- using (Stream f = File.OpenRead(fi.FullName))
- {
- Decrypt(f, fi.Directory + "\\" + fi.Name.Replace(".PGP", ""), privateKey);
- }
- GC.Collect();
- lstFileDecipherProcessed.Add(fi);
- }
- catch (Exception e)
- {
- MoveToFolder(fi, sp.FolderError);
- //throw e;
- }
- }
- //To Delete Cyphered Files
- foreach (FileInfo fi in lstFileDecipherProcessed)//lstFileDecipher)
- {
- File.Delete(fi.FullName);
- }
- GC.Collect();
- }
- private void MoveToFolder(FileInfo fs, string pDestinationFolder)
- {
- try
- {
- string destFolder = Path.Combine(pDestinationFolder, DateTime.Now.ToString("yyyyMMdd"));
- DirectoryInfo di = new DirectoryInfo(destFolder);
- if (!di.Exists)
- di.Create();
- int i = 1;
- string destPath = Path.Combine(destFolder, fs.Name);
- FileInfo fDest = new FileInfo(destPath);
- while (fDest.Exists)
- {
- // infinite loop protection
- if (i > 15)
- throw new Exception("Unable to get new filename. Original destPath: " + destPath);
- fDest = new FileInfo(Path.Combine(fDest.DirectoryName,
- Path.GetFileNameWithoutExtension(fDest.Name) + "(" + i++ + ")" + fDest.Extension));
- }
- (new FileInfo(fs.FullName)).MoveTo(fDest.FullName);
- }
- catch (Exception ex)
- {
- //FileImportResult.List.Add(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorMovingFile) + " FILE: " + fs.FileName + " Stack:" + ex.ToString());
- }
- }
- public static void Decrypt(Stream input, string outputpath, AsymmetricKeyParameter privateKeyPath)
- {
- input = PgpUtilities.GetDecoderStream(input);
- try
- {
- PgpObjectFactory pgpObjF = new PgpObjectFactory(input);
- PgpEncryptedDataList enc;
- PgpObject obj = pgpObjF.NextPgpObject();
- if (obj is PgpEncryptedDataList)
- {
- enc = (PgpEncryptedDataList)obj;
- }
- else
- {
- enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
- }
- var akp = new AsymmetricKeyParameter(true);
- PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast<PgpPublicKeyEncryptedData>().First();
- PgpPrivateKey privKey = new PgpPrivateKey(privateKeyPath, pbe.KeyId);
- Stream clear;
- clear = pbe.GetDataStream(privKey);
- PgpObjectFactory plainFact = new PgpObjectFactory(clear);
- PgpObject message = plainFact.NextPgpObject();
- if (message is PgpCompressedData)
- {
- PgpCompressedData cData = (PgpCompressedData)message;
- Stream compDataIn = cData.GetDataStream();
- PgpObjectFactory o = new PgpObjectFactory(compDataIn);
- message = o.NextPgpObject();
- if (message is PgpOnePassSignatureList)
- {
- message = o.NextPgpObject();
- PgpLiteralData Ld = null;
- Ld = (PgpLiteralData)message;
- Stream output = File.Create(outputpath + "\\" + Ld.FileName);
- Stream unc = Ld.GetInputStream();
- Streams.PipeAll(unc, output);
- }
- else
- {
- PgpLiteralData Ld = null;
- Ld = (PgpLiteralData)message;
- //Stream output = File.Create(outputpath + "\\" + Ld.FileName);
- Stream output = File.Create(outputpath);
- Stream unc = Ld.GetInputStream();
- Streams.PipeAll(unc, output);
- }
- }
- }
- catch (Exception e)
- {
- throw new Exception(e.Message);
- }
- }
- private static X509Certificate2 GetCertificateFromLocalMachine(string certName)
- {
- // Get the certificate store for the current user.
- X509Store store = new X509Store(StoreLocation.LocalMachine);
- try
- {
- store.Open(OpenFlags.ReadOnly);
- // Place all certificates in an X509Certificate2Collection object.
- X509Certificate2Collection certCollection = store.Certificates;
- // If using a certificate with a trusted root you do not need to FindByTimeValid, instead:
- // currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true);
- X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
- foreach (X509Certificate2 mCert in currentCerts)
- {
- if (string.Compare(certName, mCert.SerialNumber.ToLower(), StringComparison.InvariantCulture) == 0)
- {
- return mCert;
- }
- //TODO's
- }
- return null;
- }
- finally
- {
- store.Close();
- }
- }
- private void DecipherFile(FileInfo pCipheredFile, string pEncryptionKey)
- {
- string unCipheredFileName = pCipheredFile.Directory.FullName + "\\" + pCipheredFile.Name + ".zip";
- try
- {
- byte[] cipheredBytes = System.IO.File.ReadAllBytes(pCipheredFile.FullName);
- //uncipher here
- Stream stream = new MemoryStream(cipheredBytes);
- //full path example \\172.16.3.39\c$\inetpub\wwwroot\PpsSubmissionWSXpandIT\Uploads\ToTest\3bff0cd4-b514-4016-8708-fc49d63cc2c8-0006_pps.VM1.ZIP
- using (FileStream fileStream = File.Create(unCipheredFileName, (int)stream.Length))
- {
- byte[] bytesInStream = new byte[stream.Length];
- stream.Read(bytesInStream, 0, bytesInStream.Length);
- fileStream.Write(bytesInStream, 0, bytesInStream.Length);
- }
- }
- catch (Exception e)
- {
- File.Delete(unCipheredFileName);
- }
- }
- #endregion
- #region Zip Importation
- public List<string> DoFileImport()
- {
- ListPpsOpEForm = new List<PpsEformImporterViewModel>();
- DateTime currentDate = DateTime.UtcNow;
- try
- {
- CheckAppRequirements();
- List<FileInfo> lstFiles = Helpers.Helpers.GetDirectoryFiles(sp.FolderInput, System.IO.SearchOption.TopDirectoryOnly, "*.ZIP");
- foreach (FileInfo fi in lstFiles)
- {
- ImportFile(fi, currentDate);
- }
- }
- catch (Exception ex)
- {
- if (ex.Message.StartsWith("x1"))
- FileImportResult.List.Add(ex.Message);
- else
- FileImportResult.List.Add(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorGeneralError) + " (" + ex.ToString() + ")");
- }
- return FileImportResult.List;
- }
- private void CheckAppRequirements()
- {
- DirectoryInfo dinfo = null;
- try
- {
- dinfo = new DirectoryInfo(sp.FolderBackup);
- if (!dinfo.Exists)
- dinfo.Create();
- dinfo = new DirectoryInfo(sp.FolderError);
- if (!dinfo.Exists)
- dinfo.Create();
- dinfo = new DirectoryInfo(sp.FolderInput);
- if (!dinfo.Exists)
- dinfo.Create();
- }
- catch (Exception ex)
- {
- throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorFolderAccess) + " for Folder: " + sp.FolderInput, ex);
- }
- }
- public void ImportFile(FileInfo pFile, DateTime pCurrentDate)//, int statusID, EForm pEForm, bool pOneCoverPerDay)
- {
- FileSave fileSave = new FileSave();
- string exceptionDetail = string.Empty;
- bool flag = false;
- try
- {
- fileSave.CurrentDate = pCurrentDate;
- fileSave.CreateDate = pFile.CreationTime;
- fileSave.Extension = pFile.Extension;
- fileSave.FileName = pFile.Name;
- fileSave.FullName = pFile.FullName;
- fileSave.IsImported = false;
- fileSave.IsDuplicated = false;
- fileSave.IsValid = false;
- fileSave = LoadFile(fileSave);
- if (fileSave.IsValid)
- {
- CreateFiles(fileSave, pCurrentDate);// sp.kwLote, sp.OneCoverPerDay, sp.CoverDocLenght);
- }
- }
- catch (Exception ex)
- {
- EventLogger.WriteErrorEvent(ex.Message);
- if (ex.Message.StartsWith("Process ID Configurated "))
- flag = true;
- if (ex.Message.StartsWith("x1"))
- {
- //FileImportResult.List.Add(ex.Message);
- exceptionDetail = ex.Message;
- }
- else
- // FileImportResult.List.Add(Helpers.GetDescription(Results.ErrorResults.ErrorProcessingFile) + " (" + ex.ToString() + ")");
- exceptionDetail = Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorProcessingFile) + " (" + ex.ToString() + ")";
- }
- finally
- {
- if (!flag)
- {
- MoveToFolder(fileSave);
- WriteImportResult(fileSave, exceptionDetail);
- }
- }
- }
- private void MoveToFolder(FileSave fs)
- {
- try
- {
- string destFolder = string.Empty;
- if (fs.IsValid && fs.IsImported)
- destFolder = Path.Combine(sp.FolderBackup, DateTime.Now.ToString("yyyyMMdd"));
- else if (fs.IsValid && fs.IsDuplicated)
- destFolder = Path.Combine(sp.FolderError, DateTime.Now.ToString("yyyyMMdd"), "TRANSFER_ERRORS");
- else
- destFolder = Path.Combine(sp.FolderError, DateTime.Now.ToString("yyyyMMdd"));
- //string destFolder = Path.Combine((fs.IsValid && fs.IsImported) ? sp.FolderBackup : sp.FolderError, DateTime.Now.ToString("yyyyMMdd"));
- DirectoryInfo di = new DirectoryInfo(destFolder);
- if (!di.Exists)
- di.Create();
- int i = 1;
- string destPath = Path.Combine(destFolder, fs.FileName);
- FileInfo fDest = new FileInfo(destPath);
- while (fDest.Exists)
- {
- // infinite loop protection
- if (i > 15)
- throw new Exception("Unable to get new filename. Original destPath: " + destPath);
- fDest = new FileInfo(Path.Combine(fDest.DirectoryName,
- Path.GetFileNameWithoutExtension(fDest.Name) + "(" + i++ + ")" + fDest.Extension));
- }
- (new FileInfo(fs.FullName)).MoveTo(fDest.FullName);
- }
- catch (Exception ex)
- {
- FileImportResult.List.Add(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorMovingFile) + " FILE: " + fs.FileName + " Stack:" + ex.ToString());
- }
- }
- private void MergeImages(ref FileSave zipFile, string pProcessTag, short pTemplateID, string pConstr, string pFormTemplateName)
- {
- List<Image> imgList = new List<Image>();
- byte[] content = null;
- //TODO: FAZER MERGE DAS IMAGENS (signature, Image ou FingerPrint com o formulário)
- byte[] lstDocPdf = null;
- var lstDocs = zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "JPEG").Where(m => m.FileName.StartsWith("FORM"))
- .OrderBy(n => n.FileName).ToList();
- Dictionary<string, byte[]> pFieldImages = new Dictionary<string, byte[]>();
- var lstSignature = zipFile.ZipContents.Where(m => m.FileName.StartsWith("SIGNATURE"))
- .OrderBy(n => n.FileName).ToList();
- if (lstSignature.Count > 0)
- {
- foreach (var sig in lstSignature)
- {
- pFieldImages.Add(sig.FileName.Split('.').FirstOrDefault(), sig.File);
- }
- }
- if (pFormTemplateName != string.Empty)
- lstDocPdf = Mobile.PdfBuilder.BuildDocumentFormVodaCom(zipFile.NewFile.JsonMetadata, pFieldImages, pFormTemplateName, pTemplateID, pConstr, sp);
- else if (zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "PDF").Where(m => m.FileName.StartsWith("FORM"))
- .OrderBy(n => n.FileName).FirstOrDefault() != null)
- lstDocPdf = zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "PDF").Where(m => m.FileName.StartsWith("FORM"))
- .OrderBy(n => n.FileName).FirstOrDefault().File;
- var lstImages = zipFile.ZipContents.Where(m => m.FileName.StartsWith("IMAGE"))// && (!m.FileName.StartsWith("IMAGE_11_1") && !m.FileName.StartsWith("IMAGE_23_1")))// && !m.FileName.Equals("IMAGE_10")) //Where(n => n.Extension.ToUpper() == "JPEG")
- .OrderBy(n => n.FileName).ToList();
- //&& !m.FileName.Equals("IMAGE_11_1") && !m.FileName.Equals("IMAGE_23_1"
- lstDocs.AddRange(lstImages);
- content = lstDocPdf;
- if (lstDocs.Any())
- {
- if (content == null)
- {
- content = PdfFunctions.ImageToPdf(lstDocs[0].File);
- for (int i = 1; i < lstDocs.Count; i++)
- {
- byte[] tempBolb = new MemoryStream(lstDocs[i].File).ToArray();
- content = AppendImageToPdf(content, tempBolb, new Point(0, 0));
- }
- }
- else
- {
- for (int i = 0; i < lstDocs.Count; i++)
- {
- byte[] tempBolb = new MemoryStream(lstDocs[i].File).ToArray();
- content = AppendImageToPdf(content, tempBolb, new Point(0, 0));
- }
- }
- }
- //if (lstDocPdf != null)
- // content = PaperSoftSuportAPI.PapersoftHelperAPI.PdfFunctions.CombinePdf(lstDocPdf, content);
- //string fileName = Path.Combine(Application.StartupPath, @"PdfFormTemplates\" + zipFile.FileName + ".pdf");
- //using (FileStream _FileStream = new FileStream(fileName, System.IO.FileMode.Create, FileAccess.Write))
- //{
- // _FileStream.Write(content, 0, content.Length);
- // _FileStream.Close();
- //}
- GC.Collect();
- zipFile.NewFile.File = content;
- zipFile.NewFile.Extension = ".pdf";
- zipFile.NewFile.FileName = Path.GetFileNameWithoutExtension(zipFile.NewFile.FileName) + zipFile.NewFile.Extension;
- }
- public static byte[] AppendImageToPdf(byte[] pdf, byte[] img, Point position, double scale = 1)
- {
- using (System.IO.MemoryStream msPdf = new System.IO.MemoryStream(pdf))
- {
- using (System.IO.MemoryStream msImg = new System.IO.MemoryStream(img))
- {
- System.Drawing.Image image = System.Drawing.Image.FromStream(msImg);
- PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(msPdf);
- PdfSharp.Pdf.PdfPage page = document.AddPage();
- //PdfSharp.Pdf.PdfPage page = document.Pages[0];
- PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page);
- PdfSharp.Drawing.XImage ximg = PdfSharp.Drawing.XImage.FromGdiPlusImage(image);
- double imageWidth = ximg.Width;
- double imageHeigth = ximg.Height;
- if (imageWidth > page.Width)
- {
- imageHeigth = (imageHeigth / imageWidth) * page.Width;
- imageWidth = page.Width;
- }
- else if (imageHeigth > page.Height)
- {
- imageWidth = (imageWidth / imageHeigth) * page.Height;
- imageHeigth = page.Height;
- }
- gfx.DrawImage(
- ximg,
- position.X,
- position.Y,
- imageWidth * scale,
- imageHeigth * scale
- );
- using (System.IO.MemoryStream msFinal = new System.IO.MemoryStream())
- {
- document.Save(msFinal);
- return msFinal.ToArray();
- }
- }
- }
- }
- private FileSave LoadFile(FileSave fileToImport)
- {
- if (fileToImport.Extension.ToUpper() == ".ZIP")
- {
- fileToImport.IsZip = true;
- fileToImport.ZipContents = new List<FileSave>();
- fileToImport.ZipContents = UnzipFiles(fileToImport);
- ValidateZipFiles(fileToImport);
- fileToImport.NewFile = new MobileFile();
- fileToImport.NewFile.CreateDate = fileToImport.CreateDate;
- fileToImport.NewFile.JsonMetadata = LoadAndCheckMetadata(fileToImport);
- fileToImport.NewFile.JsonFormErrors = LoadAndCheckFormErrors(fileToImport);
- fileToImport.NewFile.FileName = Path.GetFileNameWithoutExtension(fileToImport.FileName) + fileToImport.NewFile.Extension;
- fileToImport.IsValid = true;
- }
- else
- {
- throw new Exception("Invalid extension to import");
- }
- return fileToImport;
- }
- private PpsEformViewModel LoadAndCheckMetadata(FileSave zipFile)
- {
- string jsonData = string.Empty;
- PpsEformViewModel metadata = null;// new JsonMetadata();
- try
- {
- var jsonFile = zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "JSON").FirstOrDefault();
- using (StreamReader sr = new StreamReader(new MemoryStream(jsonFile.File)))
- {
- jsonData = sr.ReadToEnd();
- }
- if (!string.IsNullOrEmpty(jsonData))
- {
- // metadata = Helpers.GetJsonData<PpsEformViewModel>(jsonData);
- var bytes = Encoding.UTF8.GetBytes(jsonData);
- using (var stream = new MemoryStream(bytes))
- {
- var serializer = new DataContractJsonSerializer(typeof(PpsEformViewModel));
- metadata = (PpsEformViewModel)serializer.ReadObject(stream);
- }
- }
- else
- throw new Exception("found empty metadata ");
- }
- catch (Exception ex)
- {
- throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorGettingMetadata) + "(" + ex.Message + ")", ex);
- }
- return metadata;
- }
- private FormErrors LoadAndCheckFormErrors(FileSave zipFile)
- {
- string jsonData = string.Empty;
- FormErrors metadata = new FormErrors();
- try
- {
- var jsonFile = zipFile.ZipContents.Where(n => n.FileName == "ERROS.TXT").FirstOrDefault();
- using (StreamReader sr = new StreamReader(new MemoryStream(jsonFile.File)))
- {
- jsonData = sr.ReadToEnd();
- }
- if (!string.IsNullOrEmpty(jsonData) && jsonData != "{}")
- {
- metadata = FormErrors.FromJson(jsonData);
- }
- }
- catch (Exception ex)
- {
- //throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorGettingJsonErrors) + "(" + ex.Message + ")", ex);
- }
- return metadata;
- }
- private bool ValidateZipFiles(FileSave zipFile)
- {
- bool isValid = false;
- bool hasData = false;
- bool hasForm = false;
- //bool hasInvalidContent = false;
- if (zipFile.ZipContents != null)
- {
- foreach (FileSave fs in zipFile.ZipContents)
- {
- if (Path.GetFileNameWithoutExtension(fs.FileName.ToUpper()).StartsWith("DATA") && fs.Extension.ToUpper() == "JSON")
- hasData = true;
- //else if (Path.GetFileNameWithoutExtension(fs.FileName.ToUpper()).StartsWith("FORM")
- // && fs.Extension.ToUpper() == "JPEG")
- hasForm = true;
- //else
- // hasInvalidContent = true;
- }
- if (hasData && hasForm)// && !hasInvalidContent)
- isValid = true;
- else
- throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorInvalidZipContent));
- }
- return isValid;
- }
- private List<FileSave> UnzipFiles(FileSave fi)
- {
- var lstFilesToImport = new List<FileSave>();
- try
- {
- MemoryStream msZip = new MemoryStream(System.IO.File.ReadAllBytes(fi.FullName));
- using (ZipFile zFile = ZipFile.Read(msZip))
- {
- foreach (ZipEntry ze in zFile)
- {
- MemoryStream ms = new MemoryStream();
- ze.Extract(ms);
- var fileSave = new FileSave()
- {
- CreateDate = DateTime.Now,
- Extension = ze.FileName.Split('.')[ze.FileName.Split('.').Length - 1],
- File = ms.ToArray(),
- FileName = ze.FileName,
- IsValid = true,
- IsImported = false,
- TotalPages = Helpers.Helpers.CountPages(ms.ToArray(), ze.FileName.Split('.')[ze.FileName.Split('.').Length - 1]),
- };
- lstFilesToImport.Add(fileSave);
- }
- }
- }
- catch (Exception ex)
- {
- throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorExtractingZipFiles) + " FILE: " + fi.FileName + " (" + ex.Message + ")");
- }
- return (lstFilesToImport != null && lstFilesToImport.Count > 0) ? lstFilesToImport.OrderBy(n => n.FileName).ToList() : lstFilesToImport;
- }
- private PpsEformImporterViewModel GetOperationMongo(string pServiceUrl, string pOperationId)
- {
- PpsEformImporterViewModel eformOperation = null;
- RestClient restClient = new RestClient(pServiceUrl + pOperationId);
- var request = new RestRequest(RestSharp.Method.GET);
- request.RequestFormat = DataFormat.Json;
- var resp = restClient.Execute(request);
- if (resp.StatusCode != HttpStatusCode.OK) {
- throw new Exception(string.Format("Unable To {0} Connect to DB Mongo for operationID: {1}", pServiceUrl, pOperationId));
- }
- try
- {
- eformOperation = (PpsEformImporterViewModel)Helpers.Helpers.ConvertJsonToObject<PpsEformImporterViewModel>(resp.Content);
- }
- catch (Exception e)
- {
- throw new Exception(string.Format("Unable To serialize operation: {0}", e.Message));
- }
- return eformOperation;
- }
- private void CreateFiles(FileSave fi, DateTime currentDate)// string pLoteKeyword, bool pOneCoverPerDay, int pCoverDocLenght)
- {
- if (fi.IsValid)
- {
- //PpsOpEForm eformOperation = null;
- PpsEformImporterViewModel eformOperation = null;
- string currentOperationID = string.Empty;
- try
- {
- currentOperationID = fi.NewFile.JsonMetadata.ID;
- //MARTELADA VMDRC
- if (currentOperationID == "5679724a91169012887f0f66" || currentOperationID == "5679724a91169012887f0f67")
- currentOperationID = "5679724a91169012887f0f67";
- if (currentOperationID == "5679724a91169012887f0f6a" || currentOperationID == "5679724a91169012887f0f6b")
- currentOperationID = "5679724a91169012887f0f6b";
- if (ListPpsOpEForm.Where(n => n.ID == currentOperationID.ToString()).Any())
- eformOperation = ListPpsOpEForm.Where(n => n.ID == currentOperationID.ToString()).FirstOrDefault();
- else
- {
- eformOperation = GetOperationMongo(sp.PpsMobileBusinessEndPoint, currentOperationID);
- ListPpsOpEForm.Add(eformOperation);
- }
- }
- catch (Exception e)
- {
- throw new Exception("Unable To Connect to DB Mongo for operationID:" + fi.NewFile.JsonMetadata.ID.ToString());
- }
- string cipherConString = eformOperation.PapersoftAddress.Database.ConnectionString;
- string conString = SecureDataTransfer.DecryptText(cipherConString, PpsMobileBaseService.ENCRYPTION_SALT);
- int custID = eformOperation.PapersoftAddress.ClientID;
- Guid processID = eformOperation.PapersoftAddress.ProcessID;
- ProcessTemplate procInProcess = sp.ProcessTemplateList.Where(n => n.ProcessId == processID).FirstOrDefault();
- if (procInProcess == null || (procInProcess != null && processID != procInProcess.ProcessId))
- throw new Exception("Process ID Configurated is different Between JSON File and DBMongo " + processID);
- PsCustomerProcess process = PsCustomerProcess.ListCustomerProcesses(conString, custID)
- .Where(n => n.PSCUST_PROCESS_ID == processID).FirstOrDefault();
- short templateID = IndexTemplate.GetIndexTemplateByProcess(conString, process.PSCUST_PROCESS_ID).IXT_ID;
- fi.NewFile.ImportedProcessCode = process.PSCUST_PROCESS_CODE;
- fi.NewFile.DocStatus = procInProcess.DocStatusDoc;
- IndexTemplate template = IndexTemplate.GetIndexTemplateByProcess(conString, processID);
- bool existZip = CheckIfDocumentExist(conString, templateID, custID, fi.NewFile.FileName);
- if (existZip)
- fi.IsDuplicated = true;
- else
- {
- #region Old Code
- ////TODO: VODACOM
- //ObjectId eformID_NewSIM = ObjectId.Parse("55cc5d41005f7215f4214862");
- //ObjectId eformID_NewSIMWitness = ObjectId.Parse("56167f0b99de4b3340575227");
- //ObjectId eformID_PreReg = ObjectId.Parse("55cc5c1e005f7215f421472b");
- //ObjectId eformID_PreRegWitness = ObjectId.Parse("56167f0b99de4b3340575228");
- //ObjectId eformID_Bank = ObjectId.Parse("55afdb8899de4b00bcd83a3c");
- //ObjectId eformID_Telco = ObjectId.Parse("55c8c02a99de4b11b8a230e3");
- ////TODO: DOXIS
- //ObjectId eFormId_DoxisBank = ObjectId.Parse("56b334c39116903cf00e58f6");
- //ObjectId eFormId_DoxisExpense = ObjectId.Parse("563ccb4f96e33d364865dc98");
- ////TODO: VM CONGO
- //ObjectId eFormId_CongoNewSubscriber = ObjectId.Parse("563ced5996e33d2d64205cd5");
- //ObjectId eFormId_CongoExistingSubscriber = ObjectId.Parse("563ced5996e33d2d64205cd6");
- //string registerType = string.Empty;
- //if (eformOperation.Id.Equals(eformID_NewSIM) || eformOperation.Id.Equals(eformID_NewSIMWitness))
- // registerType = "1";
- //else if (eformOperation.Id.Equals(eformID_PreReg) || eformOperation.Id.Equals(eformID_PreRegWitness))
- // registerType = "2";
- //string formTemplateName = (eformOperation.Id.Equals(eformID_NewSIM) || eformOperation.Id.Equals(eformID_PreReg))
- // ? "VODACOM_FORM.PDF" : "VODACOM_WITNESS_FORM.PDF";
- //if (eformOperation.Id.Equals(eformID_Bank) || eformOperation.Id.Equals(eFormId_DoxisContract))
- //{
- // formTemplateName = "BANK_FORM.pdf";
- // registerType = "3";
- //}
- //else if (eformOperation.Id.Equals(eformID_Telco))
- //{
- // formTemplateName = "TELCO_FORM.pdf";
- // registerType = "3";
- //}
- #endregion
- MergeImages(ref fi, process.PSCUST_PROCESS_TAG, templateID, conString, sp.FormTemplatePDFName);
- #region Old Code
- //if (eformOperation.Id.Equals(eFormId_CongoExistingSubscriber))
- //{
- // foreach (var fieldGroup in fi.NewFile.JsonMetadata.FieldGroups)
- // {
- // var field = fieldGroup.TemplateFields.Where(n => n.Keyword.ToUpper() == "kwMobileNr".ToUpper()).FirstOrDefault();
- // IndexTemplateField templateField = IndexTemplateField.ListIndexTemplatesFieldsWithKeyword(conString, templateID)
- // .FirstOrDefault(f => f.FIELD_KEYWORD.ToUpper() == field.Keyword.ToUpper());
- // List<PsDocumentClassification> lstFields = new List<PsDocumentClassification>();
- // lstFields.Add(new PsDocumentClassification()
- // {
- // IXTF_ORDER = templateField.IXTF_ORDER,
- // VALUE = field.Value.FirstOrDefault().Trim()
- // });
- // List<PsDocument> lstDocs = PsDocument.SearchDocument(conString, PsDocument.DocumentType.Document, templateID, process.CUST_ID, -1, -1, null, null, lstFields);
- // if (lstDocs == null || !lstDocs.Any())
- // throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorDocumentNotExist));
- // PsDocument doc = lstDocs.FirstOrDefault();
- // doc.CLASSIFICATION = PsDocumentClassification.LoadPsDocumentClassification(conString, doc.RDOC_ID);
- // doc.LoadPsDocumentBlob();
- // doc.LstPsDocumentBlob = null;
- // if (doc.RDOC_STATUS_ID == 14003)
- // {
- // PsDocumentBlob docBlob = new PsDocumentBlob(conString);
- // docBlob.RDOC_ID = doc.RDOC_ID;
- // docBlob.RDCC_N_PAGE = Helpers.Helpers.CountPages(fi.NewFile.File, "pdf");
- // docBlob.RDCC_FILENAME = fi.NewFile.FileName;
- // docBlob.RDCC_BLOB = fi.NewFile.File;
- // docBlob.RDCC_EXT_ID = 0;
- // docBlob.B_ATTACHMENT = 0;
- // docBlob.RDCC_ID = PaperSoftBusiness.PsFsCode.GetCode(PaperSoftBusiness.PsFsCode.FsCodeTableName.PSREPDOCC, doc.ConStr);
- // docBlob.DFTY_ID = doc.DFTY_ID;
- // docBlob.DOC_FORMAT_TYPE_EXT = doc.RDOC_DEFAULT_DOCFORMAT_EXT;
- // docBlob.CreatePsDocumentBlob();
- // fi.NewFile.PsDocument = doc;
- // doc = Document.CreateDocClassification(fi.NewFile, conString, registerType);
- // doc.RDOC_STATUS_ID = 9001;
- // doc.UpdatePsDocument();
- // fi.IsImported = true;
- // fi.NewFile.PsDocument = doc;
- // }
- // else
- // throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorDocumentNotExist));
- // break;
- // }
- //}
- //else
- //{
- #endregion
- PsShipping psShipping = Shipping.GetPsShipping(sp.ApplicationName, custID, " Mobile Capture - ",
- process.PSCUST_PROCESS_CODE,
- conString,
- currentDate, sp.CoverDocLenght);
- // Get or create cover...
- PsDocument coverDoc = Document.CreateCover("MobileCapture.UploadForm",
- psShipping.ShippingDescription,
- conString,
- procInProcess.DocStatusCover, custID, processID,
- psShipping,
- template.IXT_ID, sp.OneCoverPerDay, currentDate, sp.kwLote);
- PsDocument doc = Document.CreateDoc("MobileCapture.UploadForm", conString, procInProcess.DocStatusDoc, coverDoc, fi.NewFile);
- fi.NewFile.PsDocument = doc;
- fi.NewFile.PsDocument = Document.CreateDocClassification(fi.NewFile, conString, sp, sp.ImportHistoricalLog);
- fi.IsImported = true;
- #region Old Code
- //EventLogger.WriteInfoEvent("Entering Doxis");
- //if ((eformOperation.Id.Equals(eFormId_DoxisBank))) // || (eformOperation.Id.Equals(eFormId_DoxisExpense)))
- //{
- // EventLogger.WriteInfoEvent("Loading doc blob");
- // fi.NewFile.PsDocument.LoadPsDocumentBlob();
- // PsDocumentBlob documentToUpload = fi.NewFile.PsDocument.LstPsDocumentBlob.FirstOrDefault();
- // EventLogger.WriteInfoEvent("Loading doc Metadata");
- // Dictionary<string, string> docMetadata = new Dictionary<string, string>();
- // var templateFields = IndexTemplateField.ListIndexTemplatesFieldsWithKeyword(conString, fi.NewFile.PsDocument.IXT_ID);
- // fi.NewFile.PsDocument.CLASSIFICATION = PsDocumentClassification.LoadPsDocumentClassification(conString, doc.RDOC_ID);
- // fi.NewFile.PsDocument.CLASSIFICATION.ForEach(m => docMetadata.Add(templateFields.FirstOrDefault(tf => tf.IXTF_ORDER == m.IXTF_ORDER).FIELD_KEYWORD, m.VALUE));
- // DateTime uploadTime = DateTime.MinValue;
- // EventLogger.WriteInfoEvent("Start Uploading to CMIS");
- // DoxisCmisUploader.Init(sp.DoxisSecuritySettings);
- // EventLogger.WriteInfoEvent("EFormOperation: " + eformOperation.Id);
- // if (eformOperation.Id.Equals(eFormId_DoxisBank))
- // {
- // EventLogger.WriteInfoEvent("Start Uploading Contract");
- // var totalPages = PdfFunctions.PdfPageCount(documentToUpload.RDCC_BLOB);
- // var firstPage = PdfFunctions.SplitPdf(documentToUpload.RDCC_BLOB, 1, 1);
- // uploadTime = DoxisCmisUploader.UploadContractDoc(sp.DoxisBankSpecification, documentToUpload.RDCC_FILENAME, documentToUpload.RDCC_BLOB, docMetadata);
- // if (totalPages > 2)
- // {
- // var restOfPages = PdfFunctions.SplitPdf(documentToUpload.RDCC_BLOB, 2, totalPages);
- // uploadTime = DoxisCmisUploader.UploadContractDoc(sp.DoxisBankSpecification, documentToUpload.RDCC_FILENAME, restOfPages, docMetadata);
- // }
- // }
- // //else if (eformOperation.Id.Equals(eFormId_DoxisExpense))
- // //{
- // // EventLogger.WriteInfoEvent("Start Uploading Expense");
- // // uploadTime = DoxisCmisUploader.UploadExpenseDoc(sp.DoxisDocumentExpensesSpecification, documentToUpload.RDCC_FILENAME, documentToUpload.RDCC_BLOB, docMetadata);
- // //}
- // EventLogger.WriteInfoEvent("End Uploading to CMIS");
- // using (PaperSoft100_TPH_BASE_ProductionEntities ctx = Helpers.Helpers.SetEntityContext(conString))
- // {
- // doc.LogPsDocumentOperation(ctx, 1, sp.ApplicationName.ToUpper(), "CMIS Uploaded at: " + uploadTime.ToString() + " !", doc.RDOC_USER_CREATE);
- // }
- //}
- #endregion
- }
- }
- else
- fi.IsImported = false;
- }
- #endregion
- private bool CheckIfDocumentExist(string pConString, short pTemplateID, int pCustID, string pFileName)
- {
- var lstZipFileName = pFileName.Split('_');
- List<PsDocumentClassification> lstToSearch = new List<PsDocumentClassification>();
- IndexTemplateField tFieldZipName = IndexTemplateField.ListIndexTemplatesFieldsWithKeyword(pConString, pTemplateID)
- .FirstOrDefault(f => f.FIELD_KEYWORD.ToUpper() == "ZIP_FILENAME");
- lstToSearch.Add(new PsDocumentClassification
- {
- IXTF_ORDER = tFieldZipName.IXTF_ORDER, //46,
- VALUE = lstZipFileName.FirstOrDefault()
- });
- List<PsDocument> lstMobileDocuments = PsDocument.SearchDocument(pConString, PsDocument.DocumentType.Document,
- pTemplateID, -1, -1, -1, null, null, lstToSearch);
- var exists = PsDocument.SearchDocument(pConString, PsDocument.DocumentType.Document,
- pTemplateID, -1, -1, -1, null, null, lstToSearch).Any();
- return lstMobileDocuments.Any();
- }
- private void WriteImportResult(FileSave fs, string errorDescription)
- {
- StringBuilder result = new StringBuilder();
- result.Append(fs.CreateDate + ";");
- result.Append(sp.FolderInput + "\\" + fs.FileName + ";");
- result.Append(fs.NewFile.ImportedProcessCode + ";");
- result.Append(fs.NewFile.DocStatus + ";");
- result.Append(((fs.IsValid && fs.IsImported) ? sp.FolderBackup : sp.FolderError) + "\\" + DateTime.Now.ToString("yyyyMMdd"));
- result.Append(errorDescription);
- FileImportResult.List.Add(result.ToString());
- }
- //private static void WriteErrorEvent(string _eventdesc)
- //{
- // string sSource;
- // string sLog;
- // string sEvent;
- // sSource = "PaperSoft Capture Importer Service";
- // sLog = "Application";
- // sEvent = _eventdesc;
- // if (!EventLog.SourceExists(sSource))
- // EventLog.CreateEventSource(sSource, sLog);
- // EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error);
- //}
- public string currentOperationID { get; set; }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement