C#: Using reflection with COM objects

Yesterday, I was trying to use reflection to access some properties of a COM object but was getting the following exception:

Object reference not set to an instance of an object

Debugging into, I noticed that GetProperty() method was returning null in the following call:

var propertyInfo = comObject.GetType().GetProperty("PropertyName")

After some searching, I found that we need to use the more generic InvokeMember() method to get or set the properties of a COM object. Here’s the simplest example of the usage:

//get the value of comObject.PropertyName
object propertyValue = comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.GetProperty, null, comObject, null);

//set the value of comObject.PropertyName
comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.SetProperty, null, comObject, new object[] { propertyValue });

I hope this post helps someone who is trapped into the same situation.

Article Posted: AutoCompleteComboBox for Silverlight

I have posted an article at CodeProject on customization of the Silverlight AutoCompleteBox to be used as a type-ahead ComboBox in LOB applications at CodeProject. The AutoCompleteComboBox can be used in typical Object-to-Object associations (one that we typically encounter when creating associations in Entity Framework) as well as Foreign Key associations (the new association type introduced with Entity Framework 4).

Here’s a sample usage of the control in a typical MVVM scenario:

  • Object to Object Association:

    Example data structure:

    public class SalesOrderDetail
    {
        Product product;
        public Product Product
        {
            get { return product; }
            set { product = value; }
        }
    }
    

    Example control usage:

     <custom:AutoCompleteComboBox
       SelectedItemBinding="{Binding Product, Mode=TwoWay}"
       ItemsSource="{Binding Path=Products, Source={StaticResource ViewModel}}"
     />
    
  • Foreign Key Association:

    Example data structure:

    public class SalesOrderDetail
    {
        int productID;
        public int ProductID
        {
            get { return productID; }
            set { productID = value; }
        }
    }
    

    Example control usage:

     <custom:AutoCompleteComboBox
       SelectedValue="{Binding ProductID, Mode=TwoWay}"
       SelectedValuePath="ProductID"
       ItemsSource="{Binding Path=Products, Source={StaticResource ViewModel}}"
     />
    

To view the implementation details, you can read the full article at :
http://www.codeproject.com/KB/silverlight/AutoComplete_ComboBox.aspx

The source code along with a demo project can be downloaded from the article as well as here (28 KB). Remember to rename the file as zip for extraction.