This is just a quick post.
The other day, I needed to take all fields from a business object called QuoteLead which represents a Sales Lead for an insurance quote, and send it to to another system in a name/value format to post via HTTP. This is because we're integrating with a 3rd party service that requires an HTTP post, rather than a web service (SOAP would cost extra, and the client didn't want to pay the montly fee.)
So I ended up having to do a bit of refleciton, in order to send all of the business object's properties in a format like this: firstname=Bob&lastname=Smith&address1=123 some street&city=fort worth
etc. etc.
So I ended up doing this:
public virtual string SerializeForHttp()
{
QuoteLead lead = this;
PropertyInfo[] props = lead.GetType().GetProperties();
StringBuilder builder = new StringBuilder(props.Length);
foreach (PropertyInfo info in props)
{
string name = info.Name;
object value = info.GetValue(lead, null);
if (value != null)
{
builder.Append(name + "=" + value.ToString() + "&");
}
}
return builder.ToString();
}
I ran into a couple of gotchas:
- First, I tried passing various binding flags to the GetProperties() method, but i kept getting weird errors. Using the parameterless version of the method got me all the public, instance methods including inherited ones, which is exactly what i needed.
- You'll noticed I check the return value from GetValue() for null. This is because if i call the ToString() method I'll get an error for values that aren't there.
- Finally, the QuoteLead object i was "serializing" in this fashion has a related "State" property, an object which represents one of the United States. This was an object, not just a string in QuoteLead. I had to overload the ToString() method in State so that it would return the State abbreviation from the database:
public override ToString() {
return this.StateAbbreviation; }
If anyone is interested, my object model is auto-generated using Custom Codesmith templates that integrate with NHibernate. We've implemented the ActiveRecord pattern (because Castle ActiveRecord had their site going down all the time, and i like the database to gen the business objects on small projects like this.) We nicknamed this framework "SNARF" for Simple NHibernate ActiveRecord Framework. In some future posts, I'll share the framework and templates.