Tuesday, April 7, 2009

A Utility Class of Tools

This is a class of code I use all the time, sjm_tools The test harness is written as a Windows Form Application. Coding environment Visual Studio 2008, Visual-Basic .NET, .NET Framework 2.0 SP 1

In the designer create a WFA form, with a listbox, and 3 buttons. Properties:
Form1 = 450, 255
Form1.name = form1
form1.text = "Test harness for sjm_tools"

Listbox.name = List1
List1.location = 10,10
list1.size = 300,200

Button1.Name = btnFilename
btnFilename.location = 315,10
btnFilename.size = 70,25
btnFilename.Text = File Name

Button2.Name = btnSendEmail
btnSendEmail.location = 315,41
btnSendEmail.size = 70,25
btnSendEmail.Text = Send Email

Button3.Name = btnWriteToErrorLog
btnWriteToErrorLog.location = 315,72
btnWriteToErrorLog.size = 70,25
btnWriteToErrorLog.Text = Error Log

Now open the form1.vb code file, copy and paste the following code into it.
Imports System.Net.Mail
Imports System.IO
Imports System.Xml
Public Class Form1
' ------------------------------------------------------
' The Test Harness for the class sjm_tools
' ------------------------------------------------------
Dim myTools As New Sjm_Tools
Private Sub btnFilename_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnFilename.Click
Dim i As Integer
Dim s1 As String = "File_"
Dim sExt As String = ".txt"
For i = 0 To 10
List1.Items.Add(myTools.UniqueFilname(s1, sExt))
System.Windows.Forms.Application.DoEvents()
System.Threading.Thread.Sleep(10)
Next
End Sub
Private Sub btnWriteToErrorLog_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnWriteToErrorLog.Click
Dim sLogName As String
dim i as integer
sLogName = My.Application.Info.DirectoryPath & "\" & _
myTools.UniqueFilname("ErrLog_", ".txt")
for i = 1 to 5
myTools.WriteToErrorLog(sLogName, "Sample Text" & i, _
"Error Description" & i)
next
List1.Items.Clear()
List1.Items.Add("Finished - " & System.IO.Path.GetFileName(sLogName))
End Sub
Private Sub btnSendEmail_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSendEmail.Click
' ----------------------------------------------------------
' Note. My mailhost has been removed from this sample.
' You will have to substitute your own by filling in the property
' Typically find it in your email client configuration.
' Example - myIsp.myMailhost.myDomain.com
' ------------------------------------------------------
' My names for To and From targets have been removed.
' Substitute your own on the next two lines for testing
' ------------------------------------------------------
Dim sMailTo As String = "The_Target_Name@TheTargetDomain.xxx"
Dim smailFrom As String = "Your_From_Name@YourSendingDomain.xxx"
Dim sSubject As String = "The email title string"
Dim sBody As String
Dim sLog As String
myTools.MailHost() = "myIsp.myMailhost.myDomain.com"
sLog = My.Application.Info.DirectoryPath & "\"
sLog = sLog & myTools.UniqueFilname("ErrLog_", ".txt")
sBody = "Hi There, glad that you could stick around" & vbCrLf
sBody = sBody & "Introducing Mr Larry Bohay Noel on Rhythm Pole." & vbCrLf
sBody = sBody & "Have to keep myself amused when writing test harnesses."
If (myTools.SendEmail(smailFrom, sMailTo, sSubject, sBody, sLog) <> 0) Then
List1.Items.Add("SendEmail Error - see log file")
List1.Items.Add(System.IO.Path.GetFileName(sLog))
End If
List1.Items.Add("Email sent.")
End Sub
' End of Test Harness Class
End Class

Public Class Sjm_Tools
'------------------------------------------------------------------------
' Scope: A collection of tools that are used in various applications
' Author: Scott Mathews - 03Jan2009
'------------------------------------------------------------------------
' Programming Environment = Visual Studio 2008
' = .Net Framework 2.0
' = Visual Basic
' Please feel free to borrow and use.
' Contact me at mathewssj@gmail.com if you would like an addition
' -----------------------------------------------------------------------
Private m_MailHost As String = ""
' -----------------------------------------------------------------------
Public Function UniqueFilname(ByVal prefix As String, _
ByVal extension As String) As String
'--------------------------------------------------------------------
' Scope: Returns a date stamped file name string
' Author: Scott Mathews - 03Jan2009
' -------------------------------------------------------------------
' Constraints - Needs a 10 milli-second delay between calls to
' ensure a unique value
' -------------------------------------------------------------------
Dim sBuff As String
sBuff = prefix & Now() & Now.Millisecond() & extension
sBuff = Replace(sBuff, " ", "")
sBuff = Replace(sBuff, ":", "")
sBuff = Replace(sBuff, "/", "")
Return sBuff
End Function
'----------------------------------------------------------
Public Function SendEmail(ByVal sFrom As String, ByVal sTo As String, _
ByVal sSubject As String, ByVal sBody As String, _
ByVal sErrLog As String) As Integer
'--------------------------------------------------------------------
' This function uses the VB.NET mail system to send a status
' email to the user
' -------------------------------------------------------------------
' Return: 0 = success
' Return: -1 = failure
' -------------------------------------------------------------------
Dim smtp As New System.Net.Mail.SmtpClient
Dim msgMail As New MailMessage(New MailAddress(sFrom), _
New MailAddress(sTo))
Try
With msgMail
.Subject = sSubject
.Body = sBody
End With
' Set the mail host
smtp.Host() = Me.MailHost.ToString
smtp.Send(msgMail)
Catch ex As Exception
WriteToErrorLog(sErrLog, "Email send message failed = ", _
ex.Message)
msgMail.Dispose()
smtp = Nothing
Return -1
End Try
msgMail.Dispose()
smtp = Nothing
Return 0
End Function
' ----------------------------------------------------------
Public Sub WriteToErrorLog(ByVal sErrorlog As String, _
ByVal Message As String, _
ByVal ErrorDescription As String)
' -------------------------------------------------------------------
' Posts a message and description to a debug logging file
' Requires the name of the file to as a parameter
' ------------------------------------------------------------------
' Return: 0 = success
' Return: -1 = failure
' -------------------------------------------------------------------
Dim myFileStream As System.IO.FileStream
Try
'Open a file for append
myFileStream = New System.IO.FileStream(sErrorlog, _
FileMode.Append, FileAccess.Write, _
FileShare.None)
'Create the stream writer
Dim myWriter As New System.IO.StreamWriter(myFileStream)
'Write the log message to the file
myWriter.WriteLine("--------------------" & Now.ToString() & _
"--------------------------")
myWriter.WriteLine(Message)
myWriter.WriteLine(ErrorDescription)
myWriter.Flush() ' Flush before we close
myWriter.Close() ' Close the streamwriter
myFileStream.Close() ' Close the filestream
Catch ex As Exception
' Display error message box if logfile does not exist
MessageBox.Show("Could not open the file. " & _
ex.Message)
End Try
End Sub
' -----------------------------------------------------------
Public Property MailHost() As String
Get
Return m_MailHost
End Get
Set(ByVal value As String)
m_MailHost = value
End Set
End Property
End Class

No comments:

Post a Comment