Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET

Introduction to Model Driven Development with AndroMDA (Part 2)

Rate me:
Please Sign up or sign in to vote.
3.67/5 (10 votes)
31 Jul 2006CPOL16 min read 57.1K   229   24   1
This article provides a step-by-step example of how to create a basic application with model driven development using AndroMDA for code generation.

Introduction

This is part 2 of a two-part article. Please be sure you have read Part 1 before attempting this tutorial.

The Sample Application - TimeTracker

The AndroMDA tutorial uses a sample application to explain how to use AndroMDA. This application is called TimeTracker. Before we dive into the design and implementation of TimeTracker, we need to understand the business problem it is trying to solve.

Northwind Corporation uses a paper based system to track the time of their employees. This process is highly inefficient, and hence the CIO of Northwind has tasked you to create an online time tracking system called TimeTracker. Unfortunately, he wants the system delivered by next week, and if you can't meet this deadline, he will give away the job to someone else. Suddenly, you remember a conversation with your friend the other day where he was raving about how AndroMDA can generate large portions of an application from business level specifications. You say to yourself, "If this is really true, it will help me meet my deadline. Let's give AndroMDA a try". So you accept the CIO's offer and get to work.

Your first stop is at the office of the Director of Human Resources. You ask her to describe the current time tracking process. She says, "At the beginning of every week, each person picks up a new timecard from the supply room. As they work on different tasks, they record their start and stop times on this timecard. Every task has a task ID, which they look up from the employee handbook. At the end of the week, people submit their timecards to their managers for approval. A manager can either approve or reject the timecard. If rejected, they must put a comment on the timecard stating the reason for rejection. The submitter of the timecard must then make necessary corrections and resubmit the timecard for approval." You politely ask the director for a copy of a typical timecard. Here's what she gives you.

Sample Timecard

Environment Setup

Here we will download and install the components required for development with AndroMDA. This tutorial assumes that you have:

  • Microsoft Visual Studio 2005 installed. Note that the Express edition will not work as it does not have add-in support.
  • Microsoft SQL Server installed. Any version will work (2000, 2005, MSDE, etc.).

There are a number of directories involved with the various pieces of software installed. The default installation paths for these programs are listed below. Please feel free to change the installation paths depending on your configuration and personal preferences. For example, you may choose to install programs on the D: drive instead of the C: drive. However, note that some programs don't work well if there are spaces in their pathname, so it is advisable to stick to the general recommendations listed below.

Default/Recommended PathPurpose
C:\Program Files\Java\jre1.5.0_xxJava Runtime Engine (xx is the update number)
C:\Program Files\Java\jdk1.5.0_xxJava Development Kit (xx is the update number)
C:\Documents and Settings\your user name\.mavenMaven local repository
C:\Program Files\Apache Software Foundation\Maven 2.0.4Maven
C:\Program Files\Microsoft SQL ServerMicrosoft SQL Server
C:\Program Files\Microsoft Visual Studio 8Microsoft Visual Studio
C:\Program Files\Android VSAndroid/VS
C:\Program Files\MagicDraw UML Community Edition MagicDraw

