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.
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.
||Java Runtime Engine (xx is the update number)
||Java Development Kit (xx is the update number)
|C:\Documents and Settings\your user name\.maven
||Maven local repository
|C:\Program Files\Apache Software Foundation\Maven 2.0.4
|C:\Program Files\Microsoft SQL Server
||Microsoft SQL Server
|C:\Program Files\Microsoft Visual Studio 8
||Microsoft Visual Studio
|C:\Program Files\Android VS
|C:\Program Files\MagicDraw UML Community Edition
As you follow the software install instructions, select the default options in the installers unless otherwise instructed.
Install the Java Runtime
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.
- 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.
- Run the installer.
Maven is a build tool similar to ant and nant. It is used to run AndroMDA.
- Download the Maven binary zip from http://maven.apache.org. At the time of this writing, this is maven-2.0.4-bin.zip.
- Create a folder for Maven (example: C:\Program Files\Apache Software Foundation\Maven 2.0.4).
- Unpack the Maven zip into this folder.
Configure the Environment
- 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:
|Maven installation directory
||C:\Program Files\Apache Software Foundation\Maven 2.0.4
|Java installation directory
|The system search path. You need to add M2_HOME\bin and JAVA_HOME\bin to the path.
- It is recommended you restart after making these changes
Install MagicDraw 9.5 Community Edition
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.
- 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.
- Run the installer. Make sure to select the install application specific JRE option.
- Run MagicDraw.
- Click the Options menu and select Environment. Select the Path Variables option in the tree on the left.
- Click the Add button and enter the values below. Be sure to replace your user name with your system username.
||C:\Documents and Settings\your user name\.maven\repository
||Maven 1 repository
- (Optional) In the main MagicDraw window, select Options | Look and Feel | Windows to enable a more Windows-like interface.
Android/VS is a Visual Studio 2005 add-in that makes working with AndroMDA and Visual Studio much easier.
- Download the latest version of the Android/VS installer from http://sourceforge.net/project/showfiles.php?group_id=154568.
- 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
- Run Visual Studio 2005.
- Select File | New Project.
- Create a new blank solution, found under Other Project Types | Visual Studio Solutions. Name the solution Northwind.TimeTracker.
- Click OK.
Run the Solution Wizard
- Click the Run MDA Solution Wizard and click Next to exit the welcome page.
- Accept the default project name of Northwind.TimeTracker, and click Next.
- Accept the default common project name of Northwind.TimeTracker.Common, and click Next.
- Accept the default core project name of Northwind.TimeTracker.Core, and click Next.
- Accept the default checked Create schema export project option and the default project name of Northwind.TimeTracker.SchemaExport, and click Next.
- 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.
- Accept the default web common project name of Northwind.TimeTracker.Web.Common, and click Next.
- Verify that your project settings look like the screenshot below, and click Next to run the wizard.
- 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
- Click the Open Model button to open your project's UML model.
- 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.
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
- Run Enterprise Manager (2000) or SQL Server management Console (2005).
- Expand your local server (2000) or connect to your local server (2005).
- Right click the Databases folder and select Create new database.
- Enter the database name NorthwindTimeTracker and click OK.
Creating the Database with MSDE
- Open a console window by clicking Start | Run, typing cmd, and clicking OK.
- Type osql -U sa -P password -S localhost\myinstance with your MSDE login credentials and myinstance changed to your instance name.
- Type the following to create a database called NorthwindTimeTracker:
1> use master
1> CREATE DATABASE NorthwindTimeTracker
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'
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:
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
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
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
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.DateTime. If we were to use the same model to generate a Java application, AndroMDA will translate
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:
- 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.
- Click the 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.
- Right click on the TimecardVO object and select Insert new attribute. Add these public attributes to the class:
We now want to relate the
startDate of type
comments of type
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.
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
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 *.
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.
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.
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.
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:
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
- 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.
- Click the 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.
- Right click on the TimecardVO object and select Insert new attribute. Add three public attributes to the class:
id of type
startDate of type
comments of type
Timecard class onto the diagram. Click the 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.
Click the 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.
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:
- 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.
- Click the 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.
- Right click on the
TimeTrackingService class and select Insert New Operation. Add a method called
GetAllTimecards() that returns type
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.
- Drag the
Timecard class onto the diagram. Click the 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
- Save your model by clicking the Save tool.
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.
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 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.
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.
- Open the TimecardDaoImpl.cs file.
- 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:
public class TimecardDaoImpl : TimecardDaoBase
public override TimecardVO ToTimecardVO(Timecard entity)
TimecardVO valueObject = new TimecardVO();
valueObject.StartDate = entity.StartDate;
valueObject.Comments = entity.Comments;
valueObject.Id = entity.Id;
public override Timecard TimecardVOToEntity(TimecardVO timecardVO)
Timecard entity = Timecard.Factory.newInstance();
entity.StartDate = timecardVO.StartDate;
entity.Comments = timecardVO.Comments;
Implement the Service Method
Now we can implement the method in our
- Open the TimeTrackingServiceImpl.cs file.
- 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
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];
Generate Database Schema
Now we will generate the database schema to store the timecards.
- 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.
- 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.
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', 'email@example.com', 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
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.
- Right click on the web project Northwind.TimeTracker.Web and select Add new item.
- Select Web Form and accept the default name of Default.aspx by clicking Add.
- Add a grid to the page by adding the following code to Default.aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<asp:BoundField DataField="ID" HeaderText="ID"/>
<asp:BoundField DataField="StartDate" HeaderText="StartDate"/>
<asp:BoundField DataField="Comments" HeaderText="Comments"/>
- Add the code to get the timecards and bind to the grid by adding the following code to Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
ITimeTrackingService service = new TimeTrackingServiceImpl();
TimecardVO timecards = service.GetAllTimecards();
GridView1.DataSource = timecards;
- 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!