CodeSmith Community
Your Code. Your Way. Faster!
Build a Data Access Layer in less than 15 minutes

Download Links

Introduction

In this article you will learn how to build a Data Access Layer using Microsoft’s Enterprise Library in less than 15 minutes using CodeSmith and the .netTiers Template Library.

The Data Access Layer, from here on out referred to as the DAL, is the layer of application functionality that encapsulates all interactions with the database. Typically this type of code is hand written and requires specialized knowledge, not only of .NET, but of the specific data access routines too. Writing the DAL code for an application is one of the most monotonous, time consuming, repetitive, and likely bug-ridden aspects of building software.

For this article we’ll use the sample Northwind database in SQL Server, but these examples will work with any database. And of course, after this article you’ll no longer view writing the DAL for your application as monotonous and time consuming, but quick, easy, and simple!

If you follow this article at the end you will be able to create a complete best practices Data Access Layer in just under 1 minute (the other 14 minutes are for downloading the software the first time).

Code Generation, a brief overview

Code generation, or the use of software tools to generate code, is not a new concept. In fact, code generation has been around for quite some time. In this article I’m going to use CodeSmith as the tool for generating both the code and T-SQL scripts for the DAL.

CodeSmith is a developer productivity tool that enables developers to use templates to control the formatting and desired code output. Therein is the beauty of CodeSmith - software developers still retain full control over the code created through templates. Templates provide the opportunity for people to create new and interesting code reuse and generation libraries, such as the .netTiers templates used in this article.

Step 1 – Setup

The first step is to get the necessary tools (CodeSmith) and templates (.netTiers). CodeSmith is a commercial developer tool, but there is a 30-day free trial we can use for the purpose of this article:

Download and Install CodeSmith

http://www.codesmithtools.com/

CodeSmith comes with a lot of built-in templates and the next service pack will include the .netTiers templates shown in this article.

Now that CodeSmith is installed, download the .netTiers template library:

Download .netTiers Template Library for CodeSmith

http://www.nettiers.com/

On the .netTiers site click on the "Latest Download" link in the left-column; next, click on "available for download" at the top of the page. This will take you to another page where you can download the latest Windows MSI installer.

The last step is to ensure you have a SQL Server database setup and have a connection string you can use to connect to the database.

Step 2 – CodeSmith

After downloading and installing CodeSmith you should be able to open it from All Programs | CodeSmith 3.1 | CodeSmith Studio. Before we use the .netTiers templates you need to familiarize yourself with CodeSmith.

As mentioned in the introduction, CodeSmith is a template driven code generation tool. There is a window on the right of CodeSmith called the Template Explorer. The Template Explorer provides you with a quick and easy way of accessing the templates you’ve installed or written:

To explain the rest of CodeSmith we need a template. Open the Hashtable.cst template from Template Explorer by double-clicking on it.

Hashtable.cst is one of the great sample templates included with CodeSmith and is used to generate strongly typed collections that use the .NET Hashtable type as the base data type. Before we explain the template, let’s quickly look at another window in CodeSmith, the Properties window:

The Properties window allows you to set properties for the template. When using the Hashtable.cst template we need to set some common elements such as the generated ClassName, ItemType, and KeyType. For example, if you wanted to create a strongly typed collection of Person objects accessed by an integer with a class name of PersonCollection, you would set the ClassName to PersonCollection, the ItemType to Person, and the KeyType to int. You could generate the source for this strongly typed collection now by simply clicking the Run button in CodeSmith (found on the toolbar).

If you took a moment to examine the Hashtable.cst template file you might say to yourself, "This looks a lot like ASP.NET". You’d be correct. CodeSmith templates are modeled after ASP.NET Pages and share many similar ideas. However, whereas ASP.NET Pages are used to generate HTML, CodeSmith Templates are used to generate source files or other text files.

The most important thing to remember about CodeSmith is that CodeSmith does not limit your creativity by forcing you into what code is generated. Since it is template driven the code output is completely controlled by you.