As you follow the software install instructions, select the default options in the installers unless otherwise instructed.

  1. Install the Java Runtime

  2. AndroMDA is written in Java, and needs the Java runtime to execute. Don't get nervous, you won't have to worry about it after it is installed or write any Java code.

    1. Download either the JRE 5.0 from http://java.com/en/download/ or the J2SE Development Kit 5.0 from http://java.sun.com/j2se/1.5.0/download.jsp.
    2. Run the installer.
  3. Install Maven

  4. Maven is a build tool similar to ant and nant. It is used to run AndroMDA.

    1. Download the Maven binary zip from http://maven.apache.org. At the time of this writing, this is maven-2.0.4-bin.zip.
    2. Create a folder for Maven (example: C:\Program Files\Apache Software Foundation\Maven 2.0.4).
    3. Unpack the Maven zip into this folder.
  5. Configure the Environment

    1. Open the Windows Control Panel, then the System Control Panel. Click the Advanced tab and click the Environment Variables button. Ensure the following environment variables are set:
    2. VariableValueExample
      M2_HOMEMaven installation directoryC:\Program Files\Apache Software Foundation\Maven 2.0.4
      JAVA_HOMEJava installation directoryC:\Program Files\Java\jdk1.5.0
      PATHThe system search path. You need to add M2_HOME\bin and JAVA_HOME\bin to the path.%JAVA_HOME%\bin;%M2_HOME%\bin
    3. It is recommended you restart after making these changes
  6. Install MagicDraw 9.5 Community Edition

  7. AndroMDA reads UML 1.4 models that have been saved in XMI 1.2 format. MagicDraw 9.5 is a UML 1.4 modeling tool that saves XMI model files. There is a newer version of MagicDraw, but it uses UML 2.0 which AndroMDA does not yet support.

    1. Download the MagicDraw 9.5 Community Edition installer from http://www.magicdraw.com/. Do not download MagicDraw 11.x as it does not work with AndroMDA.
    2. Run the installer. Make sure to select the install application specific JRE option.
    3. Run MagicDraw.
    4. Click the Options menu and select Environment. Select the Path Variables option in the tree on the left.
    5. Click the Add button and enter the values below. Be sure to replace your user name with your system username.
    6. Field NameValue
      Namemaven1.repository
      ValueC:\Documents and Settings\your user name\.maven\repository
      DescriptionMaven 1 repository
    7. (Optional) In the main MagicDraw window, select Options | Look and Feel | Windows to enable a more Windows-like interface.
  8. Install Android/VS

  9. Android/VS is a Visual Studio 2005 add-in that makes working with AndroMDA and Visual Studio much easier.

    1. Download the latest version of the Android/VS installer from http://sourceforge.net/project/showfiles.php?group_id=154568.
    2. Run the installer.

Create TimeTracker Application

Now that you have your environment setup, you can start using AndroMDA in your projects. This section will guide you through creating the base TimeTracker solution. These are the same steps you would follow when you are starting your own application. Please note, the TimeTracker completed sample is available at the top of this article.

Couple of tips before we start:

  • Please follow the instructions in this tutorial very carefully and precisely. Do not take any shortcuts, as doing so will only waste your time. There is a reason for every step in the tutorial. You will not find any fluff here!
  • It is recommended to use the latest version of Firefox or Internet Explorer to read this tutorial.

Create the Solution

  1. Run Visual Studio 2005.
  2. Select File | New Project.
  3. Create a new blank solution, found under Other Project Types | Visual Studio Solutions. Name the solution Northwind.TimeTracker.
  4. New Solution Dialog

  5. Click OK.

Run the Solution Wizard

  1. Click the Run MDA Solution Wizard Run MDA Solution Wizard and click Next to exit the welcome page.
  2. Accept the default project name of Northwind.TimeTracker, and click Next.
  3. Accept the default common project name of Northwind.TimeTracker.Common, and click Next.
  4. Accept the default core project name of Northwind.TimeTracker.Core, and click Next.
  5. Accept the default checked Create schema export project option and the default project name of Northwind.TimeTracker.SchemaExport, and click Next.
  6. Check the Configure web project box and accept the default project name of Northwind.TimeTracker.Web. Check the Add membership support box and click Next.
  7. Accept the default web common project name of Northwind.TimeTracker.Web.Common, and click Next.
  8. Verify that your project settings look like the screenshot below, and click Next to run the wizard.
  9. Solution Wizard Settings

  10. Your solution is now configured for use with AndroMDA. Here is a list of what was created for you:
    • mda directory: AndroMDA configuration files and an empty model. Because we checked membership support, basic user and roles entities were added automatically.
    • Northwind.TimeTracker.Web: Web site with NHibernate support.
    • Northwind.TimeTracker.Common: Common project. This is where AndroMDA generates value objects and enumerations.
    • Northwind.TimeTracker.Core: Core project. This is where AndroMDA generates entities, NHibernate mappings, services, and data access objects.
    • Northwind.TimeTracker.SchemaExport: A console application that will generate the database schema from your model. It can optionally export the schema to a running database.
    • Northwind.TimeTracker.Web.Common: Project for classes and controls the web site will use. Because we checked membership support, an ASP.NET 2.0 MembershipProvider that uses the user and role entities was created for us, and the web site is pre-configured to use it.

