Metadata and Reflection in .NET

Thursday, November 11, 2004

Metadata is the life blood of the .NET platform. Many of the features we use everyday during design time, during compile time, and during execution time, rely on the presence of metadata. Metadata allows an assembly, and the types inside an assembly, to be self-describing. In this article, we will discuss metadata and look at some of types and methods used to programmatically inspect and consume metadata.

Metadata – Some History

Metadata is not new in software development. In fact, many of .NETs predecessors used metadata. COM+ for instance, kept metadata in type libraries, in the registry, and in the COM+ catalog. This metadata could describe if a component required a database transaction or if the component should participate in object pooling. However, since the COM runtime kept metadata in various locations, irregularities could occur. Also, the metadata could not fully describe a type, and was not extensible.

A compiler for the common language runtime (CLR) will generate metadata during compilation and store the metadata (in a binary format) directly into assemblies and modules to avoid irregularities. The CLR also allows metadata extensibility, meaning if you want to add custom metadata to a type or an assembly, there are mechanisms for doing so.

Metadata in .NET cannot be underestimated. Metadata allows us to write a component in C# and let another application use the metadata from Visual Basic .NET. The metadata description of a type allows the runtime to layout an object in memory, to enforce security and type safety, and ensure version compatibilities.

Metadata & Reflection

Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime, but in the upcoming example we will be reading and invoking only.

Reflection generally begins with a call to a method present on every object in the .NET framework: GetType. The GetType method is a member of the System.Object class, and the method returns an instance of System.Type. System.Type is the primary gateway to metadata. System.Type is actually derived from another important class for reflection: the MemeberInfo class from the System.Reflection namespace. MemberInfo is a base class for many other classes who describe the properties and methods of an object, including FieldInfo, MethodInfo, ConstructorInfo, ParameterInfo, and EventInfo among others. As you might suspect from thier names, you can use these classes to inspect different aspects of an object at runtime.

Metadata : An Example

In the web form shown below we will allow the user to inspect and set any property of a web control using reflection techniques. We have a Panel control on the bottom of the form filled with an assortment of controls (in this case, a TextBox, a Button, a HyperLink, and a Label, although if you download the code you can drag any controls into the panel and watch the example work).

When the page initially loads we will loop through the Controls collection of the Panel to see what controls are available. We can then display the available controls in the ListBox and allow the user to select a control. The code to load the ListBox is shown below.

private void Page_Load(object sender, System.EventArgs e)
{
   if(!Page.IsPostBack)
   {
      PopulateControlList();
   }
}

private void PopulateControlList()
{
   foreach(Control c in Panel1.Controls)
   {
      if(c is WebControl)
      {                  
         controlList.Items.Add(new ListItem(c.ID, c.ID));
      }
   }
}

You can see we test each control in the Panel to see if it derives from WebControl with the ‘is‘ keyword. If the control is a type of WebControl, we add the ID of the control to the list. The user can then select a control from the list with the mouse. We have set the list control’s AutoPostBack property to true so it will fire the SelectedIndexChanged event when this happens. During the event we want to populate a DropDownList control with the properties available on the selected object. The code to perform this task is shown next.

private void controlList_SelectedIndexChanged(object sender, System.EventArgs e)
{         
   PopulatePropertyList();
}

private void PopulatePropertyList()
{
   propertyList.Items.Clear();
   valueText.Text = String.Empty;
   WebControl control = FindSelectedPanelControl();
   
   if(control != null)
   {       
      Type type = control.GetType();
   
      PropertyInfo[] properties = type.GetProperties();

      foreach(PropertyInfo property in properties)
      {
         propertyList.Items.Add(new ListItem(property.Name));
      }

      GetPropertyValue();         
   }
}

private WebControl FindSelectedPanelControl()
{
   WebControl result = null;

   string controlID = controlList.SelectedItem.Text;    
   
   result = Panel1.FindControl(controlID) as WebControl;

   return result;
}

The first step in PopulatePropertyList is to obtain a reference to the control the user selected. We do this step in FindSelectedPanelControl by asking the list for the selected item’s Text property (which is the ID of the control). We can then pass this ID to the FindControl method to retrieve the control reference.

With the reference in hand we call GetType to obtain a Type reference. The Type class, as we mentioned before, is the gateway to obtaining metadata at runtime. By invoking the GetProperties method we obtain an array of PropertyInfo objects. The PropertyInfo class gives each object in the array a Name property, and we can populate the DropDownList with the name.

