. Topicala Page Index Token

A Journal about the experiences I have developing little applications in C#, Perl, Html and Javascript and talking about things new things that I use. Always Geeky; Always Nerdy; Always poor Grammer!

I am a Software Analyst Developer working in Southport, England but living in Liverpool. I develop mainly in C# and ASP.Net. I have been developing comercial software for several years now. I maintain this site (hosted at SwitchMedia UK) as a way of exploring new technologies (such as AJAX) and just generally talking about techie geek issues. This site is developed through a host of Perl scripts and a liberal use of Javascript. I enjoy experimenting with new technologies and anything that I make I host here.

Quick Search

Web www.kinlan.co.uk

Tuesday, December 18, 2007

IDataRecord Fields to Dictionary Extension Method

I have never been a fan of directly passing IDataRecords, or IDataReaders for that matter, about the place to get simple field values out.

Therefore, with the introduction of C# 3.0 and Extension Methods, I thought it would be cool to write (and share) a simple implementation of some code that I use to convert the IDataRecord Field data to an Dictionary<string, object> object.

namespace Kinlan.Data.Extensions
{
public static class DataExtensions
{
public static Dictionary<string, object> FieldsToDictionary(this IDataRecord dataRecord)
{
Dictionary<string, object> fieldBag = new Dictionary<string, object>(dataRecord.FieldCount);

if (dataRecord != null)
{
for (int fieldIdx = 0; fieldIdx < dataRecord.FieldCount; fieldIdx++)
{
string name = dataRecord.GetName(fieldIdx);
object value = dataRecord[fieldIdx];
fieldBag.Add(name, value);
}
}

return fieldBag;
}
}
}

It is quite simple really and nothing too complex.


A place where it can be used it Windows Workflow.  If you are injecting parameters into your Workflow instance you need to pass a Dictionary<string, object> in, well now you can (if you desired) simply convert a IDataReader/IDataRecord object into with the following simple piece of code:

WorkflowInstance instance = runtime.CreateWorkflow(typeof(_WorkflowClass_), dataReaderInstance.FieldsToDictionary());

This code should be used sparingly, for instance if you wanted a very high performance access to the field data, you might as well stay on the IDataRecord.