Open the UML Model

  1. Click the Open Model button to open your project's UML model.
  2. Open Model Button

  3. MagicDraw will open and it will automatically load the model that was generated by the add-in. An initial package structure was created by the add-in using the name of the solution you selected. Additionally, a User entity and some supporting classes were created and added to the model because the membership support option was selected.
  4. Initial Model

Leave MagicDraw open for now, as we will be adding to the model.

Creating the TimeTracker Database

We need to create a database for TimeTracker to store the timecards. While you can use any type of database NHibernate supports in your project, this tutorial will focus on SQL Server 2000, 2005, and MSDE. Here are the steps to creating a database for TimeTracker:

Creating the Database with SQL Server 2000/2005

  1. Run Enterprise Manager (2000) or SQL Server management Console (2005).
  2. Expand your local server (2000) or connect to your local server (2005).
  3. Right click the Databases folder and select Create new database.
  4. Enter the database name NorthwindTimeTracker and click OK.

Creating the Database with MSDE

  1. Open a console window by clicking Start | Run, typing cmd, and clicking OK.
  2. Type osql -U sa -P password -S localhost\myinstance with your MSDE login credentials and myinstance changed to your instance name.
  3. Type the following to create a database called NorthwindTimeTracker:
  4. 1> use master
    2:> go
    1> CREATE DATABASE NorthwindTimeTracker
    2> go
    The CREATE DATABASE process is allocating 0.63 MB on disk 'NorthwindTimeTracker'
    The CREATE DATABASE process is allocating 0.49 MB on disk 'NorthwindTimeTracker_log'

Entities

In this section, you will create your first entity using AndroMDA. We will create an entity called Timecard that will represent a timecard in the application. We will associate it with the User object, which will be the person that submitted the timecard. Our finished entity diagram will look like this:

Entity Diagram

Note that we have marked the Timecard class with a stereotype of Entity. This tells AndroMDA that Timecard is an Entity as opposed to other type of model elements such as Enumeration or EmbeddedValue. Stereotypes determine what pattern of code AndroMDA will generate for a model element. More specifically, they determine which AndroMDA code generation templates will be triggered.

Also note that we have marked the attributes to be of type Date and String. These are not .NET types, but rather, in model driven architecture, the model is kept independent of technology and hence all model elements are defined in terms of platform independent types. So Date and String in this context are platform independent types. When we run AndroMDA to generate code, it will translate platform independent types into platform dependent types such as System.String and System.DateTime. If we were to use the same model to generate a Java application, AndroMDA will translate String into java.lang.String, which is the Java equivalent of System.String. As you can see, a key advantage of the model driven approach is that your investment in the business models is preserved even as technologies come and go.

Now, let's add the Timecard entity to the model:

  1. Create a new diagram by right clicking on the Domain package and clicking New Diagram | Class Diagram. Set the name of the diagram to Entity Diagram and click OK.
  2. Click the Class tool Class Tool in the toolbar and make a new class on the diagram surface. Double click on the class, name it Timecard, and add the Entity stereotype to it.
  3. Right click on the TimecardVO object and select Insert new attribute. Add these public attributes to the class:
    • startDate of type Date.
    • comments of type String.
  4. We now want to relate the User entity to the Timecard entity. Drag the User class onto the diagram. If it looks very cluttered, you can right click on it and select Symbol Properties. Uncheck the Show Tagged Values option under General, and also uncheck Show Attributes Properties in the Attributes section. Finally click OK, right click on the User class again, and select Autosize.
  5. Because each user can submit many timecards, we need to create an association that defines this relationship. Click the Association tool, and draw an association between the Timecard class and the User class.
  6. Set the association multiplicity to * on the timecard end of the association by right clicking on the association end near the Timecard entity and selecting *.
  7. Set the name of the timecards association endpoint by right clicking on the association end near the Timecard entity and select Edit name. Name the end +timecards.
  8. Set the association multiplicity to 1 on the user end of the association by right clicking on the association end near the User entity and selecting 1.
  9. Set the name of the submitter association endpoint by right clicking on the association end near the User entity and selecting Edit name. Name the end +submitter.

Value Objects

We will now add a value object called TimecardVO to the model. This will be the value object for the Timecard entity, and we will keep it simple by mapping it one-to-one with the Timecard entity. The model for TimecardVO looks like this:

