I am not going to show you any new .NET trick with this article. Every once in a while I like to share a good programming tip that is not anything spectacular. Rather, it is just a better way to do something that I have often done in a less than effecient or user-friendly way. That's what this article is about; just doing a menial task of sending emails from an application in a better way.
I frequently write applications where I process large batches of input data from a client. If for some reason a line of data does not validate, I need to send an email to the customer so that they are aware that that the line in question could not be processed. In any case the application is designed to process the good data and bypass that which cannot be processed.
I have started with applications sending individual messages for each and every error and then found that the volume of emails could easily become a real problem, especially if the customer sends in a large number of bad input lines.
There is a simple, but much better solution to this type of problem. First, I create a StringBuilder object that will hold the error (or any type of anamoly) messeages during the processing of the input file. I place the StringBuilder object at the class level so that any method in the class can see the object. You might even globalize it further by placing it as a Publc variable in a VB.NET Module or a static varaible in a C# class.
Private sb As New StringBuilder(5000)
Next, in the places where I determine that there is a problem with input data, etc., I add a message to the error message StringBuilder as shown below:
| Dim msg As String = reason & vbCrLf & LastName & ", " & FirstName sb.Append(msg & vbCrLf) |
| Private Function CreateEMailAttachment() As String If sb.Length > 0 Then Dim fn As String = Path.Combine(logPath, "Exceptions_" & Format(Now, _ "yyyyMMddHHmmss") & ".txt") Write2File(sb.ToString, fn) sb = New StringBuilder(5000) Return fn Else Return String.Empty End If End Function |
| SendEmail("Processing Summary" & vbCrLf & summary, EmailType.Success, _ CreateEMailAttachment()) |