5,699,431 members and growing! (16,240 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate

A Data Access Layer to persist business objects using attributes and reflection - Part II

By xicoloko

Persistance to business objects through attributes and reflection
C#, Windows, .NET 1.0, .NET, Visual Studio, DBA, Dev

Posted: 20 Mar 2002
Updated: 20 Mar 2002
Views: 77,264
Bookmarked: 74 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
18 votes for this Article.
Popularity: 4.74 Rating: 3.78 out of 5
2 votes, 18.2%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
4 votes, 36.4%
4
5 votes, 45.5%
5

Index

Introduction

In 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 Tool

It 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 DataTable attribute and will generate the sql script to create the table.

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 DataTable attribute. To accomplish this take a look at the code below:

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 DataTable attribute. If so it outputs the class name. We need to get all the properties that should be mapped to table columns. That's exactly what the code below does:

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, IDENTITY The property types allowed are: string, int, decimal and DateTime.

The source files included here will create the following assemblies:

  • DAL.dll: contains the attributes
  • Customer.dll: contains the business objects
  • scriptGen.exe: the tool that generates the sql script

Coming up next

In 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.

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

About the Author

xicoloko


XicoLoko is a brazilian developer based in Switzerland.

Occupation: Architect
Company: VisionOne AG
Location: Switzerland Switzerland

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
GeneralAlberto GarcíamemberAlbertoGarciaArdiles8:24 8 Mar '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Mar 2002
Editor: Chris Maunder
Copyright 2002 by xicoloko
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project