Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Generating types from external metadata

0.00/5 (No votes)
31 May 2008 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here