-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
609 lines (533 loc) · 23 KB
/
MainForm.cs
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
using CsvHelper;
using CsvHelper.Configuration;
using iTextSharp.text.pdf;
using Microsoft.VisualBasic.FileIO;
using Microsoft.WindowsAPICodePack.Dialogs;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace CertMaker5000
{
public partial class MainForm : Form
{
FieldManagementForm FieldManagementForm = new FieldManagementForm();
bool ValidPDFFile = false;
bool ValidCSVFile = false;
string ValidPDFFilePath = "";
string ValidCSVFilePath = "";
string EmailBody = "";
DataTable CSVDataTable = new DataTable();
public MainForm()
{
InitializeComponent();
}
List<ControlState> ControlStates = new();
#region Helper Methods
public static int CountBools(params bool[] args)
{
return args.Count(t => !t);
}
private void CheckValidation()
{
if (CountBools(ValidPDFFile, ValidCSVFile) == 0)
{
FieldManagerLabel.Visible = true;
LoadPdfButton.Visible = true;
GenerateNowButton.Visible = true;
GenerateAndEmailButton.Visible = true;
//PreviewEmailButton.Visible = true;
}
else
{
FieldManagerLabel.Visible = false;
LoadPdfButton.Visible = false;
GenerateNowButton.Visible = false;
GenerateAndEmailButton.Visible = false;
//PreviewEmailButton.Visible = false;
}
}
private bool ValidateCSVFile(string FilePath)
{
IEnumerable<string> lines = File.ReadLines(FilePath).Take(10).ToList();
char? delim = DetectDelimiter(lines);
List<string> ErrorList = new List<string>();
if (delim != null)
{
// ToDo: This needs work. As this delimits the file. But it does not delimit per row.
using (var parser = new TextFieldParser(FilePath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(delim.ToString());
string[] line;
while (!parser.EndOfData)
{
try
{
line = parser.ReadFields();
}
catch (MalformedLineException ex)
{
ErrorList.Add(ex.Message);
}
}
}
// Use CSV Helper . Get DataTable
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = delim.ToString(),
};
using (var reader = new StreamReader(FilePath))
using (var csv = new CsvReader(reader, config))
{
using (var dr = new CsvDataReader(csv))
{
var dt = new DataTable();
dt.Load(dr);
DataColumn PDFFilePathColumn = new()
{
DataType = typeof(String),
ColumnName = "PDFFilePathColumn",
DefaultValue = string.Empty
};
DataColumn PhotoFilePathColumn = new()
{
DataType = typeof(String),
ColumnName = "PhotoFilePathColumn",
DefaultValue = string.Empty
};
dt.Columns.Add(PDFFilePathColumn);
dt.Columns.Add(PhotoFilePathColumn);
CSVDataTable = dt;
UserListBox.DisplayMember = "";
UserListBox.ValueMember = "";
bool ContainsEmail = false;
bool ContainsName = false;
List<string> UserListColumnNames = new List<string>();
List<string> UserListColumnEmailNames = new();
List<string> UserListColumnNameNames = new();
FieldManagementForm.CSVFieldsBindingSource.Clear();
foreach (DataColumn c in CSVDataTable.Columns)
{
FieldManagementForm.CSVFieldsBindingSource.Add("{{" + c.ColumnName + "}}");
if (c.ColumnName.ToUpper().Contains("EMAIL") || c.ColumnName.ToUpper().Contains("E-MAIL"))
{
ContainsEmail = true;
UserListColumnNames.Add(c.ColumnName);
UserListColumnEmailNames.Add(c.ColumnName);
}
if (c.ColumnName.ToUpper().Contains("NAME"))
{
ContainsName = true;
UserListColumnNames.Add(c.ColumnName);
UserListColumnNameNames.Add(c.ColumnName);
}
}
UserListBox.DataSource = dt;
if (ContainsEmail)
{
UserListBox.DisplayMember = UserListColumnEmailNames.FirstOrDefault();
UserListBox.ValueMember = UserListColumnEmailNames.FirstOrDefault();
}
else if (ContainsName)
{
UserListBox.DisplayMember = UserListColumnNameNames.FirstOrDefault();
UserListBox.ValueMember = UserListColumnNameNames.FirstOrDefault();
}
else
{
UserListBox.DisplayMember = CSVDataTable.Columns[0].ColumnName;
UserListBox.ValueMember = CSVDataTable.Columns[0].ColumnName;
}
FieldManagementForm.CSVFieldsCombo.Refresh();
}
}
if (ErrorList.Count > 0)
{
string ErrorMessage = ""
+ "Sorry, your Delimited File is not valid" + Environment.NewLine
+ $"We detected your delimiter as {(delim == '\t' ? "{tab}" : delim.ToString())}" + Environment.NewLine
+ $"We then we tried parse your file with this delimiter and was not able to successfully parse it." + Environment.NewLine
+ $"Please check your file and make sure it's a valid delimited file." + Environment.NewLine
+ $"The errors we were able to find are listed below:" + Environment.NewLine
;
foreach (string s in ErrorList)
{
ErrorMessage += (s + Environment.NewLine);
}
MessageBox.Show(ErrorMessage);
return false;
}
}
else
{
MessageBox.Show("Sorry, could not detect the delimiter of the file you provided or your file is not a proper delimited file");
return false;
}
return true;
}
private bool ValidatePDFFile(string FilePath)
{
PdfReader pdfReader = new PdfReader(FilePath);
AcroFields docfields = pdfReader.AcroFields;
ICollection<string> FieldKeys = docfields.Fields.Keys;
if (FieldKeys == null || FieldKeys.Count == 0)
{
MessageBox.Show("Sorry but your PDF does not have any fillable fields and therefore is not valid.");
return false;
}
return true;
}
public char? DetectDelimiter(IEnumerable<string> lines)
{
List<char> delimiters = new List<char>();
char[] delims = { ',', '\t', '|' };
delimiters.AddRange(delims);
Dictionary<char, int> delimFrequency = new Dictionary<char, int>();
// Setup our frequency tracker for given delimiters
delimiters.ToList().ForEach(curDelim =>
delimFrequency.Add(curDelim, 0)
);
// Get a total sum of all occurrences of each delimiter in the given lines
delimFrequency.ToList().ForEach(curDelim =>
delimFrequency[curDelim.Key] = lines.Sum(line => line.Count(p => p == curDelim.Key))
);
// Find delimiters that have a frequency evenly divisible by the number of lines
// (correct & consistent usage) and order them by largest frequency
var possibleDelimiters = delimFrequency
.Where(f => f.Value > 0
//&& f.Value % lines.Count() == 0
)
.OrderByDescending(f => f.Value)
.ToList();
// If more than one possible delimiter found, return the most used one
if (possibleDelimiters.Any())
{
return possibleDelimiters.First().Key.ToString().First();
}
else
{
return null;
}
}
private DialogResult? WarningOfResetFields(string PdfOrCsv)
{
if (PdfOrCsv.ToUpper() == "PDF" && FieldManagementForm.pDFFieldValues.Count > 0)
{
return MessageBox.Show("Please note that if you choose a different PDF. Your field mapping will be reset and you will need to redo this again.", "Data Reset Confirmation", MessageBoxButtons.OKCancel);
}
if (PdfOrCsv.ToUpper() == "CSV")
{
return MessageBox.Show("Please note that if you choose a different PDF. Your field mapping will be reset and you will need to redo this again.", "Data Reset Confirmation", MessageBoxButtons.OKCancel);
}
return null;
}
private bool CheckIfTableIsEmptyAndRespond()
{
if (CSVDataTable == null || CSVDataTable.Rows.Count == 0)
{
MessageBox.Show($"No Records have been parsed yet.{Environment.NewLine}Please try loading your CSV File Again");
return false;
}
foreach (PDFFieldValue f in FieldManagementForm.PDFFieldValueBindingSource)
{
if (String.IsNullOrEmpty(f.Value))
{
MessageBox.Show($"Sorry, but it looks like you haven't completed your mapping yet.{Environment.NewLine}Please head over to \"Field Manager\" and complete your mapping");
return false;
}
}
return true;
}
private string CleanVariableString(string input)
{
string rval = String.IsNullOrEmpty(input) ? "" : input;
return rval.Replace("{{", "").Replace("}}", "");
}
private void UpdatePreviewEmailBody()
{
string NewText = HTMLBodyEditTextBox.Text;
var reg = new Regex("{{.*?}}");
var matches = reg.Matches(NewText);
foreach (var item in matches)
{
string rval = item.ToString()!;
string input = CleanVariableString(rval);
string reval = "";
if (CSVDataTable != null && CSVDataTable.Rows.Count > 0)
{
if (UserListBox.Items.Count > 0)
{
if (UserListBox.SelectedItems.Count <= 0)
{
UserListBox.SelectedIndex = 0;
}
reval = ((DataRowView)UserListBox.SelectedItem).Row[input].ToString()!;
}
else
{
reval = CSVDataTable.Rows[0][input].ToString()!;
}
}
else
{
reval = rval;
}
reval = String.IsNullOrEmpty(reval) ? "" : reval;
NewText = NewText.Replace(rval, reval);
}
HTMLBodyPreviewTextBox.Text = NewText;
}
private string GeneratePathForPDF(DataRow row)
{
string FileName = CSVDataTable.Rows.IndexOf(row).ToString().PadLeft(10, '0') + " " + UserListBox.SelectedValue.ToString() + ".pdf";
return Path.Combine(CertDropTextBox.Text, ReplaceInvalidChars(FileName));
}
public string ReplaceInvalidChars(string filename)
{
return string.Join("", filename.Split(Path.GetInvalidFileNameChars()));
}
#endregion Helper Methods
#region Main Methods
private void WritePDF(string? FilePath, DataRow? row = null)
{
// C:\Users\Owner\Downloads\DRopCertTemplate.pdf
// ToDo: Refactor this. not to repeakj Logic in other locations.
FileInfo CertFile = new FileInfo(CertTemplateTextBox.Text);
if (!CertFile.Exists)
{
MessageBox.Show("Sorry your template not exist or you do not have access to it");
return;
}
if (FilePath == null)
{
string FileName = @"DRopCertTemplate.pdf";
FilePath = Path.Combine(@"C:\Users\Owner\Downloads\", FileName);
}
row["PDFFilePathColumn"] = FilePath;
//row["PhotoFilePathColumn"] = FilePath;
using (FileStream outFile = new FileStream(FilePath, FileMode.Create))
{
if (row != null)
{
foreach (PDFFieldValue f in FieldManagementForm.PDFFieldValueBindingSource)
{
if (f.Value == null) { MessageBox.Show("Sorry, but you need to make sure you set all your fields in the \"Field Manager\" section "); return; }
}
}
PdfReader pdfReader = new PdfReader(CertFile.FullName);
PdfStamper pdfStamper = new PdfStamper(pdfReader, outFile) { FormFlattening = true };
AcroFields docfields = pdfStamper.AcroFields;
if (row == null)
{
foreach (PDFFieldValue f in FieldManagementForm.PDFFieldValueBindingSource)
{
docfields.SetField(f.Field, f.CapsValue ? f.Value.ToUpper() : f.Value);
}
}
else
{
foreach (PDFFieldValue f in FieldManagementForm.PDFFieldValueBindingSource)
{
if (f.Value == null) { MessageBox.Show("Sorry, but you need to make sure you "); }
if (f.Value.Contains("{{"))
{
string field = f.Value;
field = field.Replace("{{", "");
field = field.Replace("}}", "");
string NewFieldValue = row.Field<string>(field).ToString();
docfields.SetField(f.Field, f.CapsValue ? NewFieldValue.ToUpper() : NewFieldValue);
}
else
{
docfields.SetField(f.Field, f.CapsValue ? f.Value.ToUpper() : f.Value);
}
}
}
pdfStamper.Close();
pdfReader.Close();
FileInfo fi = new FileInfo(FilePath);
string ImagePath = Path.Combine(fi.Directory.FullName, Path.GetFileNameWithoutExtension(fi.Name) + ".jpg").ToString();
row["PhotoFilePathColumn"] = ImagePath;
byte[] pdfbytearray = File.ReadAllBytes(FilePath);
string pdfstring = Convert.ToBase64String(pdfbytearray, 0, pdfbytearray.Length);
PDFtoImage.Conversion.SaveJpeg(ImagePath, pdfstring);
PDFViewerPicture.ImageLocation = ImagePath;
}
}
private void LoadPDFFields()
{
FileInfo CertFile = new FileInfo(CertTemplateTextBox.Text);
if (!CertFile.Exists)
{
MessageBox.Show("Sorry your template not exist or you do not have access to it");
return;
}
PdfReader pdfReader = new PdfReader(CertFile.FullName);
AcroFields docfields = pdfReader.AcroFields;
ICollection<string> FieldKeys = docfields.Fields.Keys;
ValidPDFFile = ValidatePDFFile(CertFile.FullName);
if (ValidPDFFile)
{
FieldManagementForm.PDFFieldValueBindingSource.Clear();
foreach (var k in FieldKeys)
{
var val = new PDFFieldValue();
val.Field = k;
FieldManagementForm.PDFFieldValueBindingSource.Add(val);
}
}
}
private void PreviewPDF()
{
var row = ((DataRowView)UserListBox.SelectedItem).Row;
string FilePath = GeneratePathForPDF(row);
WritePDF(FilePath, row);
}
#endregion Main Methods
#region Events
private void FieldManagerLabel_Click(object sender, EventArgs e)
{
FieldManagementForm.Show();
}
private void LoadPdfButton_Click(object sender, EventArgs e)
{
PreviewPDF();
PreviewTabControl.SelectedTab = PDFPreviewTab;
}
private void OpenPDFTemplateDialogButton_Click(object sender, EventArgs e)
{
DialogResult? result = null;
if (!String.IsNullOrEmpty(CertTemplateTextBox.Text))
{
result = WarningOfResetFields("PDF");
}
if (result == DialogResult.Cancel)
{
return;
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF Files|*.pdf";
ofd.Multiselect = false;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (result != null && result == DialogResult.OK)
{
FieldManagementForm.PDFFieldValueBindingSource.Clear();
}
CertTemplateTextBox.Text = ofd.FileName;
LoadPDFFields();
}
}
private void OpenCertDropDialogButton_Click(object sender, EventArgs e)
{
CommonOpenFileDialog cofd = new CommonOpenFileDialog();
cofd.IsFolderPicker = true;
if (cofd.ShowDialog() == CommonFileDialogResult.Ok)
{
CertDropTextBox.Text = cofd.FileName;
}
}
private void UserListBox_DoubleClick(object sender, EventArgs e)
{
PreviewPDF();
UpdatePreviewEmailBody();
}
private void OpenCsvFileDialogButton_Click(object sender, EventArgs e)
{
if (!ValidPDFFile)
{
MessageBox.Show("Sorry, but you must first select a PDF file so we can load it's fields.");
return;
}
DialogResult? result = null;
if (!String.IsNullOrEmpty(CertTemplateTextBox.Text))
{
result = WarningOfResetFields("CSV");
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Delimited (Comma,Tab,Pipe)|*.csv;*.txt";
ofd.Multiselect = false;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (result != null && result == DialogResult.OK)
{
foreach (PDFFieldValue f in FieldManagementForm.PDFFieldValueBindingSource)
{
f.Value = null!;
}
}
UserCSVFileTextBox.Text = ofd.FileName;
ValidCSVFile = ValidateCSVFile(ofd.FileName);
CheckValidation();
VariablesAllowedListBox.DataSource = FieldManagementForm.CSVFieldsBindingSource;
FieldManagementForm.Show();
//VariablesAllowedListBox.DisplayMember = "Display";
//VariablesAllowedListBox.ValueMember = "Value";
}
}
private void GenerateAndEmailButton_Click(object sender, EventArgs e)
{
if (!CheckIfTableIsEmptyAndRespond()) { return; }
var result = MessageBox.Show($"Are you sure you want to generate and send {CSVDataTable.Rows.Count} E-Mails?", "E-Mail Confirmation", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
MessageBox.Show("Ok Generating");
}
}
private void GenerateNowButton_Click(object sender, EventArgs e)
{
DisableEnableAllControlsWhileProcessing();
if (!CheckIfTableIsEmptyAndRespond()) { return; }
try
{
foreach (DataRow row in CSVDataTable.Rows)
{
WritePDF(GeneratePathForPDF(row), row);
}
MessageBox.Show($"Certs have been generated and dropped in your cert folder{Environment.NewLine}{CertDropTextBox.Text}");
} catch( Exception ex)
{
}
DisableEnableAllControlsWhileProcessing();
}
private void DisableEnableAllControlsWhileProcessing()
{
if(ControlStates.Count == 0)
{
foreach (Control c in this.Controls)
{
ControlStates.Add(new ControlState() { Control = c, State = c.Enabled });
}
}
foreach (Control c in this.Controls)
{
c.Enabled = !c.Enabled;
}
}
private void HTMLBodyEditTextBox_TextChanged(object sender, EventArgs e)
{
UpdatePreviewEmailBody();
}
private void VariablesAllowedListBox_DoubleClick(object sender, EventArgs e)
{
string item = "";
if (VariablesAllowedListBox.SelectedItems.Count > 0)
{
item = VariablesAllowedListBox.SelectedItems[0].ToString()!;
}
HTMLBodyEditTextBox.Text = HTMLBodyEditTextBox.Text.Insert(HTMLBodyEditTextBox.SelectionStart, item);
}
#endregion Events
}
public class ControlState
{
public Control Control { get; set; }
public bool State { get; set; }
}
}