The DropDownList also has AutoPostBack set to true to let us catch the SelectedIndexChange event when the user selects a property to inspect. When this event fires we want to obtain the value of the property the user selected, as shown in the event handling code below.

private void GetPropertyValue()
{
   WebControl control = FindSelectedPanelControl();
   Type type = control.GetType();
   
   string propertyName = propertyList.SelectedItem.Text;
   BindingFlags flags = BindingFlags.GetProperty;
   Binder binder = null;         
   object[] args = null;
         
   object result = type.InvokeMember(
      propertyName, 
      flags, 
      binder, 
      control, 
      args
      );
   
   valueText.Text = result.ToString();
}

Once again we will obtain a reference to the selected control using FindSelectedPanelControl, then use that control reference to obtain a Type reference for the control. Next, we need to setup parameters to invoke the property by name using InvokeMember. The InvokeMember allows us to execute methods by name (and a property is a special type of method).

The first parameter to InvokeMember is the name of the member to call. For example, “ImageUrl” is the name of a HyperLink control member. The second parameter is a BindingFlags enumeration. BindingFlags tell InvokeMember how to look for the named member. By passing BindingFlags.GetProperty we are telling InvokeMember to look for “ImageUrl” as a “get” property method, as opposed to a “set” property method (because in the runtime, get_ImageUrl and set_ImageUrl are the two methods behind the ImageUrl property).

The binder parameter for InvokeMember is a parameter we do not use, so we pass null. A binder is useful in rare circumstances where we need explicit control over how the reflection code selects a member and converts arguments. By passing a null value we are letting reflection use the default binder to perform the member lookup and argument passing.

The fourth parameter to InvokeMember is the target object instance. This is the object the runtime will try to invoke the member upon, so we pass the reference to the selected control. Finally, the last parameter is a parameter for any arguments to pass to the member. Since fetching a property does not require any parameters we can pass a null value.

InvokeMember returns an object which is the return value of the member we called (if we were to InvokeMember on a member returning void, InvokeMember returns a null value). If we InvokeMember on ImageUrl we will get back a string, we will take this string and display it in the valueText TextBox control.

If the user modifies the valueText control and clicks the “Set Property” button, we want to set the selected property with the value. The event handler for the button is shown next.

private void SetPropertyValue()
{
   WebControl control = FindSelectedPanelControl();
   Type type = control.GetType();
   
   string propertyName = propertyList.SelectedItem.Text;
   BindingFlags flags = BindingFlags.SetProperty;
   Binder binder = null;

   object arg = CoherceStringToPropertyType(control, propertyName, valueText.Text);
   object[] args = { arg };

   type.InvokeMember(
      propertyName, 
      flags, 
      binder, 
      control, 
      args
      );
}

Once again we retrieve a reference to the selected control, and a reference to the runtime type representation of the control with GetType. This time we setup the InvokeMember parameters to perform a “set property” operation. Notice the BindingFlags have chanced to BindingFlags.SetProperty. We also now have to pass an argument array, with the one argument being the value the user has typed into the textbox. We can’t just pass this string in the argument array, however, because not all of the properties take a string argument. The AutoPostBack property, for instance, takes a boolean parameter. To force the parameter into the correct type we call the method below.

private object CoherceStringToPropertyType(WebControl control, 
                                           string propertyName, 
                                           string value)
{
   object result = null;

   Type type = control.GetType();
   PropertyInfo p = type.GetProperty(propertyName);
   Type propertyType = p.PropertyType;

   TypeConverter converter = TypeDescriptor.GetConverter(propertyType);
   result = converter.ConvertFrom(value);

   return result;
}

The method above uses a TypeConverter object. A TypeConverter is useful for converting types from a textual representation back to their original type (for the AutoPostBack property, we would convert a string to a bool). Notice we can retrieve the TypeConverter for a given property by asking the TypeDescriptor class to give us a TypeConverter. This allows us to avoid writing a large amount of code, perhaps with a switch statement, that would examine the property type to determine what kind of type we need (string, bool, int, or some class we’ve never heard of). Instead, the metadata of the type allows it to be self-describing and give us an object that can perform the specific conversion for us.

This article only touches upon some of the basic features of metadata and reflection. Here are some additional resources for more information.

 

Displaying Metadata in .NET EXEs with MetaViewer

Dynamically Bind Your Data Layer to Stored Procedures and SQL Commands Using .NET Metadata and Reflection

Use Reflection to Discover and Assess the Most Common Types in the .NET Framework

How Microsoft Uses Reflection

 

Download the code for this article: ReflectIt.zip

 

-- by K. Scott Allen

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!