One of the web services I've been working on has the requirement to send out formatted emails to internal user and external customers. In order for the service to go live we needed to take any day-to-day maintenance duties away from the developers of the project. One aspect of those duties is to keep the email messages that go out up-to-date. We store the addresses, subject and body of the various emails in the database. With the message bodies, we've designed it that the author can insert various macros that will get replaced with contextual values.
For example, when a new account is created a new email is fired off to our customer. That email needs to list all the specific details of the new account. The email message will have macros available like $AccountId$, $ContactFirstName$ or $InitialPassword$. When we generate the email, we call a simple function that uses reflection to pull the properties out of the Account object and replace the macros within the email message. Below is the VB.Net function that does that.
Public Shared Function ReplaceMessageMacros(ByVal Msg As String, ByVal Obj As Object, ByVal ObjType As Type) As String
Dim objectType As Type = Obj.GetType
Dim pi As PropertyInfo()
Dim i As Integer
' get the property list from the object passed in
pi = = objectType.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
' loop thru all properties of object and see if a macro exists in the Msg
For i = 0 To (pi.Length - 1)
Dim val As String
Try
val = pi(i).GetValue(Obj, Nothing).ToString()
Catch ex As Exception
val = ""
End Try
' replace the macro with the property value
Msg = Replace(Msg, "$" & pi(i).Name & "$", val)
Next
Return Msg
End Function
Make sure you import System.Reflection