Advertisement
Guest User

dsdsd

a guest
Jun 27th, 2016
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 44.33 KB | None | 0 0
  1. using Ionic.Zip;
  2. using PaperSoft.Mobile.BusinessService.ViewModel.Operations.EForm;
  3. using PaperSoftBusiness;
  4. using PaperSoftClassification;
  5. using PaperSoftData;
  6. using PaperSoftDocumentImporterLibrary.Helpers;
  7. using PaperSoftDocumentImporterLibrary.Mobile;
  8. using PaperSoftKernelAPI.Entities.Operations.EForm;
  9. using PaperSoftKernelAPI.Services.Factories;
  10. using PaperSoftSuportAPI.PapersoftHelperAPI;
  11. using PaperSoftTemplates;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Drawing;
  15. using System.Drawing.Imaging;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Net;
  19. using System.Runtime.Serialization.Json;
  20. using System.ServiceModel;
  21. using System.Text;
  22. using System.Threading.Tasks;
  23. using System.Windows.Forms;
  24. using System.Security.Cryptography.X509Certificates;
  25. using Org.BouncyCastle.Bcpg.OpenPgp;
  26. using Org.BouncyCastle.Crypto;
  27. using Org.BouncyCastle.Crypto.Parameters;
  28. using Org.BouncyCastle.Math;
  29. using Org.BouncyCastle.OpenSsl;
  30. using Org.BouncyCastle.Security;
  31. using Org.BouncyCastle.Utilities.IO;
  32. using System.Security.Cryptography;
  33. using System.Diagnostics;
  34. using RestSharp;
  35. using PaperSoft.MobileBaseService;
  36.  
  37. namespace PaperSoftDocumentImporterLibrary
  38. {
  39.     public class ImportMobileFileToPps
  40.     {
  41.         private ServiceParameters sp;
  42.  
  43.         public List<PpsEformImporterViewModel> ListPpsOpEForm { get; set; }
  44.  
  45.         public ImportMobileFileToPps(ServiceParameters sParams)
  46.         {
  47.             FileImportResult.Init();
  48.             sp = sParams;
  49.         }
  50.  
  51.         #region Zip Decryption
  52.  
  53.         public void DoZipDecipher()
  54.         {
  55.  
  56.             //BasicHttpBinding binding = new BasicHttpBinding();
  57.             //EndpointAddress address = new EndpointAddress(sp.PpsVMEndPoint);
  58.             // PpsVMServiceReference.ServiceClient service = new PpsVMServiceReference.ServiceClient();//binding, address);
  59.             // var a = service.GetOperationEForm(ObjectId.Parse("55cc5d41005f7215f4214862"));
  60.  
  61.             List<FileInfo> lstFileDecipher = Helpers.Helpers.GetDirectoryFiles(sp.FolderInput, System.IO.SearchOption.TopDirectoryOnly, "*.PGP");
  62.             List<FileInfo> lstFileDecipherProcessed = new List<FileInfo>();
  63.  
  64.             foreach (FileInfo fi in lstFileDecipher)
  65.             {
  66.                 try
  67.                 {
  68.                     string operationId = fi.Name.Split('_')[0]; //operationId
  69.  
  70.                     X509Certificate2 cert = new X509Certificate2(sp.CertificateFilePath, sp.CertificateFilePassword, X509KeyStorageFlags.Exportable);
  71.                     //X509Certificate2 cert = GetCertificateFromLocalMachine(sp.CertificateSerialNumber);
  72.  
  73.                     AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private;
  74.                     using (Stream f = File.OpenRead(fi.FullName))
  75.                     {
  76.                         Decrypt(f, fi.Directory + "\\" + fi.Name.Replace(".PGP", ""), privateKey);
  77.                     }
  78.                     GC.Collect();
  79.  
  80.                     lstFileDecipherProcessed.Add(fi);
  81.                 }
  82.                 catch (Exception e)
  83.                 {
  84.                     MoveToFolder(fi, sp.FolderError);
  85.                     //throw e;
  86.                 }
  87.             }
  88.  
  89.             //To Delete Cyphered Files
  90.             foreach (FileInfo fi in lstFileDecipherProcessed)//lstFileDecipher)
  91.             {
  92.                 File.Delete(fi.FullName);
  93.             }
  94.             GC.Collect();
  95.         }
  96.  
  97.         private void MoveToFolder(FileInfo fs, string pDestinationFolder)
  98.         {
  99.             try
  100.             {
  101.                 string destFolder = Path.Combine(pDestinationFolder, DateTime.Now.ToString("yyyyMMdd"));
  102.                 DirectoryInfo di = new DirectoryInfo(destFolder);
  103.  
  104.                 if (!di.Exists)
  105.                     di.Create();
  106.  
  107.                 int i = 1;
  108.                 string destPath = Path.Combine(destFolder, fs.Name);
  109.                 FileInfo fDest = new FileInfo(destPath);
  110.  
  111.                 while (fDest.Exists)
  112.                 {
  113.                     // infinite loop protection
  114.                     if (i > 15)
  115.                         throw new Exception("Unable to get new filename. Original destPath: " + destPath);
  116.  
  117.                     fDest = new FileInfo(Path.Combine(fDest.DirectoryName,
  118.                                                         Path.GetFileNameWithoutExtension(fDest.Name) + "(" + i++ + ")" + fDest.Extension));
  119.                 }
  120.  
  121.                 (new FileInfo(fs.FullName)).MoveTo(fDest.FullName);
  122.             }
  123.             catch (Exception ex)
  124.             {
  125.                 //FileImportResult.List.Add(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorMovingFile) + " FILE: " + fs.FileName + " Stack:" + ex.ToString());
  126.             }
  127.         }
  128.  
  129.         public static void Decrypt(Stream input, string outputpath, AsymmetricKeyParameter privateKeyPath)
  130.         {
  131.             input = PgpUtilities.GetDecoderStream(input);
  132.             try
  133.             {
  134.                 PgpObjectFactory pgpObjF = new PgpObjectFactory(input);
  135.                 PgpEncryptedDataList enc;
  136.                 PgpObject obj = pgpObjF.NextPgpObject();
  137.                 if (obj is PgpEncryptedDataList)
  138.                 {
  139.                     enc = (PgpEncryptedDataList)obj;
  140.                 }
  141.                 else
  142.                 {
  143.                     enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
  144.                 }
  145.  
  146.                 var akp = new AsymmetricKeyParameter(true);
  147.  
  148.                 PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast<PgpPublicKeyEncryptedData>().First();
  149.  
  150.                 PgpPrivateKey privKey = new PgpPrivateKey(privateKeyPath, pbe.KeyId);
  151.  
  152.                 Stream clear;
  153.                 clear = pbe.GetDataStream(privKey);
  154.                 PgpObjectFactory plainFact = new PgpObjectFactory(clear);
  155.                 PgpObject message = plainFact.NextPgpObject();
  156.                 if (message is PgpCompressedData)
  157.                 {
  158.                     PgpCompressedData cData = (PgpCompressedData)message;
  159.                     Stream compDataIn = cData.GetDataStream();
  160.                     PgpObjectFactory o = new PgpObjectFactory(compDataIn);
  161.                     message = o.NextPgpObject();
  162.                     if (message is PgpOnePassSignatureList)
  163.                     {
  164.                         message = o.NextPgpObject();
  165.                         PgpLiteralData Ld = null;
  166.                         Ld = (PgpLiteralData)message;
  167.                         Stream output = File.Create(outputpath + "\\" + Ld.FileName);
  168.                         Stream unc = Ld.GetInputStream();
  169.                         Streams.PipeAll(unc, output);
  170.                     }
  171.                     else
  172.                     {
  173.                         PgpLiteralData Ld = null;
  174.                         Ld = (PgpLiteralData)message;
  175.                         //Stream output = File.Create(outputpath + "\\" + Ld.FileName);
  176.                         Stream output = File.Create(outputpath);
  177.                         Stream unc = Ld.GetInputStream();
  178.                         Streams.PipeAll(unc, output);
  179.                     }
  180.                 }
  181.             }
  182.             catch (Exception e)
  183.             {
  184.                 throw new Exception(e.Message);
  185.             }
  186.         }
  187.  
  188.         private static X509Certificate2 GetCertificateFromLocalMachine(string certName)
  189.         {
  190.  
  191.             // Get the certificate store for the current user.
  192.             X509Store store = new X509Store(StoreLocation.LocalMachine);
  193.             try
  194.             {
  195.                 store.Open(OpenFlags.ReadOnly);
  196.  
  197.                 // Place all certificates in an X509Certificate2Collection object.
  198.                 X509Certificate2Collection certCollection = store.Certificates;
  199.                 // If using a certificate with a trusted root you do not need to FindByTimeValid, instead:
  200.                 // currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true);
  201.                 X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
  202.                 foreach (X509Certificate2 mCert in currentCerts)
  203.                 {
  204.                     if (string.Compare(certName, mCert.SerialNumber.ToLower(), StringComparison.InvariantCulture) == 0)
  205.                     {
  206.                         return mCert;
  207.                     }
  208.                     //TODO's
  209.                 }
  210.                 return null;
  211.             }
  212.             finally
  213.             {
  214.                 store.Close();
  215.             }
  216.  
  217.         }
  218.  
  219.         private void DecipherFile(FileInfo pCipheredFile, string pEncryptionKey)
  220.         {
  221.             string unCipheredFileName = pCipheredFile.Directory.FullName + "\\" + pCipheredFile.Name + ".zip";
  222.             try
  223.             {
  224.                 byte[] cipheredBytes = System.IO.File.ReadAllBytes(pCipheredFile.FullName);
  225.                 //uncipher here
  226.  
  227.  
  228.                 Stream stream = new MemoryStream(cipheredBytes);
  229.                 //full path example \\172.16.3.39\c$\inetpub\wwwroot\PpsSubmissionWSXpandIT\Uploads\ToTest\3bff0cd4-b514-4016-8708-fc49d63cc2c8-0006_pps.VM1.ZIP
  230.                 using (FileStream fileStream = File.Create(unCipheredFileName, (int)stream.Length))
  231.                 {
  232.                     byte[] bytesInStream = new byte[stream.Length];
  233.                     stream.Read(bytesInStream, 0, bytesInStream.Length);
  234.                     fileStream.Write(bytesInStream, 0, bytesInStream.Length);
  235.                 }
  236.             }
  237.             catch (Exception e)
  238.             {
  239.                 File.Delete(unCipheredFileName);
  240.             }
  241.         }
  242.  
  243.         #endregion
  244.  
  245.         #region Zip Importation
  246.  
  247.         public List<string> DoFileImport()
  248.         {
  249.             ListPpsOpEForm = new List<PpsEformImporterViewModel>();
  250.  
  251.             DateTime currentDate = DateTime.UtcNow;
  252.  
  253.             try
  254.             {
  255.                 CheckAppRequirements();
  256.  
  257.                 List<FileInfo> lstFiles = Helpers.Helpers.GetDirectoryFiles(sp.FolderInput, System.IO.SearchOption.TopDirectoryOnly, "*.ZIP");
  258.  
  259.                 foreach (FileInfo fi in lstFiles)
  260.                 {
  261.                     ImportFile(fi, currentDate);
  262.                 }
  263.             }
  264.             catch (Exception ex)
  265.             {
  266.                 if (ex.Message.StartsWith("x1"))
  267.                     FileImportResult.List.Add(ex.Message);
  268.                 else
  269.                     FileImportResult.List.Add(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorGeneralError) + " (" + ex.ToString() + ")");
  270.             }
  271.  
  272.             return FileImportResult.List;
  273.         }
  274.  
  275.         private void CheckAppRequirements()
  276.         {
  277.             DirectoryInfo dinfo = null;
  278.  
  279.             try
  280.             {
  281.                 dinfo = new DirectoryInfo(sp.FolderBackup);
  282.                 if (!dinfo.Exists)
  283.                     dinfo.Create();
  284.  
  285.                 dinfo = new DirectoryInfo(sp.FolderError);
  286.                 if (!dinfo.Exists)
  287.                     dinfo.Create();
  288.  
  289.                 dinfo = new DirectoryInfo(sp.FolderInput);
  290.                 if (!dinfo.Exists)
  291.                     dinfo.Create();
  292.             }
  293.             catch (Exception ex)
  294.             {
  295.                 throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorFolderAccess) + " for Folder: " + sp.FolderInput, ex);
  296.             }
  297.         }
  298.  
  299.         public void ImportFile(FileInfo pFile, DateTime pCurrentDate)//, int statusID, EForm pEForm, bool pOneCoverPerDay)
  300.         {
  301.             FileSave fileSave = new FileSave();
  302.             string exceptionDetail = string.Empty;
  303.             bool flag = false;
  304.  
  305.             try
  306.             {
  307.                 fileSave.CurrentDate = pCurrentDate;
  308.                 fileSave.CreateDate = pFile.CreationTime;
  309.                 fileSave.Extension = pFile.Extension;
  310.                 fileSave.FileName = pFile.Name;
  311.                 fileSave.FullName = pFile.FullName;
  312.                 fileSave.IsImported = false;
  313.                 fileSave.IsDuplicated = false;
  314.                 fileSave.IsValid = false;
  315.                 fileSave = LoadFile(fileSave);
  316.  
  317.                 if (fileSave.IsValid)
  318.                 {
  319.                     CreateFiles(fileSave, pCurrentDate);// sp.kwLote, sp.OneCoverPerDay, sp.CoverDocLenght);
  320.                 }
  321.             }
  322.             catch (Exception ex)
  323.             {
  324.                 EventLogger.WriteErrorEvent(ex.Message);
  325.                 if (ex.Message.StartsWith("Process ID Configurated "))
  326.                     flag = true;
  327.  
  328.                 if (ex.Message.StartsWith("x1"))
  329.                 {
  330.                     //FileImportResult.List.Add(ex.Message);
  331.                     exceptionDetail = ex.Message;
  332.                 }
  333.                 else
  334.                     // FileImportResult.List.Add(Helpers.GetDescription(Results.ErrorResults.ErrorProcessingFile) + " (" + ex.ToString() + ")");
  335.                     exceptionDetail = Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorProcessingFile) + " (" + ex.ToString() + ")";
  336.             }
  337.             finally
  338.             {
  339.                 if (!flag)
  340.                 {
  341.                     MoveToFolder(fileSave);
  342.                     WriteImportResult(fileSave, exceptionDetail);
  343.                 }
  344.             }
  345.         }
  346.  
  347.         private void MoveToFolder(FileSave fs)
  348.         {
  349.             try
  350.             {
  351.                 string destFolder = string.Empty;
  352.  
  353.                 if (fs.IsValid && fs.IsImported)
  354.                     destFolder = Path.Combine(sp.FolderBackup, DateTime.Now.ToString("yyyyMMdd"));
  355.                 else if (fs.IsValid && fs.IsDuplicated)
  356.                     destFolder = Path.Combine(sp.FolderError, DateTime.Now.ToString("yyyyMMdd"), "TRANSFER_ERRORS");
  357.                 else
  358.                     destFolder = Path.Combine(sp.FolderError, DateTime.Now.ToString("yyyyMMdd"));
  359.  
  360.                 //string destFolder = Path.Combine((fs.IsValid && fs.IsImported) ? sp.FolderBackup : sp.FolderError, DateTime.Now.ToString("yyyyMMdd"));
  361.  
  362.                 DirectoryInfo di = new DirectoryInfo(destFolder);
  363.  
  364.                 if (!di.Exists)
  365.                     di.Create();
  366.  
  367.                 int i = 1;
  368.                 string destPath = Path.Combine(destFolder, fs.FileName);
  369.                 FileInfo fDest = new FileInfo(destPath);
  370.  
  371.                 while (fDest.Exists)
  372.                 {
  373.                     // infinite loop protection
  374.                     if (i > 15)
  375.                         throw new Exception("Unable to get new filename. Original destPath: " + destPath);
  376.  
  377.                     fDest = new FileInfo(Path.Combine(fDest.DirectoryName,
  378.                                                         Path.GetFileNameWithoutExtension(fDest.Name) + "(" + i++ + ")" + fDest.Extension));
  379.                 }
  380.  
  381.                 (new FileInfo(fs.FullName)).MoveTo(fDest.FullName);
  382.             }
  383.             catch (Exception ex)
  384.             {
  385.                 FileImportResult.List.Add(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorMovingFile) + " FILE: " + fs.FileName + " Stack:" + ex.ToString());
  386.             }
  387.         }
  388.  
  389.         private void MergeImages(ref FileSave zipFile, string pProcessTag, short pTemplateID, string pConstr, string pFormTemplateName)
  390.         {
  391.             List<Image> imgList = new List<Image>();
  392.             byte[] content = null;
  393.  
  394.             //TODO: FAZER MERGE DAS IMAGENS (signature, Image ou FingerPrint com o formulário)
  395.  
  396.             byte[] lstDocPdf = null;
  397.  
  398.  
  399.             var lstDocs = zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "JPEG").Where(m => m.FileName.StartsWith("FORM"))
  400.                                                .OrderBy(n => n.FileName).ToList();
  401.  
  402.  
  403.             Dictionary<string, byte[]> pFieldImages = new Dictionary<string, byte[]>();
  404.  
  405.             var lstSignature = zipFile.ZipContents.Where(m => m.FileName.StartsWith("SIGNATURE"))
  406.                                            .OrderBy(n => n.FileName).ToList();
  407.  
  408.             if (lstSignature.Count > 0)
  409.             {
  410.                 foreach (var sig in lstSignature)
  411.                 {
  412.                     pFieldImages.Add(sig.FileName.Split('.').FirstOrDefault(), sig.File);
  413.                 }
  414.             }
  415.  
  416.             if (pFormTemplateName != string.Empty)
  417.                 lstDocPdf = Mobile.PdfBuilder.BuildDocumentFormVodaCom(zipFile.NewFile.JsonMetadata, pFieldImages, pFormTemplateName, pTemplateID, pConstr, sp);
  418.             else if (zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "PDF").Where(m => m.FileName.StartsWith("FORM"))
  419.                                    .OrderBy(n => n.FileName).FirstOrDefault() != null)
  420.                 lstDocPdf = zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "PDF").Where(m => m.FileName.StartsWith("FORM"))
  421.                                    .OrderBy(n => n.FileName).FirstOrDefault().File;
  422.  
  423.             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")
  424.                               .OrderBy(n => n.FileName).ToList();
  425.             //&& !m.FileName.Equals("IMAGE_11_1") && !m.FileName.Equals("IMAGE_23_1"
  426.  
  427.             lstDocs.AddRange(lstImages);
  428.             content = lstDocPdf;
  429.             if (lstDocs.Any())
  430.             {
  431.                 if (content == null)
  432.                 {
  433.                     content = PdfFunctions.ImageToPdf(lstDocs[0].File);
  434.                     for (int i = 1; i < lstDocs.Count; i++)
  435.                     {
  436.                         byte[] tempBolb = new MemoryStream(lstDocs[i].File).ToArray();
  437.                         content = AppendImageToPdf(content, tempBolb, new Point(0, 0));
  438.                     }
  439.                 }
  440.                 else
  441.                 {
  442.                     for (int i = 0; i < lstDocs.Count; i++)
  443.                     {
  444.                         byte[] tempBolb = new MemoryStream(lstDocs[i].File).ToArray();
  445.                         content = AppendImageToPdf(content, tempBolb, new Point(0, 0));
  446.                     }
  447.                 }
  448.             }
  449.  
  450.  
  451.             //if (lstDocPdf != null)
  452.             //    content = PaperSoftSuportAPI.PapersoftHelperAPI.PdfFunctions.CombinePdf(lstDocPdf, content);
  453.  
  454.  
  455.             //string fileName = Path.Combine(Application.StartupPath, @"PdfFormTemplates\" + zipFile.FileName + ".pdf");
  456.  
  457.             //using (FileStream _FileStream = new FileStream(fileName, System.IO.FileMode.Create, FileAccess.Write))
  458.             //{
  459.             //    _FileStream.Write(content, 0, content.Length);
  460.             //    _FileStream.Close();
  461.             //}
  462.  
  463.             GC.Collect();
  464.             zipFile.NewFile.File = content;
  465.             zipFile.NewFile.Extension = ".pdf";
  466.             zipFile.NewFile.FileName = Path.GetFileNameWithoutExtension(zipFile.NewFile.FileName) + zipFile.NewFile.Extension;
  467.         }
  468.  
  469.         public static byte[] AppendImageToPdf(byte[] pdf, byte[] img, Point position, double scale = 1)
  470.         {
  471.             using (System.IO.MemoryStream msPdf = new System.IO.MemoryStream(pdf))
  472.             {
  473.                 using (System.IO.MemoryStream msImg = new System.IO.MemoryStream(img))
  474.                 {
  475.                     System.Drawing.Image image = System.Drawing.Image.FromStream(msImg);
  476.                     PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(msPdf);
  477.                     PdfSharp.Pdf.PdfPage page = document.AddPage();
  478.                     //PdfSharp.Pdf.PdfPage page = document.Pages[0];
  479.                     PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page);
  480.                     PdfSharp.Drawing.XImage ximg = PdfSharp.Drawing.XImage.FromGdiPlusImage(image);
  481.                     double imageWidth = ximg.Width;
  482.                     double imageHeigth = ximg.Height;
  483.                     if (imageWidth > page.Width)
  484.                     {
  485.                         imageHeigth = (imageHeigth / imageWidth) * page.Width;
  486.                         imageWidth = page.Width;
  487.                     }
  488.                     else if (imageHeigth > page.Height)
  489.                     {
  490.                         imageWidth = (imageWidth / imageHeigth) * page.Height;
  491.                         imageHeigth = page.Height;
  492.  
  493.                     }
  494.                     gfx.DrawImage(
  495.                         ximg,
  496.                         position.X,
  497.                         position.Y,
  498.                         imageWidth * scale,
  499.                         imageHeigth * scale
  500.                     );
  501.  
  502.                     using (System.IO.MemoryStream msFinal = new System.IO.MemoryStream())
  503.                     {
  504.                         document.Save(msFinal);
  505.                         return msFinal.ToArray();
  506.                     }
  507.                 }
  508.             }
  509.         }
  510.  
  511.         private FileSave LoadFile(FileSave fileToImport)
  512.         {
  513.             if (fileToImport.Extension.ToUpper() == ".ZIP")
  514.             {
  515.                 fileToImport.IsZip = true;
  516.                 fileToImport.ZipContents = new List<FileSave>();
  517.                 fileToImport.ZipContents = UnzipFiles(fileToImport);
  518.                 ValidateZipFiles(fileToImport);
  519.  
  520.                 fileToImport.NewFile = new MobileFile();
  521.                 fileToImport.NewFile.CreateDate = fileToImport.CreateDate;
  522.                 fileToImport.NewFile.JsonMetadata = LoadAndCheckMetadata(fileToImport);
  523.                 fileToImport.NewFile.JsonFormErrors = LoadAndCheckFormErrors(fileToImport);
  524.                 fileToImport.NewFile.FileName = Path.GetFileNameWithoutExtension(fileToImport.FileName) + fileToImport.NewFile.Extension;
  525.                 fileToImport.IsValid = true;
  526.             }
  527.             else
  528.             {
  529.                 throw new Exception("Invalid extension to import");
  530.             }
  531.  
  532.             return fileToImport;
  533.         }
  534.  
  535.         private PpsEformViewModel LoadAndCheckMetadata(FileSave zipFile)
  536.         {
  537.             string jsonData = string.Empty;
  538.             PpsEformViewModel metadata = null;// new JsonMetadata();
  539.  
  540.             try
  541.             {
  542.                 var jsonFile = zipFile.ZipContents.Where(n => n.Extension.ToUpper() == "JSON").FirstOrDefault();
  543.  
  544.                 using (StreamReader sr = new StreamReader(new MemoryStream(jsonFile.File)))
  545.                 {
  546.                     jsonData = sr.ReadToEnd();
  547.                 }
  548.  
  549.                 if (!string.IsNullOrEmpty(jsonData))
  550.                 {
  551.                     // metadata = Helpers.GetJsonData<PpsEformViewModel>(jsonData);
  552.  
  553.                     var bytes = Encoding.UTF8.GetBytes(jsonData);
  554.                     using (var stream = new MemoryStream(bytes))
  555.                     {
  556.                         var serializer = new DataContractJsonSerializer(typeof(PpsEformViewModel));
  557.                         metadata = (PpsEformViewModel)serializer.ReadObject(stream);
  558.                     }
  559.                 }
  560.                 else
  561.                     throw new Exception("found empty metadata ");
  562.  
  563.  
  564.             }
  565.             catch (Exception ex)
  566.             {
  567.                 throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorGettingMetadata) + "(" + ex.Message + ")", ex);
  568.             }
  569.  
  570.             return metadata;
  571.         }
  572.  
  573.         private FormErrors LoadAndCheckFormErrors(FileSave zipFile)
  574.         {
  575.             string jsonData = string.Empty;
  576.             FormErrors metadata = new FormErrors();
  577.  
  578.             try
  579.             {
  580.                 var jsonFile = zipFile.ZipContents.Where(n => n.FileName == "ERROS.TXT").FirstOrDefault();
  581.  
  582.                 using (StreamReader sr = new StreamReader(new MemoryStream(jsonFile.File)))
  583.                 {
  584.                     jsonData = sr.ReadToEnd();
  585.                 }
  586.  
  587.                 if (!string.IsNullOrEmpty(jsonData) && jsonData != "{}")
  588.                 {
  589.                     metadata = FormErrors.FromJson(jsonData);
  590.                 }
  591.             }
  592.             catch (Exception ex)
  593.             {
  594.                 //throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorGettingJsonErrors) + "(" + ex.Message + ")", ex);
  595.             }
  596.  
  597.             return metadata;
  598.         }
  599.  
  600.         private bool ValidateZipFiles(FileSave zipFile)
  601.         {
  602.             bool isValid = false;
  603.             bool hasData = false;
  604.             bool hasForm = false;
  605.             //bool hasInvalidContent = false;
  606.  
  607.             if (zipFile.ZipContents != null)
  608.             {
  609.                 foreach (FileSave fs in zipFile.ZipContents)
  610.                 {
  611.                     if (Path.GetFileNameWithoutExtension(fs.FileName.ToUpper()).StartsWith("DATA") && fs.Extension.ToUpper() == "JSON")
  612.                         hasData = true;
  613.                     //else if (Path.GetFileNameWithoutExtension(fs.FileName.ToUpper()).StartsWith("FORM")
  614.                     //     && fs.Extension.ToUpper() == "JPEG")
  615.                     hasForm = true;
  616.                     //else
  617.                     //    hasInvalidContent = true;
  618.                 }
  619.  
  620.                 if (hasData && hasForm)// && !hasInvalidContent)
  621.                     isValid = true;
  622.                 else
  623.                     throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorInvalidZipContent));
  624.             }
  625.  
  626.             return isValid;
  627.         }
  628.  
  629.         private List<FileSave> UnzipFiles(FileSave fi)
  630.         {
  631.             var lstFilesToImport = new List<FileSave>();
  632.  
  633.             try
  634.             {
  635.                 MemoryStream msZip = new MemoryStream(System.IO.File.ReadAllBytes(fi.FullName));
  636.  
  637.                 using (ZipFile zFile = ZipFile.Read(msZip))
  638.                 {
  639.                     foreach (ZipEntry ze in zFile)
  640.                     {
  641.                         MemoryStream ms = new MemoryStream();
  642.                         ze.Extract(ms);
  643.  
  644.                         var fileSave = new FileSave()
  645.                         {
  646.                             CreateDate = DateTime.Now,
  647.                             Extension = ze.FileName.Split('.')[ze.FileName.Split('.').Length - 1],
  648.                             File = ms.ToArray(),
  649.                             FileName = ze.FileName,
  650.                             IsValid = true,
  651.                             IsImported = false,
  652.                             TotalPages = Helpers.Helpers.CountPages(ms.ToArray(), ze.FileName.Split('.')[ze.FileName.Split('.').Length - 1]),
  653.                         };
  654.                         lstFilesToImport.Add(fileSave);
  655.                     }
  656.                 }
  657.             }
  658.             catch (Exception ex)
  659.             {
  660.                 throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorExtractingZipFiles) + " FILE: " + fi.FileName + " (" + ex.Message + ")");
  661.             }
  662.  
  663.             return (lstFilesToImport != null && lstFilesToImport.Count > 0) ? lstFilesToImport.OrderBy(n => n.FileName).ToList() : lstFilesToImport;
  664.         }
  665.  
  666.         private PpsEformImporterViewModel GetOperationMongo(string pServiceUrl, string pOperationId)
  667.         {
  668.                 PpsEformImporterViewModel eformOperation = null;
  669.                 RestClient restClient = new RestClient(pServiceUrl + pOperationId);
  670.  
  671.                 var request = new RestRequest(RestSharp.Method.GET);
  672.                 request.RequestFormat = DataFormat.Json;
  673.  
  674.                 var resp = restClient.Execute(request);
  675.  
  676.                 if (resp.StatusCode != HttpStatusCode.OK) {
  677.                     throw new Exception(string.Format("Unable To {0} Connect to DB Mongo for operationID: {1}", pServiceUrl, pOperationId));
  678.                 }
  679.                 try
  680.                 {
  681.                    eformOperation = (PpsEformImporterViewModel)Helpers.Helpers.ConvertJsonToObject<PpsEformImporterViewModel>(resp.Content);
  682.                 }
  683.                 catch (Exception e)
  684.                 {
  685.                     throw new Exception(string.Format("Unable To serialize operation: {0}", e.Message));
  686.                 }
  687.                 return eformOperation;
  688.         }
  689.  
  690.         private void CreateFiles(FileSave fi, DateTime currentDate)// string pLoteKeyword, bool pOneCoverPerDay, int pCoverDocLenght)
  691.         {
  692.             if (fi.IsValid)
  693.             {
  694.                 //PpsOpEForm eformOperation = null;
  695.                 PpsEformImporterViewModel eformOperation = null;
  696.                 string currentOperationID = string.Empty;
  697.                
  698.                 try
  699.                 {
  700.                     currentOperationID = fi.NewFile.JsonMetadata.ID;
  701.  
  702.                     //MARTELADA VMDRC
  703.                     if (currentOperationID == "5679724a91169012887f0f66" || currentOperationID == "5679724a91169012887f0f67")
  704.                         currentOperationID = "5679724a91169012887f0f67";
  705.  
  706.                     if (currentOperationID == "5679724a91169012887f0f6a" || currentOperationID == "5679724a91169012887f0f6b")
  707.                         currentOperationID = "5679724a91169012887f0f6b";
  708.  
  709.                     if (ListPpsOpEForm.Where(n => n.ID == currentOperationID.ToString()).Any())
  710.                         eformOperation = ListPpsOpEForm.Where(n => n.ID == currentOperationID.ToString()).FirstOrDefault();
  711.                     else
  712.                     {                        
  713.                         eformOperation = GetOperationMongo(sp.PpsMobileBusinessEndPoint, currentOperationID);
  714.  
  715.                         ListPpsOpEForm.Add(eformOperation);
  716.                     }
  717.                 }
  718.                 catch (Exception e)
  719.                 {                  
  720.                     throw new Exception("Unable To Connect to DB Mongo for operationID:" + fi.NewFile.JsonMetadata.ID.ToString());
  721.                 }
  722.                
  723.                 string cipherConString = eformOperation.PapersoftAddress.Database.ConnectionString;
  724.  
  725.                 string conString = SecureDataTransfer.DecryptText(cipherConString, PpsMobileBaseService.ENCRYPTION_SALT);
  726.  
  727.                 int custID = eformOperation.PapersoftAddress.ClientID;
  728.                 Guid processID = eformOperation.PapersoftAddress.ProcessID;
  729.  
  730.                 ProcessTemplate procInProcess = sp.ProcessTemplateList.Where(n => n.ProcessId == processID).FirstOrDefault();
  731.  
  732.                 if (procInProcess == null || (procInProcess != null && processID != procInProcess.ProcessId))
  733.                     throw new Exception("Process ID Configurated is different Between JSON File and DBMongo " + processID);
  734.  
  735.                 PsCustomerProcess process = PsCustomerProcess.ListCustomerProcesses(conString, custID)
  736.                                                 .Where(n => n.PSCUST_PROCESS_ID == processID).FirstOrDefault();
  737.  
  738.                 short templateID = IndexTemplate.GetIndexTemplateByProcess(conString, process.PSCUST_PROCESS_ID).IXT_ID;
  739.  
  740.                 fi.NewFile.ImportedProcessCode = process.PSCUST_PROCESS_CODE;
  741.                 fi.NewFile.DocStatus = procInProcess.DocStatusDoc;
  742.  
  743.                 IndexTemplate template = IndexTemplate.GetIndexTemplateByProcess(conString, processID);
  744.  
  745.                 bool existZip = CheckIfDocumentExist(conString, templateID, custID, fi.NewFile.FileName);
  746.  
  747.                 if (existZip)
  748.                     fi.IsDuplicated = true;
  749.                 else
  750.                 {
  751.                     #region Old Code
  752.  
  753.                     ////TODO: VODACOM
  754.                     //ObjectId eformID_NewSIM = ObjectId.Parse("55cc5d41005f7215f4214862");
  755.                     //ObjectId eformID_NewSIMWitness = ObjectId.Parse("56167f0b99de4b3340575227");
  756.                     //ObjectId eformID_PreReg = ObjectId.Parse("55cc5c1e005f7215f421472b");
  757.                     //ObjectId eformID_PreRegWitness = ObjectId.Parse("56167f0b99de4b3340575228");
  758.                     //ObjectId eformID_Bank = ObjectId.Parse("55afdb8899de4b00bcd83a3c");
  759.                     //ObjectId eformID_Telco = ObjectId.Parse("55c8c02a99de4b11b8a230e3");
  760.  
  761.                     ////TODO: DOXIS
  762.                     //ObjectId eFormId_DoxisBank = ObjectId.Parse("56b334c39116903cf00e58f6");
  763.                     //ObjectId eFormId_DoxisExpense = ObjectId.Parse("563ccb4f96e33d364865dc98");
  764.  
  765.                     ////TODO: VM CONGO
  766.                     //ObjectId eFormId_CongoNewSubscriber = ObjectId.Parse("563ced5996e33d2d64205cd5");
  767.                     //ObjectId eFormId_CongoExistingSubscriber = ObjectId.Parse("563ced5996e33d2d64205cd6");
  768.  
  769.                     //string registerType = string.Empty;
  770.                     //if (eformOperation.Id.Equals(eformID_NewSIM) || eformOperation.Id.Equals(eformID_NewSIMWitness))
  771.                     //    registerType = "1";
  772.                     //else if (eformOperation.Id.Equals(eformID_PreReg) || eformOperation.Id.Equals(eformID_PreRegWitness))
  773.                     //    registerType = "2";
  774.  
  775.                     //string formTemplateName = (eformOperation.Id.Equals(eformID_NewSIM) || eformOperation.Id.Equals(eformID_PreReg))
  776.                     //    ? "VODACOM_FORM.PDF" : "VODACOM_WITNESS_FORM.PDF";
  777.  
  778.                     //if (eformOperation.Id.Equals(eformID_Bank) || eformOperation.Id.Equals(eFormId_DoxisContract))
  779.                     //{
  780.                     //    formTemplateName = "BANK_FORM.pdf";
  781.                     //    registerType = "3";
  782.                     //}
  783.                     //else if (eformOperation.Id.Equals(eformID_Telco))
  784.                     //{
  785.                     //    formTemplateName = "TELCO_FORM.pdf";
  786.                     //    registerType = "3";
  787.                     //}
  788.                     #endregion
  789.  
  790.                     MergeImages(ref fi, process.PSCUST_PROCESS_TAG, templateID, conString, sp.FormTemplatePDFName);
  791.  
  792.                     #region Old Code
  793.                     //if (eformOperation.Id.Equals(eFormId_CongoExistingSubscriber))
  794.                     //{
  795.                     //    foreach (var fieldGroup in fi.NewFile.JsonMetadata.FieldGroups)
  796.                     //    {
  797.                     //        var field = fieldGroup.TemplateFields.Where(n => n.Keyword.ToUpper() == "kwMobileNr".ToUpper()).FirstOrDefault();
  798.  
  799.                     //        IndexTemplateField templateField = IndexTemplateField.ListIndexTemplatesFieldsWithKeyword(conString, templateID)
  800.                     //        .FirstOrDefault(f => f.FIELD_KEYWORD.ToUpper() == field.Keyword.ToUpper());
  801.  
  802.                     //        List<PsDocumentClassification> lstFields = new List<PsDocumentClassification>();
  803.                     //        lstFields.Add(new PsDocumentClassification()
  804.                     //        {
  805.                     //            IXTF_ORDER = templateField.IXTF_ORDER,
  806.                     //            VALUE = field.Value.FirstOrDefault().Trim()
  807.                     //        });
  808.  
  809.                     //        List<PsDocument> lstDocs = PsDocument.SearchDocument(conString, PsDocument.DocumentType.Document, templateID, process.CUST_ID, -1, -1, null, null, lstFields);
  810.  
  811.                     //        if (lstDocs == null || !lstDocs.Any())
  812.                     //            throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorDocumentNotExist));
  813.  
  814.  
  815.                     //        PsDocument doc = lstDocs.FirstOrDefault();
  816.                     //        doc.CLASSIFICATION = PsDocumentClassification.LoadPsDocumentClassification(conString, doc.RDOC_ID);
  817.  
  818.                     //        doc.LoadPsDocumentBlob();
  819.                     //        doc.LstPsDocumentBlob = null;
  820.  
  821.                     //        if (doc.RDOC_STATUS_ID == 14003)
  822.                     //        {
  823.                     //            PsDocumentBlob docBlob = new PsDocumentBlob(conString);
  824.                     //            docBlob.RDOC_ID = doc.RDOC_ID;
  825.                     //            docBlob.RDCC_N_PAGE = Helpers.Helpers.CountPages(fi.NewFile.File, "pdf");
  826.                     //            docBlob.RDCC_FILENAME = fi.NewFile.FileName;
  827.                     //            docBlob.RDCC_BLOB = fi.NewFile.File;
  828.                     //            docBlob.RDCC_EXT_ID = 0;
  829.                     //            docBlob.B_ATTACHMENT = 0;
  830.                     //            docBlob.RDCC_ID = PaperSoftBusiness.PsFsCode.GetCode(PaperSoftBusiness.PsFsCode.FsCodeTableName.PSREPDOCC, doc.ConStr);
  831.                     //            docBlob.DFTY_ID = doc.DFTY_ID;
  832.                     //            docBlob.DOC_FORMAT_TYPE_EXT = doc.RDOC_DEFAULT_DOCFORMAT_EXT;
  833.                     //            docBlob.CreatePsDocumentBlob();
  834.  
  835.                     //            fi.NewFile.PsDocument = doc;
  836.                     //            doc = Document.CreateDocClassification(fi.NewFile, conString, registerType);
  837.                     //            doc.RDOC_STATUS_ID = 9001;
  838.                     //            doc.UpdatePsDocument();
  839.                     //            fi.IsImported = true;
  840.                     //            fi.NewFile.PsDocument = doc;
  841.                     //        }
  842.                     //        else
  843.                     //            throw new Exception(Helpers.Helpers.GetDescription(Results.ErrorResults.ErrorDocumentNotExist));
  844.  
  845.  
  846.                     //        break;
  847.                     //    }
  848.                     //}
  849.                     //else
  850.                     //{
  851.                     #endregion
  852.  
  853.  
  854.                     PsShipping psShipping = Shipping.GetPsShipping(sp.ApplicationName, custID, " Mobile Capture - ",
  855.                                                                     process.PSCUST_PROCESS_CODE,
  856.                                                                     conString,
  857.                                                                     currentDate, sp.CoverDocLenght);
  858.  
  859.                     // Get or create cover...
  860.                     PsDocument coverDoc = Document.CreateCover("MobileCapture.UploadForm",
  861.                                                                     psShipping.ShippingDescription,
  862.                                                                     conString,
  863.                                                                     procInProcess.DocStatusCover, custID, processID,
  864.                                                                     psShipping,
  865.                                                                     template.IXT_ID, sp.OneCoverPerDay, currentDate, sp.kwLote);
  866.  
  867.                     PsDocument doc = Document.CreateDoc("MobileCapture.UploadForm", conString, procInProcess.DocStatusDoc, coverDoc, fi.NewFile);
  868.  
  869.                     fi.NewFile.PsDocument = doc;
  870.                     fi.NewFile.PsDocument = Document.CreateDocClassification(fi.NewFile, conString, sp, sp.ImportHistoricalLog);
  871.                     fi.IsImported = true;
  872.  
  873.                     #region Old Code
  874.                     //EventLogger.WriteInfoEvent("Entering Doxis");
  875.                     //if ((eformOperation.Id.Equals(eFormId_DoxisBank))) // || (eformOperation.Id.Equals(eFormId_DoxisExpense)))
  876.                     //{
  877.                     //    EventLogger.WriteInfoEvent("Loading doc blob");
  878.                     //    fi.NewFile.PsDocument.LoadPsDocumentBlob();
  879.  
  880.                     //    PsDocumentBlob documentToUpload = fi.NewFile.PsDocument.LstPsDocumentBlob.FirstOrDefault();
  881.                     //    EventLogger.WriteInfoEvent("Loading doc Metadata");
  882.                     //    Dictionary<string, string> docMetadata = new Dictionary<string, string>();
  883.                     //    var templateFields = IndexTemplateField.ListIndexTemplatesFieldsWithKeyword(conString, fi.NewFile.PsDocument.IXT_ID);
  884.                     //    fi.NewFile.PsDocument.CLASSIFICATION = PsDocumentClassification.LoadPsDocumentClassification(conString, doc.RDOC_ID);
  885.                     //    fi.NewFile.PsDocument.CLASSIFICATION.ForEach(m => docMetadata.Add(templateFields.FirstOrDefault(tf => tf.IXTF_ORDER == m.IXTF_ORDER).FIELD_KEYWORD, m.VALUE));
  886.                     //    DateTime uploadTime = DateTime.MinValue;
  887.                     //    EventLogger.WriteInfoEvent("Start Uploading to CMIS");
  888.                     //    DoxisCmisUploader.Init(sp.DoxisSecuritySettings);
  889.                     //    EventLogger.WriteInfoEvent("EFormOperation: " + eformOperation.Id);
  890.                     //    if (eformOperation.Id.Equals(eFormId_DoxisBank))
  891.                     //    {
  892.                     //        EventLogger.WriteInfoEvent("Start Uploading Contract");
  893.                     //        var totalPages = PdfFunctions.PdfPageCount(documentToUpload.RDCC_BLOB);
  894.                     //        var firstPage = PdfFunctions.SplitPdf(documentToUpload.RDCC_BLOB, 1, 1);
  895.                     //        uploadTime = DoxisCmisUploader.UploadContractDoc(sp.DoxisBankSpecification, documentToUpload.RDCC_FILENAME, documentToUpload.RDCC_BLOB, docMetadata);
  896.                     //        if (totalPages > 2)
  897.                     //        {
  898.                     //            var restOfPages = PdfFunctions.SplitPdf(documentToUpload.RDCC_BLOB, 2, totalPages);
  899.                     //            uploadTime = DoxisCmisUploader.UploadContractDoc(sp.DoxisBankSpecification, documentToUpload.RDCC_FILENAME, restOfPages, docMetadata);
  900.                     //        }
  901.                     //    }
  902.  
  903.                     //    //else if (eformOperation.Id.Equals(eFormId_DoxisExpense))
  904.                     //    //{
  905.                     //    //    EventLogger.WriteInfoEvent("Start Uploading Expense");
  906.                     //    //    uploadTime = DoxisCmisUploader.UploadExpenseDoc(sp.DoxisDocumentExpensesSpecification, documentToUpload.RDCC_FILENAME, documentToUpload.RDCC_BLOB, docMetadata);
  907.                     //    //}
  908.                     //    EventLogger.WriteInfoEvent("End Uploading to CMIS");
  909.                     //    using (PaperSoft100_TPH_BASE_ProductionEntities ctx = Helpers.Helpers.SetEntityContext(conString))
  910.                     //    {
  911.                     //        doc.LogPsDocumentOperation(ctx, 1, sp.ApplicationName.ToUpper(), "CMIS Uploaded at: " + uploadTime.ToString() + " !", doc.RDOC_USER_CREATE);
  912.                     //    }
  913.                     //}
  914.                     #endregion
  915.                 }
  916.  
  917.             }
  918.             else
  919.                 fi.IsImported = false;
  920.         }
  921.  
  922.         #endregion
  923.  
  924.         private bool CheckIfDocumentExist(string pConString, short pTemplateID, int pCustID, string pFileName)
  925.         {
  926.             var lstZipFileName = pFileName.Split('_');
  927.  
  928.             List<PsDocumentClassification> lstToSearch = new List<PsDocumentClassification>();
  929.             IndexTemplateField tFieldZipName = IndexTemplateField.ListIndexTemplatesFieldsWithKeyword(pConString, pTemplateID)
  930.                                                                                   .FirstOrDefault(f => f.FIELD_KEYWORD.ToUpper() == "ZIP_FILENAME");
  931.  
  932.             lstToSearch.Add(new PsDocumentClassification
  933.             {
  934.                 IXTF_ORDER = tFieldZipName.IXTF_ORDER, //46,
  935.                 VALUE = lstZipFileName.FirstOrDefault()
  936.             });
  937.  
  938.             List<PsDocument> lstMobileDocuments = PsDocument.SearchDocument(pConString, PsDocument.DocumentType.Document,
  939.                     pTemplateID, -1, -1, -1, null, null, lstToSearch);
  940.  
  941.             var exists = PsDocument.SearchDocument(pConString, PsDocument.DocumentType.Document,
  942.              pTemplateID, -1, -1, -1, null, null, lstToSearch).Any();
  943.  
  944.             return lstMobileDocuments.Any();
  945.  
  946.         }
  947.  
  948.  
  949.         private void WriteImportResult(FileSave fs, string errorDescription)
  950.         {
  951.             StringBuilder result = new StringBuilder();
  952.             result.Append(fs.CreateDate + ";");
  953.             result.Append(sp.FolderInput + "\\" + fs.FileName + ";");
  954.             result.Append(fs.NewFile.ImportedProcessCode + ";");
  955.             result.Append(fs.NewFile.DocStatus + ";");
  956.             result.Append(((fs.IsValid && fs.IsImported) ? sp.FolderBackup : sp.FolderError) + "\\" + DateTime.Now.ToString("yyyyMMdd"));
  957.             result.Append(errorDescription);
  958.  
  959.             FileImportResult.List.Add(result.ToString());
  960.         }
  961.  
  962.         //private static void WriteErrorEvent(string _eventdesc)
  963.         //{
  964.         //    string sSource;
  965.         //    string sLog;
  966.         //    string sEvent;
  967.  
  968.         //    sSource = "PaperSoft Capture Importer Service";
  969.         //    sLog = "Application";
  970.         //    sEvent = _eventdesc;
  971.  
  972.         //    if (!EventLog.SourceExists(sSource))
  973.         //        EventLog.CreateEventSource(sSource, sLog);
  974.  
  975.         //    EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error);
  976.         //}
  977.  
  978.         public string currentOperationID { get; set; }
  979.     }
  980. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement