|
|||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IndexIntroductionIn the early article I introduced the attributes used to describe a business object. In this article I'll show how to extract this descriptive information from classes. To explain how it will be done I'll write an application that creates a SQL script to create tables according to the attributes applied used in the class. The ToolIt will be a console application. As argument you pass the assembly name. The tool will load the assembly, enumerate the classes that are marked with the We'll start with the code to load an assembly. public static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: scriptgen [assembly path]");
return;
}
Assembly assembly = null;
try
{
assembly = Assembly.LoadFrom(args[0]);
}
catch (Exception e)
{
Console.WriteLine("Failed to load assembly [" + args[0] + "]");
Console.WriteLine(e.Message);
}
}
The code above tries to load the assembly according to the path in the argument. Now we must enumerate all of the assembly classes that have the public void ParseAssembly(Assembly assembly)
{
Type[] types = assembly.GetTypes();
foreach(Type type in types)
{
if (type.IsClass)
{
DataTableAttribute[] dataTable = (DataTableAttribute[])
type.GetCustomAttributes(typeof(DataTableAttribute),
true);
if (dataTable.Length > 0)
{
Console.WriteLine("Found class '{0}'", type.ToString());
}
}
}
}
The code above gets all the types from the assembly, then checks if it's a class and if it has the void ParseClass(Type type, DataTableAttribute dataTable)
{
PropertyInfo[] properties = type.GetProperties();
// gets the key field
foreach (PropertyInfo property in properties)
{
KeyFieldAttribute[] key = (KeyFieldAttribute[])
property.GetCustomAttributes(typeof(KeyFieldAttribute),
true);
if (key.Length > 0)
{
Console.WriteLine("Key = " + property.Name + " type is "
+ property.PropertyType);
break;
}
}
// gets the other fields
foreach (PropertyInfo property in properties)
{
BaseFieldAttribute[] field = (BaseFieldAttribute[])
property.GetCustomAttributes(typeof(BaseFieldAttribute),
true);
if (field.Length > 0)
{
if (!(field[0] is KeyFieldAttribute))
{
Console.WriteLine("Property " + property.Name
+ " [" + property.PropertyType + "] " +
+ "maps to column [
+ field[0].ColumnName + "]");
}
}
}
}
Now all we have to do is to create the sql script. Our tool in this version will only be able to create scripts that follow this 2 requisites: The key is a int, The source files included here will create the following assemblies:
Coming up nextIn the next article I'll create the full DAL that gets an object in runtime and persists it in a database, as well as gets it from the data provider.
|
||||||||||||||||||||||||||||||||||||||||