Step 3 – Generate the DAL

Now that you have a basic understanding of CodeSmith I want to show you the .netTiers templates.

Remember, the idea behind CodeSmith is that it allows you to write code faster, with fewer defects. The .netTiers templates take that one step further and create a DAL for you that follows all the recommended Patterns & Practices from the team at Microsoft by the same name.

First we need to add the .netTiers templates to the CodeSmith Template Explorer:

  1. In Template Explorer click on the Open Folder icon to browse for a folder containing templates.
  2. Go to the folder where .netTiers was installed. On my computer this is:
    C:\Program Files\SerialCoder\NetTiers 0.9.2 - Caribert\Templates\
  3. Once this folder is created as a shortcut in Template Explorer, expand it and select NetTiers.cst
  4. Now that the .netTiers templates are installed you need to configure a data source. With the NetTiers.cst template open, open the Properties window and configure a Source Database by clicking on the ellipses:
  5. This opens the Database Picker, we’re going to create a new data source so click on the ellipses in the Database Picker to open the Data Source Manager. In the screen shot below is an example of how this should look (choose a name that let’s you quickly know what database you’re working with):
  6. Test the connection to ensure it works and then back out of these dialog windows by clicking OK. Make sure the new data source is selected.
  7. Finally, set the EntireDatabase property to True, set the NameSpace property to Demo, and set the OutputDirectory property to the directory where you would like the generated files to be located. You will need to create the output directory if it doesn’t exist.

Once you’ve completed these steps your property window for the NetTiers.cst template should look similar to the screenshot below (changes highlighted):

We are not going to show anywhere near the full capabilities of .netTiers in this article or CodeSmith, but we’ve now done enough to generate a DAL. Click the Run button in the CodeSmith toolbar to generate the code.

Step 4 – Review the Generated Code

Open Visual Studio .NET and if you followed the directions above you should find a Demo.sln file in the c:\NetTiers\Northwind_Demo\ directory.

Take a moment and browse the solution and project files in Visual Studio:

You should find 3 projects within the solution:

  • Demo – the main library that contains the classes you will use within your application to interact with the database.
  • Demo.DataAccessLayer – the library containing the data access implementation code.
  • Demo.DataAccessLayer.SqlClient – the library containing the Microsoft Patterns & Practices classes for working with the database.

Step 5 – Compile …and we’re done!

Next, with Visual Studio still open, compile the project.

Congratulations! You now have a Data Access Layer that implements the recommended best practices from the Microsoft Patterns & Practices group for working with a database.

You can now begin using your new Data Access Layer in other Visual Studio .NET projects. For example, below is code to retrieve, update and then delete an employee record.

using Demo.DataAccessLayer.SqlClient;

// Select by primary key
Employee employee = SqlDataRepository.EmployeeProvider.GetByEmployeeID(13);
employee.FirstName = "John";
employee.LastName = "Doe";

// Save changes
SqlDataRepository.EmployeeProvider.Save(employee);

// Delete record
SqlDataRepository.EmployeeProvider.Delete(employee);

For more information on how to use the generated DAL, take a look at the .netTiers wiki here:http://nettiers.com/DocumentationPage.ashx

Remember all of the Data Access Layer code was generated by templates, so later when you change your database structure you can simply rebuild the DAL again from the templates. Furthermore, you can even extend the templates with your own ideas, comments, naming conventions, patterns, and so on.

Conclusion

The possibilities for CodeSmith templates are limited only by your own creativity. As I’ve demonstrated in this article, CodeSmith is an exceptionally powerful developer productivity tool. Coupled with the .netTiers templates you can write a best practices Data Access Layer for your application in a matter of minutes.

You can also watch a video of this presentation here:

http://community.codesmithtools.com/r.ashx?id=1

One of the fun features added into version 3.1 was a simple "value calculator". The value calculator provides a conservative estimate of the time saved by using CodeSmith:

