-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
534 lines (477 loc) · 20 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
534 lines (477 loc) · 20 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
// Copyright © 2016-2022 ASM-SW
//asmeyers@outlook.com https://github.com/asm-sw
using Microsoft.VisualBasic.FileIO;
using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
namespace EmailWithAttachedFile
{
enum MsgStatus
{
NotSent=0,
Sent,
Error,
NoEmailAddress
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IDisposable
{
public MainWindow()
{
InitializeComponent();
ConfigurationEmailWAF.DeSerialize(m_configuration.ConfigFileName, ref m_configuration);
textFromEmail.Text = m_configuration.FromEmail;
textSmtpServer.Text = m_configuration.SmtpServer;
textSmtpPort.Text = m_configuration.SmtpPort.ToString();
checkSmtpEnableSsl.IsChecked = m_configuration.SmtpEnabledSSL;
textMessageTemplateFileName.Text = m_configuration.TemplateFileName;
textInputName.Text = m_configuration.InputFileName;
textAdditionEmailName.Text = m_configuration.AdditionEmailAddressFileName;
textMailSubject.Text = m_configuration.MailSubject;
}
/// <summary>
/// This object is used to pass result status from the background worker thread by the ReportProgress method
/// </summary>
class ResultObject
{
public ResultObject()
{
MaxCount = 0;
CountComplete = 0;
NameComplete = string.Empty;
ErrorMessage = string.Empty;
IsOk = true;
}
public int MaxCount { get; set; } // Number of emails being sent
public int CountComplete { get; set; } // Number of emails completed
public string NameComplete { get; set; } // Name of the last email completed
public string ErrorMessage { get; set; } // Error message if there was an issue
public bool IsOk { get; set; } // false indicates there was an error
}
private ConfigurationEmailWAF m_configuration = new ConfigurationEmailWAF();
private BackgroundWorker m_bgWorker = new BackgroundWorker();
private readonly EmailSender m_emailSender = new EmailSender();
private string m_outputFileName = string.Empty;
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
GetValuesFromForm();
if (CheckConfiguration())
{
buttonStart.IsEnabled = false;
buttonStop.IsEnabled = true;
listLog.Items.Clear();
StartupBackgroudWorker();
}
}
/// <summary>
/// reads values from the form (user input) and puts them into the configuration object
/// </summary>
private void GetValuesFromForm()
{
m_configuration.FromEmail = textFromEmail.Text;
m_configuration.SmtpServer = textSmtpServer.Text;
int.TryParse(textSmtpPort.Text, out int port);
m_configuration.SmtpPort = port;
m_configuration.SmtpEnabledSSL = (bool)checkSmtpEnableSsl.IsChecked;
m_configuration.Password = passwordBox.SecurePassword;
m_configuration.TemplateFileName = textMessageTemplateFileName.Text;
m_configuration.InputFileName = textInputName.Text;
m_configuration.MailSubject = textMailSubject.Text;
m_configuration.AdditionEmailAddressFileName = textAdditionEmailName.Text;
}
/// <summary>
/// Checks that the user input is OK. Puts up a message box on error
/// </summary>
/// <returns>false if there was an error</returns>
private bool CheckConfiguration()
{
bool isOk = true;
StringBuilder errMsg = new StringBuilder("ERROR:\n");
isOk &= CheckString(m_configuration.FromEmail, "FromEmail", ref errMsg);
isOk &= CheckString(m_configuration.SmtpServer, "SMTP Server", ref errMsg);
if (m_configuration.SmtpPort < 1 || m_configuration.SmtpPort > 65535)
{
errMsg.AppendLine("\tSMTP Port number must be 1 to 65535");
isOk = false;
}
if (m_configuration.Password.Length < 1)
{
errMsg.AppendLine("\tPassword not entered");
isOk = false;
}
isOk &= CheckFile(m_configuration.TemplateFileName, "Template File", ref errMsg);
isOk &= CheckFile(m_configuration.InputFileName, "Input File", ref errMsg);
if (string.IsNullOrWhiteSpace(m_configuration.AdditionEmailAddressFileName))
{
if (MessageBox.Show("Do you wish to continue without an addtional email address file?", "Continue?", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
return false;
}
else
isOk &= CheckFile(m_configuration.AdditionEmailAddressFileName, "Additional Email Addresses", ref errMsg);
if (!isOk)
MessageBox.Show(errMsg.ToString());
return isOk;
}
/// <summary>
/// Checks if a file exists.
/// </summary>
/// <param name="fileName">name of file</param>
/// <param name="name">user friendly name to put in error message</param>
/// <param name="errMsg">string builder for error message. Message are appended.</param>
/// <returns>true if OK</returns>
private bool CheckFile(string fileName, string name, ref StringBuilder errMsg)
{
bool isOk = true;
if (!CheckString(fileName, name, ref errMsg))
{
isOk = false;
}
else if (!File.Exists(fileName))
{
errMsg.AppendFormat("\t{0} file \"{1}\" does not exist.\n", name, fileName);
isOk = false;
}
return isOk;
}
/// <summary>
/// Checks to see if a string is null or whitespace.
/// </summary>
/// <param name="value">string to check</param>
/// <param name="name">user friendly name to put in error message</param>
/// <param name="errMsg">string builder for error message. Message are appended.</param>
/// <returns>true if OK</returns>
private bool CheckString(string value, string name, ref StringBuilder errMsg)
{
if (string.IsNullOrWhiteSpace(value))
{
errMsg.AppendFormat("\t{0} is empty.\n", name);
return false;
}
return true;
}
/// <summary>
/// Creates and setsups backgroud worker threader. Inits mail sender.
/// </summary>
private void StartupBackgroudWorker()
{
progressBar.Value = 0;
progressText.Content = string.Empty;
if (!m_emailSender.Init(ref m_configuration, out StringBuilder errMsg))
{
MessageBox.Show(errMsg.ToString());
return;
}
m_bgWorker = new BackgroundWorker
{
WorkerReportsProgress = true
};
m_bgWorker.DoWork += Worker_DoWork;
m_bgWorker.ProgressChanged += Worker_ProgressChanged;
m_bgWorker.RunWorkerCompleted += Worker_RunWorkerCompleted;
m_bgWorker.WorkerSupportsCancellation = true;
m_bgWorker.RunWorkerAsync(null);
}
/// <summary>
/// Background worker thread. Reads the input file. Sends email to each row in the file.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
AdditionalEmailAddrs addionalEmailAddrs= new AdditionalEmailAddrs();
StringBuilder msgParseAdditionalEmailAddress = new StringBuilder();
ResultObject resParseAdditionalEmailAddress = new ResultObject
{
NameComplete = string.Empty
};
if (!string.IsNullOrWhiteSpace(m_configuration.AdditionEmailAddressFileName))
{
// skipping this if the filename hasn't been filled in.
// There is an earlier check to see if users is OK with not adding additional email addrs
if (addionalEmailAddrs.ReadAdditionalEmailAddrFile(m_configuration.AdditionEmailAddressFileName, ref msgParseAdditionalEmailAddress))
{
resParseAdditionalEmailAddress.IsOk = false;
resParseAdditionalEmailAddress.ErrorMessage = "Parsed additional email addresses file: " + m_configuration.AdditionEmailAddressFileName;
}
else
{
resParseAdditionalEmailAddress.IsOk = false;
resParseAdditionalEmailAddress.ErrorMessage = msgParseAdditionalEmailAddress.ToString();
(sender as BackgroundWorker).ReportProgress(0, resParseAdditionalEmailAddress);
e.Result = resParseAdditionalEmailAddress; return;
}
e.Result = resParseAdditionalEmailAddress;
(sender as BackgroundWorker).ReportProgress(0, resParseAdditionalEmailAddress);
}
ReadInputFile(out DataTable inputData);
if (m_bgWorker.CancellationPending)
return;
inputData.Columns.Add("Status", typeof(string));
inputData.Columns.Add("Message", typeof(string));
foreach (DataRow row in inputData.Rows)
{
row["Status"] = MsgStatus.NotSent.ToString();
row["Message"] = string.Empty;
}
ResultObject results = new ResultObject
{
MaxCount = inputData.Rows.Count,
CountComplete = 0
};
foreach (DataRow row in inputData.Rows)
{
if (m_bgWorker.CancellationPending)
{
e.Cancel = true;
break;
}
if (string.IsNullOrWhiteSpace(row["Email"].ToString()))
{
results.IsOk = false;
results.ErrorMessage = "Email address is blank";
row["Status"] = MsgStatus.NoEmailAddress.ToString();
row["Message"] = results.ErrorMessage;
}
else
{
// send the email
string emailAddr = row["Email"].ToString();
if (addionalEmailAddrs.GetAddtionalEmailAddresses(emailAddr, out string emailAddrAddtional))
emailAddr = emailAddrAddtional;
results.IsOk = m_emailSender.SendMail(row["Name"].ToString(), emailAddr, row["FileName"].ToString(), out string errMsg);
results.ErrorMessage = errMsg;
if (results.IsOk)
{
row["Status"] = MsgStatus.Sent.ToString();
}
else
{
row["Status"] = MsgStatus.Error.ToString();
row["Message"] = results.ErrorMessage.Replace('\n', ';');
}
}
results.NameComplete = row["Name"].ToString();
++results.CountComplete;
int progressPercentage = Convert.ToInt32(((double)results.CountComplete / results.MaxCount) * 100);
e.Result = results;
(sender as BackgroundWorker).ReportProgress(progressPercentage, results);
}
// write out results file
m_outputFileName = Path.Combine(Path.GetDirectoryName(m_configuration.InputFileName),
Path.GetFileNameWithoutExtension(m_configuration.InputFileName)) + "out.csv";
using (System.IO.StreamWriter file = new System.IO.StreamWriter(m_outputFileName))
{
file.Write(inputData.ToCSV());
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
if (e.UserState is ResultObject results)
{
if (string.IsNullOrEmpty(results.NameComplete))
Log(results.ErrorMessage);
else
{
progressText.Content = string.Format("{0} of {1} complete", results.CountComplete, results.MaxCount);
if (results.IsOk)
Log("Sent: " + results.NameComplete);
else
Log("Not Sent: " + results.NameComplete + "\n\t" + results.ErrorMessage);
}
}
}
private void Log(string msg)
{
listLog.Items.Add(msg);
listLog.Items.MoveCurrentToLast();
listLog.ScrollIntoView(listLog.Items.CurrentItem);
}
void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Log("************ DONE *********************");
Log("Check results in: " + m_outputFileName);
Log("***************************************");
buttonStop.IsEnabled = false;
buttonStart.IsEnabled = true;
}
private void ButtonMessageTemplate_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
{
// Set filter for file extension and default file extension
DefaultExt = ".txt",
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*"
};
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
textMessageTemplateFileName.Text = filename;
}
}
/// <summary>
/// Checks to see if input is an integer
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static bool IsInteger(string text)
{
Regex regex = new Regex("[0-9]+");
return regex.IsMatch(text);
}
/// <summary>
/// limit input to a integer during paste event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void IntegerOnlyPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsInteger(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
/// <summary>
/// limit input to an integer during text entry
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void IntegerOnly(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsInteger(e.Text);
}
private void ButtonInputFile_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
{
// Set filter for file extension and default file extension
DefaultExt = ".csv",
Filter = "CSV Files (*.txt)|*.csv|All files (*.*)|*.*"
};
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
textInputName.Text = filename;
}
}
private void ButtonInputAdditionalEmailFile_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
{
// Set filter for file extension and default file extension
DefaultExt = ".csv",
Filter = "CSV Files (*.txt)|*.csv|All files (*.*)|*.*"
};
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
textAdditionEmailName.Text = filename;
}
}
/// <summary>
/// Parser for reading the CSV input file.
/// </summary>
/// <param name="inputData">DataTabel containing the read in data</param>
private void ReadInputFile(out DataTable inputData)
{
inputData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(m_configuration.InputFileName))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string item in colFields)
{
DataColumn column = new DataColumn(item);
inputData.Columns.Add(column);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
inputData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void ButtonStop_Click(object sender, RoutedEventArgs e)
{
// button enable handled in worker_RunWorkerCompleted()
//buttonStart.IsEnabled = true;
//buttonStop.IsEnabled = false;
if (m_bgWorker == null)
return;
if (m_bgWorker.IsBusy)
m_bgWorker.CancelAsync();
}
/// <summary>
/// Saves configuration when shutting down
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainFormClosing(object sender, CancelEventArgs e)
{
GetValuesFromForm();
m_configuration.Serialize(m_configuration.ConfigFileName);
}
private void ShowPassword_Checked(object sender, RoutedEventArgs e)
{
passwordTxtBox.Text = passwordBox.Password;
passwordBox.Visibility = Visibility.Collapsed;
passwordTxtBox.Visibility = Visibility.Visible;
}
private void ShowPassword_Unchecked(object sender, RoutedEventArgs e)
{
passwordBox.Password = passwordTxtBox.Text;
passwordTxtBox.Text = "";
passwordTxtBox.Visibility = Visibility.Collapsed;
passwordBox.Visibility = Visibility.Visible;
}
#region IDisposable Support
private bool m_disposed = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!m_disposed)
{
if (disposing)
{
m_bgWorker.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
m_disposed = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}