Thursday, May 30, 2013

C# Assign values to hard coded objects when you don't know their names; i.e dynamically at runtime

I have an method that gets passed a collection of KeyValue pairs.
These KeyValues consist of a Key, which contains the name of the property, or variable, and a Value. For example:

KeyValue1
  • Key="InvoiceId"
  • Value="3436" //the type is string


KeyValue2
  • Key="DateDue"
  • Value="1/17/2013 6:00:00 AM" //the type is DateTime

So the objective is as follows:
  1. Find the variable named dbi.InvoiceId
    1. Then assign it the Value of 3436, as a string
  2. Find the variable named dbi.DateDue
    1. Then assign it the Value of "1/17/2013 6:00:00 AM", as a DateTime
Looks complicated. But its not.

Make sure the reference System.Reflection. The framework on my project is .Net 4.
Here's the code:
        public string SendByteArrayToSharepoint(Byte[] bytes, string fileName, SharepointGatewayCustomAttributes customAttributes)
        {
            try
            {
                //THIS IS THE TARGET OBJECT
                DropBoxItem dbi = new DropBoxItem()
                {
                    ContentType = contentType,
                    Name = Path.GetFileName(fileName),
                    Title=fileName,
                    Path = fileName
                };

                //Now iterate through the AttributeCollection
                foreach (var v in customAttributes.AttributeCollection)
                {
                    // this locates the object
                    PropertyInfo pi = dbi.GetType().GetProperty(v.Key);

                    //this assigns the value of the object, using the correct type
                    pi.SetValue(dbi, ChangeNullableType(v.Value, pi.PropertyType), null);
                }


This is the method called ChangeNullableType:
Credit for this method goes to Peter Johnson's Blog at http://weblogs.asp.net/pjohnson/archive/2006/05/19/447154.aspx
public static object ChangeNullableType(object value, Type conversionType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            } // end if

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
                // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
                // determine what the underlying type is
                // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
                // have a type--so just return null
                // Note: We only do this check if we're converting to a nullable type, since doing it outside
                // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
                // value is null and conversionType is a value type.
                if (value == null)
                {
                    return null;
                }

                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                NullableConverter nullableConverter = new NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return Convert.ChangeType(value, conversionType);
        }





No comments:

Post a Comment