As shown in the screenshot above, using the .netTiers templates with CodeSmith generated 91,559 lines of code. Assuming a developer can write approximately 50 lines of code per-hour (had we written this manually) writing the code we generated would have taken 1,800 hours. Taking this a step further and assuming that a developer’s time is approximately $60/hour, CodeSmith and .netTiers together saved you 1,800 hours of your life and $109,000 for your company!

So get CodeSmith… and then go ask for a raise.

CodeSmith and .netTiers Resources

If you have questions about CodeSmith, please be sure to visit the CodeSmith community portal at: http://community.codesmithtools.com. The CodeSmith community portal is a great resource where people can share templates, ideas, and help each other.

If you are interested in purchasing CodeSmith, please visit the CodeSmith website at http://www.codesmithtools.com. There you will find the CodeSmith store where you can purchase license keys to unlock the 30-day trial version. If you have other questions, just email sales@codesmithtools.com.

If you have questions about the .netTiers templates, please visit the .netTiers forum at:

http://community.codesmithtools.com/forums/16/ShowForum.aspx


Posted 02-13-2006 12:16 PM by ejsmith
Filed under: ,

Comments

Video Tutorials wrote Build a Data Access Layer in less than 15 minutes (Video)
on 02-13-2006 2:12 PM
This video shows you how to create a Data Access Layer using CodeSmith and the .NetTiers templates in 15 minutes or less.
CodeSmith Announcements wrote .NetTiers Tutorial Available
on 02-13-2006 5:05 PM
In this tutorial you will learn how to build a Data Access Layer using Microsoft’s Enterprise Library...
J-dee.COM - Jon Paul Davies .NET wrote Cool CodeSmith Tutorial
on 02-14-2006 3:45 AM
Very nice tutorial video detailing how to create a best practice Data Access Layer in 15 minutes with...
Rexiology::Work wrote .netTiers templates for CodeSmith...
on 02-14-2006 10:49 AM
 
