65.9K
CodeProject is changing. Read more.
Home

Generating types from external metadata

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.25/5 (4 votes)

May 31, 2008

CPOL

1 min read

viewsIcon

15420

downloadIcon

68

Type generation from external metadata.

Introduction

This is a solution for creating types that are defined in an external metadata. The idea is to define types that can be used in the application without compiling or changing the code.

Idea

Along with types that are defined (like in my example, in an external XML file), data bindings and data access to database can be stored in external meta data. So by having such meta data and using Designer hosting, a very usefully customization solution can be provided. Advanced users of the application can design and use their own, for example, WinForms without writing a single line of code.

Using the Code

There are several classes involved. The main one is TypeMetaData, which describes the type. The properties AssemblyName, ModuleName, and TypeName are mandatory since they are used in the process of type creation. All the properties are stored in the List Properties, whose items are of type PropertyMetaData. PropertyMetaData describes the property type. Since this is just a basic example, we have just the property name and property type. In addition, we can add property attributes or any other related metatdata. The class TypeXmlSerializer is used to serialize and deserialize the type metadata to XML. Type generation happens in the class TypeGenerator. There is a method GenerateType(TypeMetaData metaData) whose responsibility is to generate the type from the given meta data.

Below is an example of using the TypeGenerator:

//
// Generating type from xml
//

OpenFileDialog dlg = new OpenFileDialog();
dlg.DefaultExt = "xml";
dlg.Filter = "XML Files|*.xml";

if (dlg.ShowDialog() == DialogResult.OK)
{

   TypeMetaData meta = TypeXmlSerializer.DeSerialize(dlg.FileName);
   object newType = TypeGenerator.GenerateType(meta);
}

TypeMetaData should be deserialized from the external source and then used to generate the type.

Conclusion

I hope that this short article was useful and that it can give ideas to anyone who needs to design and implement dynamic type creation.