-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode
More file actions
1931 lines (1688 loc) · 88.5 KB
/
code
File metadata and controls
1931 lines (1688 loc) · 88.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Explain the benefits of this code snipit: using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using tcore.DataContract;
using System.Linq;
using System.Collections;
using System.Web.Script.Serialization;
using tcore.Facades;
using tcore.BusinessObjects.MAILHOUSE;
using System.IO.Compression;
using System.Text;
using tcore.FileServerManager;
using tcore.Common;
using tcore.BusinessObjects;
using System.Threading;
namespace tcore.Task
{
public class DocumentNOTDExportTask : ScheduledTask
{
private static readonly ILog log = LogManager.GetLogger(typeof(DocumentExportTask));
private int UpdUserID = 0;
private string _outDirectory;
private string _tempDirectory;
private string _archiveDirectory;
private string _failedDirectory;
private string _ImageLocalDirectory;
private string _returnedDocsDirectory;
private string _NcoaNixieFolder;
private string _NocaNixieUploadFolder;
private string _tempNOTDDirectory;
private IFileServerManager fileServerManager;
private bool enabledFTP = false;
private string outgoingFTPLocation = string.Empty;
private string outgoingFTPUser = string.Empty;
private string outgoingFTPPassword = string.Empty;
private string outgoingFTPEnableSSL = string.Empty;
private string outgoingFTPDailyFilesFinalFolder = string.Empty;
private string outgoingFTPDailyFilesFolder = string.Empty;
private string outgoingFTPDEvidenceTempFolder = string.Empty;
private string outgoingFTPDailyEvidenceFolder = string.Empty;
//private string NixieNCOASNeededToSend = string.Empty;
private string NocaNixieUploadFolder = string.Empty;
private bool parallelProcess = false;
protected int maxDegreeOfParallel { get; set; }
protected int BatchSizeToProcess = 0;
protected int BatchSizeToProcessWImages = 0;
protected int TaskBundleSize = 0;
List<MHDataFilesDC> DataFileTypeInfo = new List<MHDataFilesDC>();
private bool processSubsetInParallel = false;
private bool exportSubsetInParallel = false;
private bool exportMissedFiles = false;
protected List<long> erroredNOTD = new List<long>();
private MHStatementManagerBO _MHBO;
Dictionary<string, string> imgsToTransfer = new Dictionary<string, string>();
List<string> pdfsToTransfer = new List<string>();
public string strJsData = "";
public DocumentNOTDExportTask()
{
_MHBO = new MHStatementManagerBO();
}
private bool useSshPrivateKey = false;
private string sshPrivateKeyPath = string.Empty;
private string sshPrivateKeyPassphrase = string.Empty;
private static object locker = new Object();
private bool NotIndNOTDS = false;
void Initialization()
{
_outDirectory = Common.Utils.GetConfiguration("OutDirectory");
_tempDirectory = Common.Utils.GetConfiguration("TempDirectory");
_archiveDirectory = Common.Utils.GetConfiguration("ArchiveDirectory");
_failedDirectory = Common.Utils.GetConfiguration("FailedDirectory");
_returnedDocsDirectory = Common.Utils.GetConfiguration("ReturnedDocsDirectory");
_ImageLocalDirectory = Common.Utils.GetConfiguration("ImageLocalDirectory");
_tempNOTDDirectory = Common.Utils.GetConfiguration("TempNOTDDirectory");
if (Common.Utils.GetConfiguration("FTPEnabled").ToUpper() == "TRUE")
{
enabledFTP = true;
}
outgoingFTPLocation = Common.Utils.GetConfiguration("OutgoingFTPLocation");
outgoingFTPUser = Common.Utils.GetConfiguration("OutgoingFTPUser");
outgoingFTPPassword = Common.Utils.GetConfiguration("OutgoingFTPPassword");
outgoingFTPEnableSSL = Common.Utils.GetConfiguration("OutgoingFTPEnableSSL");
UpdUserID = Convert.ToInt32(Common.Utils.GetConfiguration("UserID"));
outgoingFTPDailyFilesFolder = Common.Utils.GetConfiguration("OutgoingFTPDailyFilesFolder");
outgoingFTPDailyFilesFinalFolder = Common.Utils.GetConfiguration("OutgoingFTPDailyFilesFinalFolder");
outgoingFTPDEvidenceTempFolder = Common.Utils.GetConfiguration("OutgoingFTPDEvidenceTempFolder");
outgoingFTPDailyEvidenceFolder = Common.Utils.GetConfiguration("OutgoingFTPDailyEvidenceFolder");
if (Common.Utils.GetConfiguration("ParallelProcess").ToUpper() == "TRUE")
{
parallelProcess = true;
}
maxDegreeOfParallel = Convert.ToInt16(tcore.Common.Utils.GetConfiguration("MaxDegreeOfParallel"));
TaskBundleSize = Convert.ToInt32(tcore.Common.Utils.GetConfiguration("TaskBundleSize"));
BatchSizeToProcess = Convert.ToInt16(Common.Utils.GetConfiguration("BatchSizeToProcess"));
BatchSizeToProcessWImages = Convert.ToInt16(Common.Utils.GetConfiguration("BatchSizeToProcessWImages"));
if (Common.Utils.GetConfiguration("ProcessSubsetInParallel").ToUpper() == "TRUE")
{
processSubsetInParallel = true;
}
if (Common.Utils.GetConfiguration("ExportSubsetInParallel").ToUpper() == "TRUE")
{
exportSubsetInParallel = true;
}
if (Common.Utils.GetConfiguration("ExportMissedFiles").ToUpper() == "TRUE")
{
exportMissedFiles = true;
}
long NixieNCOASNeededToSend = Convert.ToInt16(tcore.Common.Utils.GetConfiguration("NixieNCOASNeededToSend"));
_NocaNixieUploadFolder = tcore.Common.Utils.GetConfiguration("NocaNixieUploadFolder");
_NcoaNixieFolder = Common.Utils.GetConfiguration("NcoaNixieFolder");
if (Common.Utils.GetConfiguration("useSshPrivateKey").ToUpper() == "TRUE")
{
useSshPrivateKey = true;
}
sshPrivateKeyPath = Common.Utils.GetConfiguration("sshPrivateKeyPath");
sshPrivateKeyPassphrase = Common.Utils.GetConfiguration("sshPrivateKeyPassphrase");
if(Common.Utils.GetConfiguration("NewNonNOTDFormat").ToUpper() == "TRUE")
{
NotIndNOTDS = true;
}
}
override public void RunTask()
{
SuccessDC success = new SuccessDC();
List<MHHeaderRecordDC> notdFilesToProcess = new List<MHHeaderRecordDC>();
List<MHHeaderRecordDC> filesToProcessWIndividualTolls = new List<MHHeaderRecordDC>();
List<MHHeaderRecordDC> lastNotds = new List<MHHeaderRecordDC>();
Initialization();
DataFileTypeInfo = _MHBO.GetDataFilesAll();
if (NotIndNOTDS)
{
notdFilesToProcess = GetDataFileListToProcess();
notdFilesToProcess = notdFilesToProcess
.Where(a => a.fileType == "NOTDSUMMARY" || a.fileType == "NOTDSUMMARYRI")
.OrderBy(a => a.fileType)
.ThenBy(a => a.accountId)
.ThenBy(a => a.dataHeaderId)
.Distinct()
.ToList();
//this is slo mo mode if u need to debug
//notdBatchProcess(filesToProcess, NotIndNOTDS, _outDirectory, _MHBO);
for (int i = 0; i < notdFilesToProcess.Count(); i = i + (notdFilesToProcess.Count() / TaskBundleSize))
{
List<MHHeaderRecordDC> notdChunkToProcess = new List<MHHeaderRecordDC>();
notdChunkToProcess = notdFilesToProcess.Take(TaskBundleSize).ToList();
Console.WriteLine(notdChunkToProcess.Count().ToString() + " chunk of: " + notdFilesToProcess.Count().ToString() + " processing...");
List<MHHeaderRecordDC> removeList = new List<MHHeaderRecordDC>();
removeList = notdFilesToProcess.Take(TaskBundleSize).ToList();
System.Threading.Tasks.Task task = ProcessBatchTask(notdChunkToProcess, BatchSizeToProcessWImages, NotIndNOTDS, _outDirectory, _MHBO);
task.Wait();
Console.WriteLine("Batch completed...");
foreach (var r in removeList)
{
var itemToRemove = notdFilesToProcess.Single(n => n.batchId == r.batchId);
notdFilesToProcess.Remove(itemToRemove);
}
Console.WriteLine(removeList.Count().ToString() + " processed and removed.");
}
Console.WriteLine("completed task.");
log.Debug("completed task.");
}
else //notd summary and notd singles (MDTA-8585 will replace)
{
notdFilesToProcess = GetDataFileListToProcess();
notdFilesToProcess = notdFilesToProcess
.Where(a => a.fileType == "NOTDSUMMARY" || a.fileType == "NOTDSUMMARYRI")
.OrderBy(a => a.fileType)
.ThenBy(a => a.accountId)
.ThenBy(a => a.dataHeaderId)
.Distinct()
.ToList();
for (int i = 0; i < notdFilesToProcess.Count(); i = i + (notdFilesToProcess.Count() / TaskBundleSize))
{
List<MHHeaderRecordDC> notdChunkToProcess = new List<MHHeaderRecordDC>();
notdChunkToProcess = notdFilesToProcess.Take(TaskBundleSize).ToList();
Console.WriteLine(notdChunkToProcess.Count().ToString() + " chunk of: " + notdFilesToProcess.Count().ToString() + " processing...");
List<MHHeaderRecordDC> removeList = new List<MHHeaderRecordDC>();
removeList = notdFilesToProcess.Take(TaskBundleSize).ToList();
System.Threading.Tasks.Task<SuccessDC> task = ProcessBatchTask(notdChunkToProcess, BatchSizeToProcessWImages, NotIndNOTDS, _outDirectory, _MHBO);
task.Wait();
Console.WriteLine("Batch completed...");
RemoveProcessedFromList(notdFilesToProcess, removeList);
}
//reallocate memory
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
private static void RemoveProcessedFromList(List<MHHeaderRecordDC> notdFilesToProcess, List<MHHeaderRecordDC> removeList)
{
System.Threading.Tasks.Parallel.ForEach(removeList, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = -1 }, r =>
{
var itemToRemove = notdFilesToProcess.Single(n => n.batchId == r.batchId);
notdFilesToProcess.Remove(itemToRemove);
});
Console.WriteLine(removeList.Count().ToString() + " processed and removed.");
}
public static async System.Threading.Tasks.Task<SuccessDC> ProcessBatchTask(List<MHHeaderRecordDC> notdFilesToProcess, int BatchSizeToProcessWImages, bool NotIndNOTDS, string _outDirectory, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
await System.Threading.Tasks.Task.Run(() =>
{
int threadCount = (notdFilesToProcess.Count / (BatchSizeToProcessWImages));
if (threadCount <= 1)
{
threadCount = 1;
}
else
{
int remainder, quotient = Math.DivRem(notdFilesToProcess.Count, (BatchSizeToProcessWImages), out remainder);
if (remainder > 0)
threadCount = threadCount + 1;
}
Thread[] notdThread = new Thread[threadCount];
List<Thread> notdThreadList = new List<Thread>();
int threadIteration = 0;
for (int i = 0; i < notdFilesToProcess.Count(); i = i + (BatchSizeToProcessWImages))
{
List<MHHeaderRecordDC> fileChunkToProcess = notdFilesToProcess.Skip(i).Take(BatchSizeToProcessWImages).ToList();
notdThread[threadIteration] = new Thread(() => notdBatchProcess(fileChunkToProcess, NotIndNOTDS, _outDirectory, _MHBO, BatchSizeToProcessWImages));
notdThread[threadIteration].Start();
notdThreadList.Add(notdThread[threadIteration]);
threadIteration = threadIteration + 1;
}
foreach (Thread t in notdThreadList)
{
t.Join();
}
});
success.blnSuccess = true;
return success;
}
static readonly object notdLock = new object();
public static SuccessDC notdBatchProcess(List<MHHeaderRecordDC> filesToProcess, bool NotIndNOTDS, string _outDirectory, MHStatementManagerBO _MHBO, int BatchSizeToProcessWImages)
{
SuccessDC success = new SuccessDC();
List<MHHeaderRecordDC> filesToProcessWIndividualTolls = new List<MHHeaderRecordDC>();
List<long> invoicesToAdd = new List<long>();
if (NotIndNOTDS) //this will be the new norm without the NOTD file
{
if (filesToProcess.Count > 0)
{
List<MHHeaderRecordDC> NOTDsummarys = new List<MHHeaderRecordDC>();
Console.WriteLine("Begin processing NOTDSUMMARYS ...");
NOTDsummarys = filesToProcess.Where(a => a.fileType == "NOTDSUMMARY").ToList();
success = ProcessSubSetOfFiles(NOTDsummarys, _MHBO);
//this is used in the naming convention of each batch at time of write
string commonTrackerID = DateTime.Now.ToString("yyyyMMddHHmmss");
//JSONs
success = ExportSubSetOfFiles(commonTrackerID, NotIndNOTDS, _outDirectory, _MHBO);
//images
success = ExportSubSetOfImages(NOTDsummarys, commonTrackerID, NotIndNOTDS, _outDirectory, _MHBO, BatchSizeToProcessWImages);
}
}
else
{
//grab transactions and makes individual NOTDS in tbHeaderRecords table to export
System.Threading.Tasks.Parallel.ForEach(filesToProcess, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = -1 }, file =>
{
try
{
Console.WriteLine("Adding batch of invoices for NOTDS from NOTDSUMMARYS.");
invoicesToAdd = AddNOTDStoQNOtificationsFromSummaries(file.qRequestId, file.fileType, _MHBO);
foreach (long individualNOTD in invoicesToAdd)
{
var notdAdd = _MHBO.GetHeaderRecordByHeaderID(Convert.ToInt64(individualNOTD));
if (notdAdd.Count > 0)
try
{
filesToProcessWIndividualTolls.Add(notdAdd[0]);
}
catch { };
}
if (file != null)
{
filesToProcessWIndividualTolls.Add(file);
};
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
});
if (filesToProcessWIndividualTolls.Count > 0)
{
List<MHHeaderRecordDC> NOTDsummarys = new List<MHHeaderRecordDC>();
List<MHHeaderRecordDC> NOTDS = new List<MHHeaderRecordDC>();
Console.WriteLine("Begin processing NOTDSUMMARYS ...");
try
{
NOTDsummarys = filesToProcessWIndividualTolls.Where(a => a.fileType == "NOTDSUMMARY" || a.fileType == "NOTDSUMMARYRI").ToList();
success = ProcessSubSetOfFiles(NOTDsummarys, _MHBO);
string commonTrackerID = NOTDsummarys[0].batchId.ToString();
success.blnSuccess = true;
if (success.blnSuccess)
{
Console.WriteLine("Begin processing NOTDS ...");
NOTDS = filesToProcessWIndividualTolls.Where(a => a.fileType == "NOTD" || a.fileType == "NOTDRI").ToList();
success = ProcessSubSetOfFiles(NOTDS, _MHBO);
filesToProcessWIndividualTolls.Clear();
}
success.blnSuccess = true;
if (success.blnSuccess)
{
//images
success = ExportSubSetOfImages(NOTDsummarys, commonTrackerID, NotIndNOTDS, _outDirectory, _MHBO, BatchSizeToProcessWImages);
}
success.blnSuccess = true;
if (success.blnSuccess)
{
//JSONs
success = ExportSubSetOfFiles(commonTrackerID, NotIndNOTDS, _outDirectory, _MHBO);
}
filesToProcessWIndividualTolls.Clear();
}
catch { }
//doc main uploads for now
//UploadFiles();
}
}
success.blnSuccess = true;
return success;
}
private static SuccessDC ExportSubSetOfImages (List<MHHeaderRecordDC> NOTDsummarys, string commonTrackerID, bool NotIndNOTDS, string _outDirectory, MHStatementManagerBO _MHBO, int BatchSizeToProcessWImages)
{
SuccessDC success = new SuccessDC();
Dictionary<string, string> filesToZip = GetImagesToTransfer(NOTDsummarys, _MHBO);
if (NotIndNOTDS)
{
string zipName = "MDTA_MH_" + NOTDsummarys[0].fileType + "_" + commonTrackerID;
System.Threading.Tasks.Task task = ZipBundlesWImages(zipName, filesToZip, _outDirectory, BatchSizeToProcessWImages);
task.Wait();
}
else
{
string zipName = "MDTA_MH_NOTD_" + commonTrackerID;
System.Threading.Tasks.Task task = ZipBundlesWImages(zipName, filesToZip, _outDirectory, BatchSizeToProcessWImages);
task.Wait();
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
success.blnSuccess = true;
return success;
}
private static Dictionary<string, string> GetImagesToTransfer(List<MHHeaderRecordDC> NOTDsummarys, MHStatementManagerBO _MHBO)
{
List<MHNotdSummaryDC> summarys = new List<MHNotdSummaryDC>();
Dictionary<string, string> filesToZip = new Dictionary<string, string>();
string img = string.Empty;
string path = string.Empty;
foreach (var notd in NOTDsummarys)
{
try
{
var item = _MHBO.GetNOTDSummaryByHeaderID(notd.batchId);
summarys.Add(item[0]);
}
catch { } //swallow error and move on if the image can not be found
}
foreach(var s in summarys)
{
//full vehicle image
var lastSlashIndex = s.imageName.LastIndexOf('\\');
img = s.imageName.Substring((lastSlashIndex + 1));
path = s.imageName.Substring(0, s.imageName.Length - img.Length);
if (!filesToZip.ContainsKey(img))
try
{
filesToZip.Add(img, path);
}
catch { } //swallow error and move on if the image can not be found
else
{
var m = img;
}
//lpr plate image
lastSlashIndex = s.imageROIName.LastIndexOf('\\');
img = s.imageROIName.Substring((lastSlashIndex + 1));
path = s.imageROIName.Substring(0, s.imageROIName.Length - img.Length);
if (!filesToZip.ContainsKey(img))
try
{
filesToZip.Add(img, path);
}
catch { } //swallow error and move on if the image can not be found
else
{
var m = img;
}
}
return filesToZip;
}
public static SuccessDC ProcessSubSetOfFiles(List<MHHeaderRecordDC> filesToProcess, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
filesToProcess = filesToProcess.OrderBy(a => a.fileType).ThenBy(a => a.dataHeaderId).ToList();
System.Threading.Tasks.Parallel.ForEach(filesToProcess, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = -1 }, file =>
{
try
{
success = ProcessFileData(file, _MHBO);
}
catch { }
if (!success.blnSuccess)
ErrorHeaderFile(file, success, success.vcResult, _MHBO);
});
success.blnSuccess = true;
return success;
}
public static SuccessDC ExportSubSetOfFiles(string commonNameTracker, bool NotIndNOTDS, string _outDirectory, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
List<MHHeaderRecordDC> filesToExport = new List<MHHeaderRecordDC>();
List<MHHeaderRecordDC> subsetOFfilesToExport = new List<MHHeaderRecordDC>();
List<string> fileTypes = new List<string>();
filesToExport = _MHBO.GetDataFilesToExport().Where(a => a.fileType.Contains("NOTD"))
.OrderByDescending(a => a.fileType)
.ThenBy(a => a.dataHeaderId).ToList();
fileTypes = filesToExport.Select(a => a.fileType).Distinct().ToList();
foreach (var fileType in fileTypes)
{
try
{
List<MHHeaderRecordDC> SubsetOffilesToExport = filesToExport.Where(a => a.fileType == fileType).ToList();
success = CreateBundledFilesToTransfer(SubsetOffilesToExport,commonNameTracker, NotIndNOTDS, _outDirectory, _MHBO);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
log.Error(ex.Message, ex);
success.vcResult = ex.Message;
}
}
return success;
}
private static SuccessDC ProcessFileData(MHHeaderRecordDC file, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
MHCommonFieldsDC commonFields = new MHCommonFieldsDC();
if (file.accountId <= 0 || file.batchId <= 0)
{
success.blnSuccess = true;
success.vcResult = file.batchId + " : Account or HeaderRecord not found. : will not process";
log.Error(file.batchId + " : Account or HeaderRecord not found : will not process");
return success;
}
try
{
switch (file.fileType)
{
case "NOTD":
_MHBO.InsertCommonFieldsByRequestIdFromAMS(file.accountId, file.batchId, file.dataFileId, file.qRequestId);
break;
case "NOTDRI":
_MHBO.InsertCommonFieldsByRequestIdFromAMS(file.accountId, file.batchId, file.dataFileId, file.qRequestId);
break;
default:
_MHBO.InsertCommonFieldsFromAMS(file.accountId, file.batchId, file.dataFileId);
break;
}
//based on document type in DB
switch (file.fileType)
{
case "NOTDSUMMARY":
_MHBO.InsertNotdSummaryFromAMS(file.batchId);
success.blnSuccess = true;
break;
case "NOTDSUMMARYRI":
_MHBO.InsertNotdSummaryRiFromAMS(file.batchId);
success.blnSuccess = true;
break;
case "NOTD":
_MHBO.InsertNotdFromAMS(file.batchId);
success.blnSuccess = true;
break;
case "NOTDRI":
_MHBO.InsertNotdRiFromAMS(file.batchId);
success.blnSuccess = true;
break;
default:
success.blnSuccess = true;
break;
}
if (success.blnSuccess)
{
//mark header as processed
_MHBO.UpdateHeaderRecordAsProcessed(file.batchId);
}
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
success.vcResult = ex.Message;
}
return success;
}
private static SuccessDC CreateFilesToTransfer(MHHeaderRecordDC headerFile, bool NotIndNOTDS, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
object bodyData = null;
object translatedBodyData = null;
try
{
switch (headerFile.fileType)
{
case "NOTDSUMMARY":
bodyData = _MHBO.GetNOTDSummaryByHeaderID(headerFile.batchId);
if (bodyData != null)
{
success = TranslateNotdSummaryBodyData(bodyData, headerFile ,NotIndNOTDS, _MHBO);
if (success.blnSuccess)
{
translatedBodyData = success.objData;
success.blnSuccess = true;
}
}
else
{
log.Error("CreateFilesToTransfer: HeaderID: " + headerFile.batchId + " bodyData failed to translate.");
success.blnSuccess = false;
}
break;
case "NOTDSUMMARYRI":
bodyData = _MHBO.GetNoTDSummaryRIByHeaderID(headerFile.batchId);
if (bodyData != null)
{
success = TranslateNotdSummaryRiBodyData(bodyData, headerFile, NotIndNOTDS, _MHBO);
if (success.blnSuccess)
{
translatedBodyData = success.objData;
success.blnSuccess = true;
}
}
else
{
log.Error("CreateFilesToTransfer: HeaderID: " + headerFile.batchId + " bodyData failed to translate.");
success.blnSuccess = false;
}
break;
case "NOTD":
bodyData = _MHBO.GetNoTDByHeaderID(headerFile.batchId);
if (bodyData != null)
{
success = TranslateNotdBodyData(bodyData, headerFile, _MHBO);
if (success.blnSuccess)
{
translatedBodyData = success.objData;
success.blnSuccess = true;
}
}
else
{
log.Error("CreateFilesToTransfer: HeaderID: " + headerFile.batchId + " bodyData failed to translate.");
success.blnSuccess = false;
}
break;
case "NOTDRI":
bodyData = _MHBO.GetNoTDRIByHeaderID(headerFile.batchId);
if (bodyData != null)
{
success = TranslateNotdRiBodyData(bodyData, headerFile, _MHBO);
if (success.blnSuccess)
{
translatedBodyData = success.objData;
success.blnSuccess = true;
}
}
else
{
log.Error("CreateFilesToTransfer: HeaderID: " + headerFile.batchId + " bodyData failed to translate.");
success.blnSuccess = false;
}
break;
default:
break;
}
//serialize data for export
if (success.blnSuccess)
{
success.objData = translatedBodyData;
}
else
{
Console.WriteLine("CreateFilesToTransfer FAILED success : " + success.blnSuccess);
log.Error("CreateFilesToTransfer FAILED success : " + success.blnSuccess);
}
}
catch(Exception ex)
{
Console.WriteLine(" err: " + ex.Message);
log.Error(ex.Message, ex);
}
return success;
}
private static SuccessDC CreateBundledFilesToTransfer(List<MHHeaderRecordDC> headerFiles, string commonNameTracker, bool NotIndNOTDS, string _outDirectory, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
object translatedBodyData = null;
List<object> translatedBodies = new List<object>();
List<MHCommonAndBodyDataDC> bundledFiles = new List<MHCommonAndBodyDataDC>();
List<MHCommonAndBodyDataDC> excludedEmailFiles = new List<MHCommonAndBodyDataDC>();
foreach (MHHeaderRecordDC headerFile in headerFiles)
{
try
{
MHCommonAndBodyDataDC commonAndBody = new MHCommonAndBodyDataDC();
success = null;
try
{
success = CreateFilesToTransfer(headerFile, NotIndNOTDS, _MHBO);
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
if (success.blnSuccess)
{
translatedBodyData = success.objData;
commonAndBody.headerBatchId = headerFile.batchId;
commonAndBody.bodyDataFiles = translatedBodyData;
if (commonAndBody.bodyDataFiles != null)
{
bundledFiles.Add(commonAndBody);
_MHBO.UpdateHeaderRecordAsAddedToJson(headerFile.batchId);
}
Console.WriteLine("Bundled for export: " + headerFile.batchId);
}
else
{
//there was a problem. Mark it as errored
try
{
ErrorHeaderFile(headerFile, success, "Bundled for export: " + headerFile.batchId.ToString() + "Err: " + success.vcResult ?? "unkown.", _MHBO);
}
catch { }; //when a time-out occurs, it has already errored so no since erroring again to say there was an error
}
}
catch (Exception ex)
{
Console.WriteLine(headerFiles[0].dataHeaderId + " err: " + ex.Message);
log.Error(ex.Message, ex);
}
}
success.blnSuccess = true;
if (success.blnSuccess)
{
try
{
//delete those not being sent because wrong delivery type
System.Threading.Tasks.Parallel.ForEach(excludedEmailFiles, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = -1 }, ex =>
{
try
{
_MHBO.DeleteHeaderRecordByHeaderID(ex.headerBatchId);
}
catch { }; //when a time-out occurs, it has already errored so no since erroring again to say there was an error
});
//before exporting, lets put all componets into one Export Data Contract for proper formatting
MHBundledExportDC exportData = TranslateBundleForExport(bundledFiles, headerFiles[0],commonNameTracker, _MHBO);
if (Convert.ToInt32(exportData.recordCount) > 0)
{
string jsonName = "MDTA_MH_" + headerFiles[0].fileType + "_" + commonNameTracker;
JavaScriptSerializer json = new JavaScriptSerializer();
json.MaxJsonLength = Int32.MaxValue;
var strJson = json.Serialize(exportData);
Console.WriteLine("Generating JSON file for: " + headerFiles[0].fileType.ToString() + jsonName + ".JSON");
File.WriteAllText(Path.Combine(_outDirectory, jsonName + ".JSON"), strJson);
//save file name to DB
System.Threading.Tasks.Parallel.ForEach(headerFiles, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = -1 }, hr =>
{
try
{
_MHBO.UpdateHeaderRecordWithJsonFileName(hr.batchId, jsonName);
}
catch { } //when a time-out occurs, it has already errored so no since erroring again to say there was an error
});
}
}
catch (Exception ex)
{
Console.WriteLine(headerFiles[0].dataHeaderId + " err: " + ex.Message);
log.Error(ex.Message, ex);
}
}
success.blnSuccess = true;
return success;
}
public static void ErrorHeaderFile(MHHeaderRecordDC headerFile, SuccessDC success, string from, MHStatementManagerBO _MHBO)
{
try
{
_MHBO.UpdateHeaderRecordAsErrored(headerFile.batchId, from + ": " + success.vcResult);
}
catch { } //when a time-out occurs, it has already errored so no since erroring again to say there was an error
}
private static async System.Threading.Tasks.Task<SuccessDC> ZipBundlesWImages(string zipFileName, Dictionary<string, string> imgsToTransfer, string _outDirectory, int BatchSizeToProcessWImages)
{
SuccessDC success = new SuccessDC();
await System.Threading.Tasks.Task.Run(() =>
{
//isolate image collection for these zips only
Dictionary<string, string> filesToZip = new Dictionary<string, string>(imgsToTransfer);
Console.WriteLine("Images to zip count: " + filesToZip.Count().ToString());
//this is slow mo mode in case you need to debug
//zipBatch(zipFileName + "_1.zip", filesToZip, _outDirectory);
int threadCount = (filesToZip.Count / (BatchSizeToProcessWImages));
if (threadCount <= 1)
{
threadCount = 1;
}
else
{
int remainder, quotient = Math.DivRem(filesToZip.Count, (BatchSizeToProcessWImages), out remainder);
if (remainder > 0)
threadCount = threadCount + 1;
}
Thread[] zipThread = new Thread[threadCount];
List<Thread> zipThreadList = new List<Thread>();
int threadIteration = 0;
long zipItemCount = 1;
string zipIterationName = string.Empty;
for (int i = 0; i < filesToZip.Count(); i = i + (BatchSizeToProcessWImages))
{
var fileChunkToZip = filesToZip.Skip(i).Take(BatchSizeToProcessWImages).ToList();
zipIterationName = zipFileName + "_" + (threadIteration + 1).ToString() + ".zip";
zipThread[threadIteration] = new Thread(() => zipBatch(zipIterationName, fileChunkToZip, _outDirectory));
zipThread[threadIteration].Start();
Console.Write("thread: " + (threadIteration + 1) + " processing");
zipThreadList.Add(zipThread[threadIteration]);
threadIteration = threadIteration + 1;
zipItemCount = zipItemCount + 1;
foreach (Thread t in zipThreadList)
{
t.Join();
}
}
});
success.blnSuccess = true;
return success;
}
static readonly object zipLock = new object();
private static SuccessDC zipBatch(string zipIterationName, IEnumerable<KeyValuePair<string, string>> fileChunkToZip, string _outDirectory)
{
SuccessDC success = new SuccessDC();
try
{
var zipFileName = Path.Combine(_outDirectory, zipIterationName);
if (fileChunkToZip.Count() > 0)
{
using (var stream = File.OpenWrite(zipFileName))
using (ZipArchive archive = new ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create))
foreach (var file in fileChunkToZip)
{
try
{
if (file.Key != null)
{
try
{
archive.CreateEntryFromFile(Path.GetFullPath(file.Value) + Path.GetFileName(file.Key), file.Key, CompressionLevel.Fastest);
}
catch { }; //sometimes we dont have the image actually so swallow error and move on
}
else
{
log.Error(file.Key + " image key had error: " + file.Value);
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
continue;
}
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
success.blnSuccess = true;
return success;
}
private static SuccessDC TranslateNotdRiBodyData(object bodyData, MHHeaderRecordDC headerFile, MHStatementManagerBO _MHBO)
{
SuccessDC success = new SuccessDC();
var data = new MHExNotdRiDC();
try
{
var iStat = ((IEnumerable)bodyData).Cast<MHNotdDC>().OrderBy(a => Convert.ToInt32(a.transactionNumber)).ToList();
data.headerBatchId = headerFile.batchId;
data.mailingNumber = iStat[0].mailingNumber;
data.totalPaymentAmount = iStat[0].totalPaymentAmount;
data.daysToPay = iStat[0].daysToPay;
data.paymentDueDate = TranslateToISODateTime(iStat[0].paymentDueDate);
data.tollViolationDate = TranslateToISODateTime(AddDaysToDate(iStat[0].paymentDueDate, 1).ToString());
data.billedAmount = iStat[0].billedAmount;
data.civilPenaltyFeeDue = TranslateMoney(iStat[0].civilPenaltyFeeDue);
data.paymentDueAmountWithPenalty = iStat[0].paymentDueAmountWithPenalty;
data.tollViolationGracePeriod = "1"; // iStat[0].tollViolationGracePeriod;
data.numberOfTrans = iStat.Count.ToString();
data.reissue = "Y";
data.amountDueAfter = iStat[0].amountDueAfter;
data.transactions = new List<MHExTransactionDC>();
foreach (var e in iStat)
{
var fs = new MHExTransactionDC();
if (e.exitPlazaCode != null && e.exitPlazaCode.Length > 0 && e.entryPlazaCode != null && e.entryPlazaCode.Length > 0)
{
//mapped plaza info
var plazaData = new List<MHExPlazaInfoDC>();
plazaData = _MHBO.GetPlazaInfoByIdFromAMS(Convert.ToInt64(e.entryPlazaCode), Convert.ToInt64(e.exitPlazaCode));
if (!string.Equals(plazaData[0].EntryDecription.Trim(), plazaData[0].ExitDecription.Trim(), StringComparison.CurrentCulture))
{
//If something is comming into e.entryPlazaDescription we'll use it. (Covid dynamic label)
fs.entryPlazaDescription = string.IsNullOrEmpty(e.entryPlazaDescription) ? plazaData[0].EntryDecription : e.entryPlazaDescription;
fs.entryPlazaCode = plazaData[0].EntryCode;
fs.transactionEntryDateTime = TranslateToISODateTime(e.transactionEntryDateTime);
}
//If something is comming into e.entryPlazaDescription we'll use it. (Covid dynamic label)
fs.exitPlazaDescription = string.IsNullOrEmpty(e.entryPlazaDescription) ? plazaData[0].ExitDecription : e.entryPlazaDescription;
fs.exitPlazaCode = plazaData[0].ExitCode;
fs.transactionExitDateTime = TranslateToISODateTime(e.transactionExitDateTime);
fs.locationCounty = plazaData[0].ExitCounty;
fs.facilityName = plazaData[0].Facility;
}
fs.childRecordType = "TX";
fs.licensePlateNumber = e.licensePlateNumber;
fs.licensePlateState = e.licensePlateState;
fs.transponderNumberOrPlateNumber = e.licensePlateNumber;
fs.vehicleClassification = "";
fs.transactionAmount = e.billedAmount;
fs.runningBalanceAmount = e.amountDueAfter;
fs.transactionNumber = e.transactionNumber;
fs.transactionDateTime = TranslateToISODateTime(e.transactionExitDateTime);
fs.transactionDescription = "Toll";
fs.imageName = ParseImageName(e.imageName);
if (fs.imageName == "NotAvailable.jpg")
{
success.vcResult = "Image not found where specified";
log.Error(success.vcResult);
return success;
}
fs.imageROIName = ParseImageName(e.roiImageName);
if (fs.imageROIName == "NotAvailable.jpg")
{
success.vcResult = "ROI Image not found where specified";
log.Error(success.vcResult);
fs.imageROIName = String.Empty;
}
data.transactions.Add(fs);
};
success.blnSuccess = true;