[via Rob Howard]
Nice post from Rob Howard on introduction of .netTiers templates for CodeSmith....
Luc Gauthier's Weblogs wrote Construire une couche d'accès données avec CodeSmith
on 02-14-2006 11:05 AM
Il y a déjà un bon moment que j'utilise l'excellent outils de génération de code CodeSmith (http://www.codesmithtools.com/)....
Bilal Haidar [MVP] :: Blog wrote Build a Data Access Layer in less than 15 minutes with CodeSmith
on 02-14-2006 11:14 AM
Erick Smith, the founder of CodeSmith, posted a great article on how to create a Data Access Layer in...
rburkhal wrote re: Build a Data Access Layer in less than 15 minutes
on 02-14-2006 8:41 PM
Hi,
Now we need the .NetTiers CPT setup and use.
Rexiology... wrote .netTiers templates for CodeSmith...
on 02-15-2006 12:04 AM
 
crosspost from http://rex.la/blogs/work/
[via Rob Howard]
Nice post from Rob Howard on introduction...
Manish Agrawal wrote Generating DAL (Data Access Layer) using Code Smith
on 02-23-2006 11:11 AM
catsclaw wrote re: Build a Data Access Layer in less than 15 minutes
on 03-06-2006 5:49 PM
This is great, except that I am using VS 2005 and I think the .nettiers scripts only work with VS2003 or VS2000.  If there is a VS2005 version of this same process, I would be TOTALLY stoked!

Any idea when .nettiers will be updated for VS2005 and the new Enterprise Library (Jan 2006)?
ejsmith wrote re: Build a Data Access Layer in less than 15 minutes
on 03-08-2006 7:53 PM
Here are some links for the current .NET 2.0 version of the templates:

Download:
http://community.codesmithtools.com/forums/10777/PostAttachment.aspx

Quick Start Document:
http://community.codesmithtools.com/forums/permalink/9769/9769/ShowThread.aspx#9769
The Mit's Blog wrote GAT et T4 : enfin un générateur
on 03-22-2006 6:07 AM
Ce matin comme beaucoup je pense, je suis tombé sur cette bréve de Dotnetguru :
[News] GAT propose...
chris.strevel [blog] wrote DataGeneration with CodeSmith
on 04-18-2006 9:24 PM
El día de hoy durante nuestro curso estuvimos viendo como crear objetos de acceso a datos en Visual Studio...
David Hayden - Florida .NET Developer - C# and SQL Server wrote Sarasota .NET Developer MSDN Event - CodeSmith - .netTiers - Generate Data Access Layer using Enterprise Library DAAB
on 05-12-2006 4:51 PM
David Hayden - Florida .NET Developer - C# and SQL Server wrote Sarasota .NET Developer MSDN Event - CodeSmith - .netTiers - Generate Data Access Layer using Enterprise Library DAAB
on 05-12-2006 4:52 PM
Dot-A-Lot wrote .netTiers [Via Rob Howard]
on 05-28-2006 1:56 PM
Create a Data Access Layer in less than 15 minutes Eric Smith, and some other folks at Telligent, recently...
Daniels Blog wrote CodeSmith and .NetTeirs
on 07-26-2006 6:43 PM
csgreg wrote re: Build a Data Access Layer in less than 15 minutes
on 08-17-2006 9:44 AM
An updated tutorial would be nice using Nettiers 2 with VS 2005.  The api is different and no longer using Ent Lib config tool to configure Nettiers.  Lots of bad links and incomplete documentation currently out there, would be nice to have a great tuturial like your Feb version.
Lance's Whiteboard wrote Atlas & NetTiers, a match made in heaven (Part 1)
on 08-22-2006 1:29 PM
As mentioned in my previous post, Time to learn Atlas..., I am trying to quickly get up to speed on Atlas
CodeSmith Announcements wrote .netTiers Tutorial Available
on 10-14-2006 9:35 PM

In this tutorial you will learn how to build a Data Access Layer using Microsoft’s Enterprise Library in less than 15 minutes using CodeSmith and the .netTiers Template Library.

guntur juliantoro wrote re: Build a Data Access Layer in less than 15 minutes
on 02-23-2007 9:53 AM

I just tried this code, and I found out that you cannot use any _ in any of your custom stored procedure parameters....any workaround on this?

subvert wrote re: Build a Data Access Layer in less than 15 minutes
on 04-17-2007 11:14 PM

The value calculator is a little silly. Lines of code has never been a good metric for value.

90% of this functionality can be implemented in nHibernate with no code generation, using a single, simple generified DAO. Even the integration tests can be condensed to a single class.

Eric J. Smith wrote Build a Data Access Layer in less than 15 minutes
on 06-12-2007 12:04 PM

“In this article you will learn how to build a Data Access Layer using Microsoft’s Enterprise

Fine Art » Build a Data Access Layer in less than 15 minutes wrote Fine Art » Build a Data Access Layer in less than 15 minutes
on 09-25-2007 5:53 PM

Pingback from  Fine Art » Build a Data Access Layer in less than 15 minutes

http://community.codesmithtools.com/blogs/tutorials/archive/2006/02/13/nettiers.aspx wrote http://community.codesmithtools.com/blogs/tutorials/archive/2006/02/13/nettiers.aspx
on 03-23-2008 2:25 AM
danielkemper.de wrote Linksammlung ASP.NET
on 05-30-2008 2:37 AM

Linksammlung ASP.NET

How to get relational data into an object? | keyongtech wrote How to get relational data into an object? | keyongtech
on 01-21-2009 7:20 PM

Pingback from  How to get relational data into an object? | keyongtech

harikrishna wrote re: Build a Data Access Layer in less than 15 minutes
on 01-28-2009 1:52 AM

exception handeling need to be made easier

Copyright © 2008 CodeSmith Tools, LLC
Powered by Community Server (Commercial Edition), by Telligent Systems