-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm1.cs
1639 lines (1393 loc) · 64.5 KB
/
Form1.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
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
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Windows.Forms;
using iText.Layout;
using iText.Layout.Element;
using System.Drawing.Imaging;
using iText.Kernel.Pdf;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Image;
using Topaz;
// Alias the namespaces to avoid ambiguity
using PdfImage = iText.Layout.Element.Image;
using DrawingImage = System.Drawing.Image;
using iText.Layout.Properties;
using iText.Kernel.Pdf.Canvas;
namespace SOFA_Generator
{
public partial class Form1 : Form
{
private bool isDrawing = false;
private Point lastPoint = Point.Empty;
private Bitmap signatureBitmap;
private string excelFilePath = @"\\lxez-fs-021v\18sfs\S 5\S-5B Pass & Registration(PA)\02-USFJ Form 4EJ\05 - Trackers\SOFA.xlsx"; // Default path for the Excel file
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
public Form1()
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
InitializeComponent();
signatureBitmap = new Bitmap(signaturePanel.Width, signaturePanel.Height);
signaturePanel.Paint += new PaintEventHandler(signaturePanel_Paint);
signaturePanel.MouseDown += new MouseEventHandler(signaturePanel_MouseDown);
signaturePanel.MouseMove += new MouseEventHandler(signaturePanel_MouseMove);
signaturePanel.MouseUp += new MouseEventHandler(signaturePanel_MouseUp);
btnSearch.Click += new EventHandler(this.btnSearch_Click);
statusComboBox.SelectedIndexChanged += new EventHandler(this.statusComboBox_SelectedIndexChanged);
motorcycleCheckBox.CheckedChanged += motorcycleCheckBox_CheckedChanged;
btnReset.Click += new EventHandler(this.btnReset_Click);
InitializeStampComboBox();
sigPlusNET1.SetTabletState(1);
sigPlusNET1.SetJustifyMode(0);
InitializeUnitComboBox();
HideFormFields();
}
private void Form1_Load(object sender, EventArgs e)
{
HideFormFields();
LoadIssuerNames();
}
private void HideFormFields()
{
lastNameTextBox.Visible = false;
firstNameTextBox.Visible = false;
permit1TextBox.Visible = false;
issue1DateTimePicker.Visible = false;
exp1DateTimePicker.Visible = false;
permit2TextBox.Visible = false;
issue2DateTimePicker.Visible = false;
exp2DateTimePicker.Visible = false;
signaturePanel.Visible = false;
btnSaveSignature.Visible = false;
btnRequestSignature.Visible = false;
btnGeneratePermitNumber.Visible = false;
msfTextBox.Visible = false;
catPaxComboBox.Visible = false;
autoJeepCheckBox.Visible = false;
motorcycleCheckBox.Visible = false;
dobDateTimePicker.Visible = false;
heightTextBox.Visible = false;
weightTextBox.Visible = false;
hairColorComboBox.Visible = false;
eyeColorComboBox.Visible = false;
restrictionsBox.Visible = false;
remarksBox.Visible = false;
issuerComboBox.Visible = false;
sexComboBox.Visible = false;
statusComboBox.Visible = false;
unitComboBox.Visible = false;
sigPlusNET1.Visible = false;
signaturegroupBox.Visible = false;
picturegroupBox.Visible = false;
stampComboBox.Visible = false;
// Also hide labels
sexLabel.Visible = false;
dobLabel.Visible = false;
heightLabel.Visible = false;
weightLabel.Visible = false;
hairColorLabel.Visible = false;
eyeColorLabel.Visible = false;
groupBox1.Visible = false;
groupBox2.Visible = false;
lastNameLabel.Visible = false;
rankLabel.Visible = false;
statusLabel.Visible = false;
firstNameLabel.Visible = false;
unitLabel.Visible = false;
remarksLabel.Visible = false;
catLabel.Visible = false;
issuerLabel.Visible = false;
stampLabel.Visible = false;
MSFlabel.Visible = false;
}
private void statusComboBox_SelectedIndexChanged(object? sender, EventArgs e)
{
// Safeguard: Ensure controls are initialized
if (statusComboBox == null || militaryRankComboBox == null || civilianRankComboBox == null || naLabel == null)
{
return;
}
// Hide all rank-related controls initially
militaryRankComboBox.Visible = false;
civilianRankComboBox.Visible = false;
naLabel.Visible = false;
// Show the appropriate control based on the selected status
switch (statusComboBox.SelectedItem?.ToString())
{
case "AD": // Active Duty
case "R/G": // Reserves/Guard
militaryRankComboBox.Visible = true;
break;
case "CIV": // Civilian
civilianRankComboBox.Visible = true;
break;
case "CTR": // Contractor
case "DEP": // Dependent
naLabel.Visible = true;
break;
}
}
private void InitializeUnitComboBox()
{
// Ensure the Excel file path is set
if (string.IsNullOrEmpty(excelFilePath))
{
MessageBox.Show("Please select an Excel file first.");
return;
}
FileInfo fileInfo = new FileInfo(excelFilePath);
try
{
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
// Get the "Defenders" worksheet
ExcelWorksheet defendersSheet = package.Workbook.Worksheets["Defenders"];
if (defendersSheet == null)
{
MessageBox.Show("The 'Defenders' sheet was not found in the Excel file.");
return;
}
// Clear the existing items in the ComboBox
unitComboBox.Items.Clear();
// Iterate through the rows in the Defenders sheet
int startRow = 2; // Assuming the first row is a header
for (int row = startRow; row <= defendersSheet.Dimension.End.Row; row++)
{
string unitName = defendersSheet.Cells[row, 2].Text; // Column 2 for unit names
if (!string.IsNullOrEmpty(unitName))
{
unitComboBox.Items.Add(unitName);
}
}
// Optionally, select the first item in the ComboBox if there are items
if (unitComboBox.Items.Count > 0)
{
unitComboBox.SelectedIndex = 0;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error loading units: {ex.Message}");
}
}
private void ShowFormFields(bool isExistingEntry)
{
ShowFormFields(isExistingEntry, signaturePanel);
}
private void ShowFormFields(bool isExistingEntry, Panel signaturePanel)
{
lastNameTextBox.Visible = true;
firstNameTextBox.Visible = true;
dobDateTimePicker.Visible = true;
heightTextBox.Visible = true;
weightTextBox.Visible = true;
hairColorComboBox.Visible = true;
eyeColorComboBox.Visible = true;
restrictionsBox.Visible = true;
remarksBox.Visible = true;
issuerComboBox.Visible = true;
sexComboBox.Visible = true;
permit1TextBox.Visible = true;
issue1DateTimePicker.Visible = true;
exp1DateTimePicker.Visible = true;
statusComboBox.Visible = true;
unitComboBox.Visible = true;
sigPlusNET1.Visible = true;
signaturegroupBox.Visible = true;
picturegroupBox.Visible = true;
stampComboBox.Visible = true;
// Show labels
sexLabel.Visible = true;
dobLabel.Visible = true;
heightLabel.Visible = true;
weightLabel.Visible = true;
hairColorLabel.Visible = true;
eyeColorLabel.Visible = true;
sexLabel.Visible = true;
rankLabel.Visible = true;
statusLabel.Visible = true;
firstNameLabel.Visible = true;
lastNameLabel.Visible = true;
unitLabel.Visible = true;
remarksLabel.Visible = true;
unitLabel.Visible = true;
issuerLabel.Visible = true;
stampLabel.Visible = true;
// Show Permit 1 GroupBox since it's used for both new and existing entries
groupBox1.Visible = true;
// Existing entry logic
if (isExistingEntry)
{
groupBox2.Visible = true;
permit2TextBox.Visible = true;
issue2DateTimePicker.Visible = true;
exp2DateTimePicker.Visible = true;
}
else
{
groupBox2.Visible = false;
}
btnSaveSignature.Visible = true;
btnRequestSignature.Visible = true;
btnGeneratePermitNumber.Visible = true;
signaturePanel.Visible = true;
autoJeepCheckBox.Visible = true;
motorcycleCheckBox.Visible = true;
msfTextBox.Visible = true;
UpdateMotorcycleFieldsVisibility();
}
private void UpdateMotorcycleFieldsVisibility()
{
bool isMotorcycleSelected = motorcycleCheckBox.Checked;
msfTextBox.Visible = isMotorcycleSelected;
catPaxComboBox.Visible = isMotorcycleSelected;
catLabel.Visible = isMotorcycleSelected;
MSFlabel.Visible = isMotorcycleSelected;
if (!isMotorcycleSelected)
{
msfTextBox.Clear();
catPaxComboBox.SelectedIndex = -1; // Clear the selection when not visible
}
}
private void ClearFormFields()
{
lastNameTextBox.Text = string.Empty;
firstNameTextBox.Text = string.Empty;
dodIdTextBox.Text = string.Empty;
unitComboBox.SelectedIndex = -1;
permit1TextBox.Text = string.Empty;
issue1DateTimePicker.Value = DateTime.Today;
exp1DateTimePicker.Value = DateTime.Today;
permit2TextBox.Text = string.Empty;
issue2DateTimePicker.Value = DateTime.Today;
exp2DateTimePicker.Value = DateTime.Today;
// New fields
dobDateTimePicker.Value = DateTime.Today;
heightTextBox.Text = string.Empty;
weightTextBox.Text = string.Empty;
hairColorComboBox.SelectedIndex = -1;
eyeColorComboBox.SelectedIndex = -1;
restrictionsBox.Checked = false;
}
private void InitializeStampComboBox()
{
stampComboBox.Items.Clear();
stampComboBox.Items.AddRange(new object[] { "", "Student Driver", "On Base Only", "TDY", "Limited" });
stampComboBox.SelectedIndex = 0; // Optional: Set default value
}
private void btnSearch_Click(object? sender, EventArgs e)
{
string dodId = dodIdTextBox.Text.Trim();
if (string.IsNullOrEmpty(dodId))
{
MessageBox.Show("Please enter a DoD ID.");
return;
}
if (!IsValidDoDId(dodId))
{
MessageBox.Show("Please enter a valid 10-digit DoD ID.");
return;
}
// Always reset the form before populating new data
ResetForm();
// Check if the Excel file exists before searching
if (!File.Exists(excelFilePath))
{
MessageBox.Show("Excel file not found. Please use the 'SOFA Database' button to select the correct file.");
return;
}
var customerData = GetCustomerDataFromExcel(dodId);
if (customerData != null)
{
PopulateFormWithExistingData(customerData);
ShowFormFields(isExistingEntry: true);
MessageBox.Show("Customer data found.");
}
else
{
dodIdTextBox.Text = dodId; // Keep the DoD ID in the textbox
ShowFormFields(isExistingEntry: false);
MessageBox.Show("DoD ID not found. Please enter new data.");
}
}
private Dictionary<string, string> GetCustomerDataFromExcel(string dodId)
{
try
{
// Check if the file exists first
if (!File.Exists(excelFilePath))
{
MessageBox.Show("Excel file not found. Please select the correct file using the 'SOFA Database' button.");
return null!;
}
FileInfo fileInfo = new FileInfo(excelFilePath);
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
if (worksheet == null)
{
MessageBox.Show("The required worksheet is not available in the Excel file. Please check the file format.");
return null!;
}
var row = worksheet.Cells["F:F"].FirstOrDefault(c => c.Text == dodId); // Column F for "DoD ID #"
if (row != null)
{
int rowIndex = row.Start.Row;
var data = new Dictionary<string, string>
{
{ "Last Name", worksheet.Cells[rowIndex, 1].Text },
{ "First Name", worksheet.Cells[rowIndex, 2].Text },
{ "Status", worksheet.Cells[rowIndex, 3].Text },
{ "Rank", worksheet.Cells[rowIndex, 4].Text },
{ "Unit", worksheet.Cells[rowIndex, 5].Text },
{ "DoD ID #", worksheet.Cells[rowIndex, 6].Text },
{ "Permit #1", worksheet.Cells[rowIndex, 7].Text },
{ "Issue 1", worksheet.Cells[rowIndex, 8].Text },
{ "Exp 1", worksheet.Cells[rowIndex, 9].Text },
{ "Permit #2", worksheet.Cells[rowIndex, 10].Text },
{ "Issue 2", worksheet.Cells[rowIndex, 11].Text },
{ "Exp 2", worksheet.Cells[rowIndex, 12].Text },
{ "MSF", worksheet.Cells[rowIndex, 13].Text },
{ "CAT/PAX", worksheet.Cells[rowIndex, 14].Text },
{ "Sex", worksheet.Cells[rowIndex, 15].Text },
{ "DOB", worksheet.Cells[rowIndex, 16].Text },
{ "Height", worksheet.Cells[rowIndex, 17].Text },
{ "Weight", worksheet.Cells[rowIndex, 18].Text },
{ "HairColor", worksheet.Cells[rowIndex, 19].Text },
{ "EyeColor", worksheet.Cells[rowIndex, 20].Text },
{ "GlassesContacts", worksheet.Cells[rowIndex, 21].Text },
{ "Remarks", worksheet.Cells[rowIndex, 22].Text },
{ "Stamp", worksheet.Cells[rowIndex, 23].Text } // Column 23 for "Stamp"
};
return data;
}
else
{
MessageBox.Show("DoD ID not found in the Excel file.");
}
}
}
catch (FileNotFoundException ex)
{
MessageBox.Show($"Error: Excel file not found. {ex.Message}");
}
catch (IndexOutOfRangeException ex)
{
MessageBox.Show($"Error: Worksheet not found or index out of range. {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"An unexpected error occurred: {ex.Message}");
}
return null!;
}
private bool IsValidDoDId(string dodId)
{
// Trim the DoD ID to remove any leading/trailing spaces
dodId = dodId.Trim();
// Check the length of the DoD ID
if (dodId.Length != 10)
{
MessageBox.Show($"Invalid length: {dodId.Length}. DoD ID must be 10 digits long.");
return false;
}
// Attempt to parse the DoD ID as a number
if (!long.TryParse(dodId, out long idNumber))
{
MessageBox.Show($"Invalid number: '{dodId}'. Could not parse as a number.");
return false;
}
// Ensure the number is within the valid range for a 10-digit DoD ID
if (idNumber < 1000000000 || idNumber > 9999999999)
{
MessageBox.Show($"Number out of range: {idNumber}. Valid range is 1000000000 to 9999999999.");
return false;
}
return true;
}
private void PopulateFormWithExistingData(Dictionary<string, string> data)
{
// Reset the form to ensure no residual data is left from previous entries
ResetForm();
// Populate basic fields
lastNameTextBox.Text = data["Last Name"];
firstNameTextBox.Text = data["First Name"];
dodIdTextBox.Text = data["DoD ID #"];
// Load Permit #1 and its associated fields
permit1TextBox.Text = data["Permit #1"];
if (DateTime.TryParse(data["Issue 1"], out DateTime issue1Date))
{
issue1DateTimePicker.Value = issue1Date;
}
if (DateTime.TryParse(data["Exp 1"], out DateTime exp1Date))
{
exp1DateTimePicker.Value = exp1Date;
}
// If Permit #2 exists, load it into the Permit #2 fields
if (!string.IsNullOrEmpty(data["Permit #2"]))
{
permit2TextBox.Text = data["Permit #2"];
if (DateTime.TryParse(data["Issue 2"], out DateTime issue2Date))
{
issue2DateTimePicker.Value = issue2Date;
}
if (DateTime.TryParse(data["Exp 2"], out DateTime exp2Date))
{
exp2DateTimePicker.Value = exp2Date;
}
// Show Permit #2 fields if data exists
groupBox2.Visible = true;
}
else
{
// Hide Permit #2 fields if no data is available
groupBox2.Visible = false;
}
// Populate Status and Rank
string status = data["Status"].Trim();
statusComboBox.SelectedItem = statusComboBox.Items.Cast<string>().FirstOrDefault(item => item == status);
string rank = data["Rank"].Trim();
switch (status)
{
case "CIV":
civilianRankComboBox.Visible = true;
civilianRankComboBox.SelectedItem = civilianRankComboBox.Items.Cast<string>().FirstOrDefault(item => item == rank);
break;
case "AD":
case "R/G":
case "CTR":
militaryRankComboBox.Visible = true;
militaryRankComboBox.SelectedItem = militaryRankComboBox.Items.Cast<string>().FirstOrDefault(item => item == rank);
break;
default:
naLabel.Visible = true;
break;
}
// Populate Unit
string unit = data["Unit"].Trim();
unitComboBox.SelectedItem = unitComboBox.Items.Cast<string>().FirstOrDefault(item => item.Trim() == unit);
// Populate Sex
string sex = data["Sex"].Trim();
sexComboBox.SelectedItem = sexComboBox.Items.Cast<string>().FirstOrDefault(item => item == sex);
// Populate Stamp from the Excel file (column 23)
string stamp = data["Stamp"].Trim();
stampComboBox.SelectedItem = stampComboBox.Items.Cast<string>().FirstOrDefault(item => item == stamp);
// Automatically check "Auto/Jeep" because it's implied when customer data is found
autoJeepCheckBox.Checked = true; // Since "Auto/Jeep" is always implied
// Check if MSF is present and populate msfTextBox accordingly
if (data.ContainsKey("MSF") && !string.IsNullOrWhiteSpace(data["MSF"]))
{
// MSF field has valid data
msfTextBox.Text = data["MSF"];
msfTextBox.Visible = true;
motorcycleCheckBox.Checked = true; // Only check if MSF data is valid
// Make the CAT/PAX fields visible and select the matching item
catPaxComboBox.Visible = true;
catLabel.Visible = true;
string catPaxValue = data["CAT/PAX"];
var matchingItem = catPaxComboBox.Items.Cast<string>().FirstOrDefault(item => item == catPaxValue);
if (matchingItem != null)
{
catPaxComboBox.SelectedItem = matchingItem;
}
else
{
catPaxComboBox.SelectedIndex = -1; // Clear the selection if no match is found
}
}
else
{
// MSF field is empty or doesn't exist, so uncheck Motorcycle and hide fields
motorcycleCheckBox.Checked = false;
msfTextBox.Visible = false;
catPaxComboBox.Visible = false;
catLabel.Visible = false;
}
// Populate other fields like DOB, Height, Weight, etc.
if (DateTime.TryParse(data["DOB"], out DateTime dobDate))
{
dobDateTimePicker.Value = dobDate;
}
heightTextBox.Text = data["Height"];
weightTextBox.Text = data["Weight"];
hairColorComboBox.SelectedItem = data["HairColor"];
eyeColorComboBox.SelectedItem = data["EyeColor"];
restrictionsBox.Checked = data["GlassesContacts"] == "True";
// Show form fields relevant to an existing entry
ShowFormFields(isExistingEntry: true);
}
private void signaturePanel_MouseDown(object? sender, MouseEventArgs e)
{
isDrawing = true;
lastPoint = e.Location;
}
private void LoadIssuerNames()
{
// Ensure the Excel file path is set
if (string.IsNullOrEmpty(excelFilePath))
{
MessageBox.Show("Please select an Excel file first.");
return;
}
FileInfo fileInfo = new FileInfo(excelFilePath);
// Open the Excel package
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
// Get the "Defenders" worksheet
ExcelWorksheet defendersSheet = package.Workbook.Worksheets["Defenders"];
if (defendersSheet == null)
{
MessageBox.Show("The 'Defenders' sheet was not found in the Excel file.");
return;
}
// Clear the existing items in the ComboBox
issuerComboBox.Items.Clear();
// Iterate through the rows in the Defenders sheet
int startRow = 2; // Assuming the first row is a header
for (int row = startRow; row <= defendersSheet.Dimension.End.Row; row++)
{
string defenderName = defendersSheet.Cells[row, 1].Text; // Column 1 for Defender names
if (!string.IsNullOrEmpty(defenderName))
{
issuerComboBox.Items.Add(defenderName);
}
}
if (issuerComboBox.Items.Count > 0)
{
issuerComboBox.SelectedIndex = 0; // Optionally select the first item
}
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = Path.GetDirectoryName(excelFilePath);
openFileDialog.Filter = "Excel Files (*.xlsx)|*.xlsx|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the path of the selected file
excelFilePath = openFileDialog.FileName;
MessageBox.Show($"Excel file path set to: {excelFilePath}", "File Selected", MessageBoxButtons.OK, MessageBoxIcon.Information);
// Reload the units and issuers after selecting the new file
InitializeUnitComboBox(); // Reload unit names from the new file
LoadIssuerNames(); // Reload issuer names from the new file
}
}
}
private void ResetForm()
{
// Temporarily detach the event handler to avoid triggering during reset
statusComboBox.SelectedIndexChanged -= statusComboBox_SelectedIndexChanged;
// Clear all textboxes, comboboxes, and other input fields
lastNameTextBox.Clear();
firstNameTextBox.Clear();
permit1TextBox.Clear();
permit2TextBox.Clear();
dobDateTimePicker.Value = DateTime.Today.AddYears(-16); // Default DOB to 16 years ago
issue1DateTimePicker.Value = DateTime.Today;
exp1DateTimePicker.Value = DateTime.Today.AddDays(90); // Default expiry date
issue2DateTimePicker.Value = DateTime.Today;
exp2DateTimePicker.Value = DateTime.Today.AddDays(90);
heightTextBox.Clear();
weightTextBox.Clear();
hairColorComboBox.SelectedIndex = -1;
eyeColorComboBox.SelectedIndex = -1;
sexComboBox.SelectedIndex = -1;
remarksBox.Clear();
stampComboBox.SelectedIndex = -1;
restrictionsBox.Checked = false;
sigPlusNET1.ClearTablet();
motorcycleCheckBox.Checked = false;
autoJeepCheckBox.Checked = false;
// Reset rank-related controls and visibility
militaryRankComboBox.SelectedIndex = -1;
civilianRankComboBox.SelectedIndex = -1;
militaryRankComboBox.Visible = false;
civilianRankComboBox.Visible = false;
naLabel.Visible = false;
// Reset unit and status combo boxes
unitComboBox.SelectedIndex = -1;
statusComboBox.SelectedIndex = -1;
msfTextBox.Clear();
catPaxComboBox.SelectedIndex = -1;
catPaxComboBox.Visible = false;
catLabel.Visible = false;
// Reattach the event handler
statusComboBox.SelectedIndexChanged += statusComboBox_SelectedIndexChanged;
}
private void btnReset_Click(object? sender, EventArgs e)
{
// Call the ResetForm method when the Reset button is clicked
ResetForm();
}
private void signaturePanel_MouseMove(object? sender, MouseEventArgs e)
{
if (isDrawing)
{
using (Graphics g = Graphics.FromImage(signatureBitmap))
{
g.DrawLine(Pens.Black, lastPoint, e.Location);
}
lastPoint = e.Location;
signaturePanel.Invalidate();
}
}
private void signaturePanel_MouseUp(object? sender, MouseEventArgs e)
{
isDrawing = false;
}
private void signaturePanel_Paint(object? sender, PaintEventArgs e)
{
e.Graphics.DrawImage(signatureBitmap, Point.Empty);
}
private void btnSaveSignature_Click(object sender, EventArgs e)
{
try
{
// Step 1: Capture the signature and save it
using (Bitmap bitmap = new Bitmap(signaturePanel.Width, signaturePanel.Height))
{
signaturePanel.DrawToBitmap(bitmap, new Rectangle(0, 0, signaturePanel.Width, signaturePanel.Height));
// Save the signature image to a temporary file
string filePath = Path.Combine(Path.GetTempPath(), "signatureCapture.jpg");
bitmap.Save(filePath, ImageFormat.Jpeg);
// Step 2: Set the paths for the PDF
string pdfTemplatePath = Path.Combine(baseDir, "Resources", "PDF", "Form4EJ.pdf");
string outputPdfPath = Path.Combine(baseDir, "Resources", "PDF", "Form4EJ_Filled.pdf");
// Step 3: Prepare form data (for saving to both Excel and PDF)
string unitValue = unitComboBox.SelectedItem?.ToString()?.Trim() ?? "";
var formData = new Dictionary<string, string>
{
// PDF field names
{ "NAME", lastNameTextBox.Text + ", " + firstNameTextBox.Text }, // For PDF
{ "UNIT", unitValue }, // PDF field uses "UNIT"
{ "SEX", sexComboBox.SelectedItem?.ToString() ?? "" },
{ "DOB", dobDateTimePicker.Value.ToShortDateString() },
{ "HEIGHT", heightTextBox.Text },
{ "WEIGHT", weightTextBox.Text },
{ "HAIRCOLOR", hairColorComboBox.SelectedItem?.ToString() ?? "" },
{ "EYECOLOR", eyeColorComboBox.SelectedItem?.ToString() ?? "" },
{ "ISSUER", issuerComboBox.SelectedItem?.ToString() ?? "" },
{ "AUTO/JEEP", autoJeepCheckBox.Checked ? "Yes" : "Off" },
{ "MOTORCYCLE", motorcycleCheckBox.Checked ? "Yes" : "Off" },
{ "GLASSES/CONTACTS", restrictionsBox.Checked ? "Yes" : "No" },
{ "CAT/PAX", catPaxComboBox.SelectedItem?.ToString() ?? "" },
{ "Remarks", remarksBox.Text },
{ "MSF", msfTextBox.Text },
// Excel fields
{ "Last Name", lastNameTextBox.Text }, // For Excel
{ "First Name", firstNameTextBox.Text }, // For Excel
{ "DoD ID #", dodIdTextBox.Text },
{ "Status", statusComboBox.SelectedItem?.ToString() ?? "" },
{ "Stamp", stampComboBox.SelectedItem?.ToString() ?? "" },
{ "Rank", GetSelectedRank() }, // Excel field for rank
{ "Unit", unitValue }, // Excel field uses "Unit"
};
FileInfo fileInfo = new FileInfo(excelFilePath);
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
if (worksheet.Dimension == null || worksheet.Dimension.End.Row == 0)
{
MessageBox.Show("The worksheet is empty or not properly loaded.");
return;
}
int rowIndex = -1;
// Find the row by DoD ID
for (int i = 2; i <= worksheet.Dimension.End.Row; i++)
{
if (worksheet.Cells[i, 6].Text == formData["DoD ID #"]) // Column 6 for "DoD ID #"
{
rowIndex = i;
break;
}
}
// If not found, create a new row
if (rowIndex == -1)
{
rowIndex = worksheet.Dimension.End.Row + 1;
}
// Save or update all Excel data (including permit data)
worksheet.Cells[rowIndex, 1].Value = formData["Last Name"];
worksheet.Cells[rowIndex, 2].Value = formData["First Name"];
worksheet.Cells[rowIndex, 3].Value = formData["Status"];
worksheet.Cells[rowIndex, 4].Value = formData["Rank"];
worksheet.Cells[rowIndex, 5].Value = formData["Unit"];
worksheet.Cells[rowIndex, 6].Value = formData["DoD ID #"];
worksheet.Cells[rowIndex, 15].Value = formData["SEX"];
worksheet.Cells[rowIndex, 16].Value = formData["DOB"];
worksheet.Cells[rowIndex, 17].Value = formData["HEIGHT"];
worksheet.Cells[rowIndex, 18].Value = formData["WEIGHT"];
worksheet.Cells[rowIndex, 19].Value = formData["HAIRCOLOR"];
worksheet.Cells[rowIndex, 20].Value = formData["EYECOLOR"];
worksheet.Cells[rowIndex, 21].Value = formData["GLASSES/CONTACTS"];
// Check if Permit #1 is filled
string existingPermit1 = worksheet.Cells[rowIndex, 7].Text;
if (string.IsNullOrEmpty(existingPermit1))
{
// Permit #1 is empty, so save Permit #1 data
worksheet.Cells[rowIndex, 7].Value = permit1TextBox.Text;
worksheet.Cells[rowIndex, 8].Value = issue1DateTimePicker.Value.ToShortDateString();
worksheet.Cells[rowIndex, 9].Value = exp1DateTimePicker.Value.ToShortDateString();
formData["PERMIT"] = permit1TextBox.Text ?? ""; // Save Permit #1 number
formData["ISSUE"] = issue1DateTimePicker.Value.ToShortDateString(); // Use Permit #1 issue date
formData["Exp"] = exp1DateTimePicker.Value.ToShortDateString(); // Set Permit #1 expiration date
}
else
{
// Permit #1 is filled, so overwrite Permit #2
worksheet.Cells[rowIndex, 10].Value = permit2TextBox.Text ?? "";
worksheet.Cells[rowIndex, 11].Value = issue2DateTimePicker.Value.ToShortDateString();
worksheet.Cells[rowIndex, 12].Value = exp2DateTimePicker.Value.ToShortDateString();
formData["PERMIT"] = permit2TextBox.Text ?? ""; // Save Permit #2 number
formData["ISSUE"] = issue2DateTimePicker.Value.ToShortDateString(); // Use Permit #2 issue date
formData["Exp"] = exp2DateTimePicker.Value.ToShortDateString(); // Set Permit #2 expiration date
}
// Save other optional fields (MSF, remarks, etc.)
worksheet.Cells[rowIndex, 13].Value = formData["MSF"];
worksheet.Cells[rowIndex, 14].Value = formData["CAT/PAX"];
worksheet.Cells[rowIndex, 22].Value = formData["Remarks"];
worksheet.Cells[rowIndex, 23].Value = formData["Stamp"];
// Save the Excel file
package.Save();
}
// Step 6: Generate the PDF
CompletePdfWorkflow(pdfTemplatePath, outputPdfPath, formData, filePath);
// Step 7: Automatically print the filled PDF to the default printer
PrintPdf(outputPdfPath);
// Confirmation message
MessageBox.Show("PDF generated, data saved, and sent to printer!");
}
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred while saving the signature or generating the PDF: {ex.Message}");
}
}
// Method to print the PDF
private void PrintPdf(string pdfFilePath)
{
try
{
// Path to Adobe Reader executable (change this if it's installed elsewhere)
string adobeReaderPath = @"C:\Program Files\Adobe\Acrobat DC\Acrobat\Acrobat.exe";
// Check if Adobe Reader is installed
if (!File.Exists(adobeReaderPath))
{
MessageBox.Show("Adobe Reader is not installed or not found at the specified path.");
return;
}
// Use Adobe Reader to print the PDF
Process printProcess = new Process();
printProcess.StartInfo = new ProcessStartInfo
{
FileName = adobeReaderPath,
Arguments = $"/t \"{pdfFilePath}\"", // /t prints the file to the default printer
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
printProcess.Start();
// Optionally, wait for the process to complete printing
printProcess.WaitForExit(10000); // Wait for 10 seconds for printing to complete
printProcess.Close();
}
catch (Exception ex)
{
MessageBox.Show($"Error while printing the PDF: {ex.Message}");
}
}
private void InitializeCatPaxComboBox()
{
catPaxComboBox.Items.Clear();
catPaxComboBox.Items.Add("Cat 1: 50cc or less");
catPaxComboBox.Items.Add("Cat 2: Motorcycles 125cc or less");
catPaxComboBox.Items.Add("Cat 3: Motorcycles 400cc or less");
catPaxComboBox.Items.Add("Cat 4: Motorcycles 750cc or less");
catPaxComboBox.Items.Add("Cat 5: Motorcycles over 750cc");
// Optionally, select the first item as default
if (catPaxComboBox.Items.Count > 0)
{
catPaxComboBox.SelectedIndex = 0;
}
}
private void SaveDataToExcel(Dictionary<string, string> data)
{
FileInfo fileInfo = new FileInfo(excelFilePath);
if (IsFileLocked(fileInfo))
{
MessageBox.Show("The Excel file is currently open in another application. Please close it and try again.");
return;
}
try
{
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
// Ensure the worksheet has data
if (worksheet.Dimension == null || worksheet.Dimension.End.Row == 0)
{
MessageBox.Show("The Excel sheet is empty or has no header row.");
return;
}
int rowIndex = -1;
// Search for the row by matching the "DoD ID #" field
for (int i = 2; i <= worksheet.Dimension.End.Row; i++) // Assuming row 1 is headers
{
if (worksheet.Cells[i, 6].Text == data["DoD ID #"]) // Column 6 for "DoD ID #"
{
rowIndex = i;
break;
}
}
// If not found, add a new row
if (rowIndex == -1)
{
rowIndex = worksheet.Dimension.End.Row + 1;
}
// Save **all** the customer data (for both new and existing rows)
worksheet.Cells[rowIndex, 1].Value = data["Last Name"];
worksheet.Cells[rowIndex, 2].Value = data["First Name"];
worksheet.Cells[rowIndex, 3].Value = data["Status"];
worksheet.Cells[rowIndex, 4].Value = data["Rank"];
worksheet.Cells[rowIndex, 5].Value = data["Unit"];
worksheet.Cells[rowIndex, 6].Value = data["DoD ID #"];
// Save Permit #1 details
worksheet.Cells[rowIndex, 7].Value = data["PERMIT"]; // Permit #1
worksheet.Cells[rowIndex, 8].Value = data["ISSUE"]; // Issue 1
worksheet.Cells[rowIndex, 9].Value = data["Exp"]; // Exp 1
// Save Permit #2 fields if available