Value Object Diagram

The TimeTracker front end will receive TimecardVO objects from the time tracking service. Typically, items that the front end will need to display are put in value objects. For example, we could add a string with the submitting user's name to TimecardVO, even though this information may or may not be stored in the actual Timecard entity.

  1. Create a new diagram by right clicking on the VO package and clicking New Diagram | Class Diagram. Set the name of the diagram to Value Object Diagram and click OK.
  2. Click the Class tool Class Tool in the toolbar and make a new class on the surface. Double click on the class, name it TimecardVO, and add the Value Object stereotype to it.
  3. Right click on the TimecardVO object and select Insert new attribute. Add three public attributes to the class:
    • id of type Long.
    • startDate of type Date.
    • comments of type String.
  4. Drag the Timecard class onto the diagram. Click the Dependency tool Dependency Tool and draw a dependency from the Timecard class to the TimecardVO class. Adding this dependency will tell AndroMDA that the Timecard entity will be converted to TimecardVO objects, and it will generate helper code in the generated TimecardDao data access class to support translation between them.
  5. Click the Class tool Class Tool in the toolbar and make a new class on the surface. Double click on the class and name it TimecardVO[]. We do not need to add a stereotype to it. This will create a type that we can use to return collections of TimecardVO objects from service methods.

Services

We now have the the entities and value objects modeled, and we need to add services that will operate on these objects. Here we will create the TimeTrackingService. For this tutorial, we will create a method on the service called GetAllTimecards, which will return all the timecards in the system. The model for the TimeTrackingService looks like this:

Service Diagram

  1. Create a new diagram by right clicking on the Service package and clicking New Diagram | Class Diagram. Set the name of the diagram to Service Diagram and click OK.
  2. Click the Class tool Class Tool in the toolbar and make a new class on the surface. Double click on the class, name it TimeTrackingService, and add the Service stereotype to it.
  3. Right click on the TimeTrackingService class and select Insert New Operation. Add a method called GetAllTimecards() that returns type TimecardVO[].
  4. Note: Sometimes if you type TimecardVO[] on the diagram surface, MagicDraw will set the type to TimecardVO with a return type modifier of []. This is incorrect, as you want the return type to be TimecardVO[] with no return type modifier set. This can be changed by double clicking on the method name and using the Operation Specification dialog.

  5. Drag the Timecard class onto the diagram. Click the Dependency tool Dependency Tool and draw a dependency from the TimeTrackingService class to the Timecard class. Adding this dependency tells AndroMDA to make it easy to access the timecard data access class from methods inside in the TimeTrackingService class.
  6. Save your model by clicking the Save Save Tool tool.

Display Timecards

Now that we have our model created and saved, we can write some code to see some results. First, we will generate code with AndroMDA, and then we will implement the GetAllTimecards service method. After that, we will export the schema to our TimeTracker database, and finally we will create a screen that lists all the timecards in the database.

Generate Code

First we will generate code from our model. Switch to Visual Studio, and you can either select the Build | Rebuild All option or you can click the Generate Generate button. This will run AndroMDA inside a Visual Studio tool window and generate the entity classes, hibernate mappings, data access objects, and service interfaces and base classes.

GeneratedFiles

When this operation is complete, you will see a number of files generated. Files that you don't need to edit and are always generated are placed in the target directory. Files that require you to fill in some code will be placed in the src directory if they don't exist. If they do exist, they will not be overwritten so your changes will be preserved.

Writing the Entity to VO Conversion Code

The first thing we need to do is write some code that will convert between Timecard entities and TimecardVO value objects.

  1. Open the TimecardDaoImpl.cs file.
  2. Note, the generated file has already created the method stubs ready for us to implement. Fill these methods in. Your final code should look like this:
  3. C#
    using Northwind.TimeTracker.VO;
    
    public class TimecardDaoImpl : TimecardDaoBase
    {
       public override TimecardVO ToTimecardVO(Timecard entity)
       {
          // Entity to VO conversion
          TimecardVO valueObject = new TimecardVO();
    
          valueObject.StartDate = entity.StartDate;
          valueObject.Comments = entity.Comments;
          valueObject.Id = entity.Id;
    
          return valueObject;
       }
    
       public override Timecard TimecardVOToEntity(TimecardVO timecardVO)
       {
          // VO to entity conversion
          Timecard entity = Timecard.Factory.newInstance();
    
          entity.StartDate = timecardVO.StartDate;
          entity.Comments = timecardVO.Comments;
    
          return entity;
       }
    }

