Reflection and XmlSerialization Examples to Generate Body of Email From Object for System.Net.Mail

Reflection and XmlSerialization Examples to Generate Body of Email From Object for System.Net.Mail

 by David Hayden ( .NET Developer )

 

I had to generate an email messages from a form in a website today. As we all know it is a pretty trivial thing to do, but then I got to thinking about how it was commonly done several years ago and how I could complicate the solution by using Reflection and XmlSerialization! I am not suggesting one uses these techniques. I just thought it would be fun to write them.

Let's say we generate sales lead from a website. All of the wonderful information in the form gets populated into a SalesLead Class. For brevity, let's say the class looks like this:

 

public class SalesLead
{
    private string _firstName = string.Empty;
    private string _lastName = string.Empty;
    private string _phoneNumber = string.Empty;
    private string _emailAddress = string.Empty;

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public string PhoneNumber
    {
        get { return _phoneNumber; }
        set { _phoneNumber = value; }
    }

    public string EmailAddress
    {
        get { return _emailAddress; }
        set { _emailAddress = value; }
    }

    public SalesLead() { }
}

 

Now I need to generate one of those ugly email messages to someone in sales that essentially looks like this:

 

FirstName: John
LastName: Doe
PhoneNumber: 555-1212
EmailAddress: john.doe@...

 

We could manually create a hard-coded routine to send the sales lead information to the sales department, or we could build something generic that uses Reflection or perhaps XmlSerializer.

 

Reflection

Using reflection to generate the list of properties and values in an object and return the above string give us something that looks like this:

 

public class GenerateEmailBodyUsingReflection
{
    public string GetEmailBody(object item)
    {
        StringBuilder builder = new StringBuilder();

        Type type = item.GetType();

        PropertyInfo[] properties = type.GetProperties();

        foreach (PropertyInfo p in properties)
        {
            builder.Append(p.Name);
            builder.Append(": ");
            builder.Append(p.GetValue(item, null).ToString());
            builder.Append(System.Environment.NewLine);
        }

        return builder.ToString();
    }
}

 

Pretty simple to do. Notice that the GetEmailBody Method takes an object and not a particular class, like SalesLead. Notice that we also can add properties to the object and not have to change this class at all. It will find the new properties and add them to the body.

 

XmlSerialization

For kicks, we could use XmlSerialization to accomplish the same thing. Here is some code that does just that:

 

public class GenerateEmailBodyUsingXmlSerialization
{
    public string GetEmailBody(object item)
    {
        StringBuilder builder = new StringBuilder();

        XmlSerializer serializer =
new XmlSerializer(item.GetType()); using (Stream stream = new MemoryStream()) { serializer.Serialize(stream, item); stream.Position = 0; XmlTextReader reader =
new XmlTextReader(stream); reader.ReadStartElement(); while (reader.Read()) { if (reader.NodeType ==
XmlNodeType.Element) { builder.Append(reader.Name); builder.Append(": "); builder.Append(reader.ReadString()); builder.Append(System.Environment
.NewLine); } } }
return builder.ToString(); } }

 

Seems kinda crazy to write, but certainly an interesting intellectual process :)

 

Strategy Pattern and Dependency Injection

Use the Strategy Pattern and Dependency Injection to hide the actual class doing the implementation and for the benefit of adding testing later (did someone say add testing later and not use TDD?):

 

public interface IEmailBodyFromObjectGenerator
{
    string GetEmailBody(object item);
}

public class GenerateEmailBodyUsingXmlSerialization
: IEmailBodyFromObjectGenerator
public class GenerateEmailBodyUsingReflection
: IEmailBodyFromObjectGenerator

 

public class Emailer
{
    IEmailBodyFromObjectGenerator _generator;

    public Emailer(IEmailBodyFromObjectGenerator
generator) { _generator
= generator; } public void SendObjectViaEmail(object item) { MailMessage message = new MailMessage(); // ... message.Body = _generator.GetEmailBody(item); // ... SmtpClient client = new SmtpClient(); client.Send(message); } }

 

Go ahead and use your Emailer Class now

 

IEmailBodyFromObjectGenerator generator =
EmailBodyFromObjectGeneratorFactory.Create(); new Emailer(generator).SendObjectViaEmail(salesLead);

 

Now that's more like it :)

 

Conclusion

I just felt like playing with a little Reflection and XmlSerialization, so take this example as tongue in cheek. I thought someone might benefit from some of the code and concepts, however.

Here is another tutorial on reflection I wrote awhile back:

 

Source: David Hayden ( .NET Developer )

Filed: C#

 

posted on Monday, May 01, 2006 5:55 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices