David Truxall

Adrift in .Net

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

Other Good Blogs

My Other Articles on CodeProject

Subscriptions

News

Day of .Net October 18, 2008 - Be there!
View David Truxall's profile on LinkedIn
My presentations on SlideShare

Post Categories



Monday, January 15, 2007 - Posts

CopySourceAsHTML Clipboard Access Error (Blame the VPC)
I kept getting an error when trying to use CopySourceAsHTML in Visual Studio 2005. The error was that CopySourceAsHTML was unable to access the clipboard. Turns out the problem is when using it in a VPC, and the answer is here.

posted Monday, January 15, 2007 3:11 PM by davetrux with 0 Comments

Casting Text Data to Members in a Businees Object via Reflection

I have a pipe-delimited text file that I am parsing and using to fill a collection of custom business objects. Instead of hard-coding the bits of each pipe-delimited line, I am using an XML file to map data items in the file to object members, like this XML fragment:

<Field>
    <Name>NAMID</Name>
    <Location>0</Location>
    <MapsTo>MemberId</MapsTo>
    <IsRole>false</IsRole>
</Field>

After parsing and matching the data element to the proper member name, I call this function:

public void SetDataMemberValue(string memberName, Member member, string data)
{    
     // get an instance      
     // of that object's type.
     Type objectType = member.GetType();
     PropertyInfo[] properties = objectType.GetProperties();
     foreach (PropertyInfo property in properties)
     {
        if (string.Equals(property.Name, memberName, StringComparison.OrdinalIgnoreCase))
        {
            object[] args = new object[1];
            args[0] = data;
            object result = null;
 
            if (property.PropertyType == data.GetType())
            {
                //The type of the property matches the data's type
                result = data;
            }
            else
            {
               result = property.PropertyType.InvokeMember("Parse", BindingFlags.InvokeMethod, null, result, args);
            }
 
            if (result != null)
            {
                property.SetValue(member, result, null);
            }
        }
    }
}

The tricky bit is the InvokeMember call, which is casting my string to the appropriate type for the property. Of course this is they stylized version of the function, I removed the try-catch bits to make it smaller and readable for the acutal function. You should wrap the InvokeMember call with a try-catch as Parse methods can fail quite hard.

posted Monday, January 15, 2007 2:27 PM by davetrux with 0 Comments




Powered by Dot Net Junkies, by Telligent Systems