Implement the Service Method

Now we can implement the method in our TimeTrackingService.

  1. Open the TimeTrackingServiceImpl.cs file.
  2. Note, the generated file has already created the method stubs ready for us to implement. In addition, the service base class already has a method called GetAllTimecards(). When called, it will start an NHibernate transaction and then call our method: HandleGetAllTimecards(). Here is one example implementation of the GetAllTimecards method:
  3. C#
    using System.Collections;
    using Northwind.TimeTracker.VO;
    
    public class TimeTrackingServiceImpl : TimeTrackingServiceBase
    {
       protected override TimecardVO[] HandleGetAllTimecards()
       {
           IList timecards = this.TimecardDao.LoadAll();
           IList timecardVOs = this.TimecardDao.ToTimecardVOList(timecards);
           TimecardVO[] voarray = new TimecardVO[timecardVOs.Count];
           timecardVOs.CopyTo(voarray, 0);
           return voarray;
       }
    }

Generate Database Schema

Now we will generate the database schema to store the timecards.

  1. Click the Export Schema button. This will run the schema export console project in Visual Studio. The AndroMDA Visual Studio add-in defaults are set to pass the export option so it will write the schema to your database.
  2. After the schema is created, we need to create some test data. Run the following SQL in any tool (Query Analyzer, Management Studio, Toad, etc.). You can also run the database/testdata.sql file that is in the completed downloadable solution.
  3. SQL
    DELETE FROM TIMECARD
    DELETE FROM AppUser
    SET IDENTITY_INSERT AppUser ON
    INSERT INTO AppUser    (ID, UserName, Password, Email, IsActive, Comment, CreationDate)
                VALUES  (1, 'bob', 'n/a', 'bob@bob.net', 1, '', getdate())
    SET IDENTITY_INSERT AppUser OFF
    SET IDENTITY_INSERT TIMECARD ON
    INSERT INTO TIMECARD (ID, START_DATE, COMMENTS, SUBMITTER_FK)
                  VALUES (1, getdate(), 'This is the first timecard', 1)
    INSERT INTO TIMECARD (ID, START_DATE, COMMENTS, SUBMITTER_FK)
                  VALUES (2, getdate(), 'This is another timecard', 1)
    SET IDENTITY_INSERT TIMECARD OFF
    GO

Create a Test Page

Now that we have our service code, database schema, and test data, we can create a web page that lists all the timecards.

  1. Right click on the web project Northwind.TimeTracker.Web and select Add new item.
  2. Select Web Form and accept the default name of Default.aspx by clicking Add.
  3. Add a grid to the page by adding the following code to Default.aspx:
  4. ASP.NET
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID"/>
            <asp:BoundField DataField="StartDate" HeaderText="StartDate"/>
            <asp:BoundField DataField="Comments" HeaderText="Comments"/>
        </Columns>
    </asp:GridView>
  5. Add the code to get the timecards and bind to the grid by adding the following code to Default.aspx.cs:
  6. C#
    using Northwind.TimeTracker.Service;
    using Northwind.TimeTracker.VO;
    
    public partial class _Default : System.Web.UI.Page
    {
       protected void Page_Load(object sender, EventArgs e)
       {
          if (!IsPostBack)
          {
             ITimeTrackingService service = new TimeTrackingServiceImpl();
             TimecardVO[] timecards = service.GetAllTimecards();
             GridView1.DataSource = timecards;
             GridView1.DataBind();
          }
       }
    }
  7. Right click on the web project and select View in browser.

You should see a list of two timecards. Congratulations, you have created your first application using AndroMDA!

Further Reading

AndroMDA

NHibernate

History

  • 1.0 - First release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I work for the Sapient Corporation.

Comments and Discussions

 
GeneralCould u plz help me Pin
Sherief M.2-Aug-07 2:41
Sherief M.2-Aug-07 2:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.