What is a DAL? (Part 2)

In my last post about the DAL I presented a very basic DAL based on a static class. This is fine for small applications, but for larger applications the limitations will soon start to show themselves.

In this post I’ll convert the DAL to a series of singletons so that each singleton operates on a different part of the database.

First of all, I should explain what a singleton is. A singleton is a class that has only one instance. The way that single instance is generated is controlled from the class itself.

When some code wants to use the singleton it calls a static property called Instance to get the one and only instance of the class. The property checks to see if there is already an instance available and if not creates it. This instance is stored in a private static field on the class. To ensure that only one instance of the class is ever created

The following is the DAL with just the parts that make it a singleton

    public class InvoiceDal
    {
        /// <summary>
        /// A private field to hold the only instance of this class
        /// </summary>
        private static InvoiceDal instance;

        /// <summary>
        /// A private constructor so that the only thing that can
        /// construct this class is itself
        /// </summary>
        private InvoiceDal()
        {
            // Do initialisation stuff here.
        }

        /// <summary>
        /// A public property that retrieves the only instance of the
        /// class
        /// </summary>
        public static InvoiceDal Instance
        {
            get
            {
                if (instance == null)
                    instance = new InvoiceDal();
                return instance;
            }
        }
    }

Now the methods from the original static DAL (see previous post) can be carried over almost as they are. It is just the static keyword that has to be removed.

But, the point of this post is to refactor the old static DAL into a number of DAL classes where each class represents some component. The part given already represents the invoicing system. The next part will be for the stock inventory system.

It should, hopefully, be obvious that part of the DAL given already will be needed again. The lazy way is to just copy and paste the methods into a new DAL class. This is wasteful and the poor sod that has to maintain the code will not thank you. In practice what tends to happen is that, in your absence, you will be the butt of all jokes and your name will be dragged through the mud. This is something you don’t want to happen to you.

So, instead an abstract base class will be created which contains the common parts of the DAL. Certain decisions need to be made about goes in the base class. For example, is the base class responsible for figuring out what connection string to use? If you are only going to connect to one database then it certainly does seem to be a good choice. What if you need to (or expect to) connect to multiple databases? In those situations the derived class may be the best place to figure out the connection string. For this example, I’ll assume that multiple database are in use, but all from the same type of database system (e.g. Different databases running on SQL Server). I’ll come on to different database systems later in the series.

The abstract base class looks like this:

public abstract class DalBase
{
    private static string connectionString;

    protected DalBase()
    {
    }

    /// <summary>
    /// Builds the command object with an appropriate connection and sets
    /// the stored procedure name.
    /// </summary>
    /// <param name="storedProcedureName">The name of the stored
    /// procedure</param>
    /// <returns>The command object</returns>
    protected SqlCommand BuildCommand(string storedProcedureName)
    {
        // Create a connection to the database.
        SqlConnection connection = new SqlConnection(connectionString);

        // Create the command object - The named stored procedure
        // will be called when needed.
        SqlCommand result = new SqlCommand(storedProcedureName,
            connection);
        result.CommandType = CommandType.StoredProcedure;
        return result;
    }

    /// <summary>
    /// Builds a DataAdapter that can be used for retrieving the results
    /// of queries
    /// </summary>
    /// <param name="storedProcedureName">The name of the stored
    /// procedure</param>
    /// <returns>A data adapter</returns>
    protected SqlDataAdapter BuildBasicQuery(string storedProcedureName)
    {
        SqlCommand cmd = BuildCommand(storedProcedureName);

        // Set up the data adapter to use the command already setup.
        SqlDataAdapter result = new SqlDataAdapter(cmd);
        return result;
    }
}

And the derived class looks like this:

public class InvoiceDal : DalBase
{

    /// <summary>
    /// A private field to hold the only instance of this class
    /// </summary>
    private static InvoiceDal instance;

    /// <summary>
    /// A private constructor so that the only thing that can
    /// construct this class is itself
    /// </summary>
    private InvoiceDal()
    {
        connectionString =
            ConfigurationManager.AppSettings["InvoiceConnectionString"];
    }

    /// <summary>
    /// A public property that retrieves the only instance of the class
    /// </summary>
    public static InvoiceDal Instance
    {
        get
        {
            if (instance == null)
                instance = new InvoiceDal();
            return instance;
        }
    }

    /// <summary>
    /// A sample public method. There are no parameters, it simply calls
    /// a stored procedure that retrieves all the products
    /// </summary>
    /// <returns>A DataTable containing the product data</returns>
    public DataTable GetAllProducts()
    {
        SqlDataAdapter dataAdapter = BuildBasicQuery("GetAllProducts");

        // Get the result set from the database and return it
        DataTable result = new DataTable();
        dataAdapter.Fill(result);
        return result;
    }

    /// <summary>
    /// A sample public method. It takes one parameter which is passed
    /// to the database
    /// </summary>
    /// <param name="invoiceNumber">A number which identifies the
    /// invoice</param>
    /// <returns>A dataset containing the details of the required
    /// invoice</returns>
    public DataSet GetInvoice(int invoiceNumber)
    {
        SqlDataAdapter dataAdapter = BuildBasicQuery("GetInvoice");
        dataAdapter.SelectCommand.Parameters.AddWithValue(
            "@invoiceNumber", invoiceNumber);

        DataSet result = new DataSet();
        dataAdapter.Fill(result);
        return result;
    }

    /// <summary>
    /// A sample public method. Creates an invoice in the database and
    /// returns the invoice number to the calling code.
    /// </summary>
    /// <param name="customerId">The id of the customer</param>
    /// <param name="billingAddressId">The id of the billing
    /// address</param>
    /// <param name="date">The date of the invoice</param>
    /// <returns>The invoice number</returns>
    public int CreateInvoice(int customerId, int billingAddressId,
        DateTime date)
    {
        SqlCommand cmd = BuildCommand("CreateInvoice");
        cmd.Parameters.AddWithValue("@customerId", customerId);
        cmd.Parameters.AddWithValue("@billingAddressId",
            billingAddressId);
        cmd.Parameters.AddWithValue("@date", date);

        cmd.Connection.Open();
        int result = (int)cmd.ExecuteScalar();
        cmd.Connection.Close();
        return result;
    }

}

It is now possible to create more of these derived classes for various parts of the application all sharing the same common code in the base class.

Tags:

Why not to sign up with Quechup

There isn’t a lot that I can say about this that hasn’t already been said countless times before. It you search for quechup on the ‘net you’ll find hundreds of people complaining about it.

However, I’d never even heard of it until this morning when I received an email from Simon Harriyott. It said:

Simon Harriyott (**email address**)
has invited you as a friend on Quechup…
…the social networking platform sweeping the globe

And in the small print:

You received this because Simon Harriyott (**email address**) knows and agreed to invite you. You will only receive one invite from **email address**. Quechup will not spam or sell your email address

 Except Simon didn’t invite me, the sign up process seems to spam your contacts list.

So, hopefully you will see this before you receive an invite from someone and accidentally spam your contact list.

 Simon also has a blog entry on the subject if you want to read more on how bad Quechup are.

Tags:

Then and Now

 

Recently a post was put up on Code Project that was basically a direct copy of a homework assignment. I don’t answer questions for people’s homework. I have enough trouble trying to hire a good developer as it is without contributing to another generation of useless code monkeys.

Anyway, the question was in two parts. The first part, in summary, was to write some code that calculates powers. e.g. 23=8; 74=2401; etc. by just using simple multiplication. The second part was to solve the same problem but without using a multiplication operator.

This has got me thinking for most of the afternoon, even after watching an episode of Judge John Deed (I’m on holiday). What I was thinking about was the different ways in which I’d tackle the problem. They way I would have tackled the problem when I was a student, and the way I’d do it now.

Then (15 years ago as a student) I’d have created a console application, read in a couple of integers from the keyboard and performed the calculation all in one horrible Main function. Then I would have thrown a few random integers at the command line to satisfy myself that it would work. If it didn’t I’d hack away at it until it did. There wouldn’t be any consistency in the testing as I’d be throwing different integers at it.

Now, because I was curious what the answer was, I did the following: I created a test assembly and wrote some unit tests so that each time I ran the tests it would be the same tests. Then I created a method that performed the calculation. It took two integers, x and y, and calculates xy using the multiplication technique. Then I ran my tests to see if it worked. Once that was working, I re-wrote the method to use the addition only technique. Then I ran the tests again to ensure that I still got the same results.

Tags:

Article Theft

It seems there is a website out there called BuzzyCode. Naturally it is a software development website and it contains lots of information about how to do certain things in software. All very well and good so far, except for one thing. There is a lot of plagarised work on the site.

A few days ago, the site was discovered by a member of Code Project, and he soon discovered that it contained a lot of ripped off articles that were originally written by people who are members of Code Project. Some members of Code Project managed to speak to (or otherwise communicate with) the people that run the site and it would appear that their story doesn’t add up.

Original Real Author Plagarised Copy
PleaseWaitButton ASP.NET Server Control Mike Ellison Stolen
ASP.NET Query control Mike Ellison Stolen
Dynamically Loading a DLL – MC++ Nishant Sivakumar Stolen
Displaying an empty value in a combo box in a C# Windows application using MS Access Johann Lazarus Allegedly Stolen
A Sample Chat Application using Mike Schwarz’s AJAX Library K.sundar Allegedly Stolen
Passing an Object between Two .NET Windows Forms Larry1024 Allegedly Stolen
Ye Aulde Application Starter miklovan Allegedly Stolen
Pocket 1945 – A C# .NET CF Shooter Jonas Follesø Allegedly Stolen

Heck they even seem to steal from each other (or perhaps forgot that an article had already been copied and added it under a different author’s name). For example: http://www.buzzycode.com/ShowArticles-id_493.aspx and http://www.buzzycode.com/ShowArticles-id_596.aspx are almost identical  – Mostly the formatting is different.

Finally, in a wonderfully ironic twist their website contains an article on reasons to offshore development to India which contains this titbit: “Indians are also known for their honesty and integrity therefore you can be rest assured that all intellectual and other virtual property will not be infringed upon and belong to the original party.” Maybe they should have added “except those that set up this website”

More information can be found on Code Project as many threads started up regarding the problem:

Thread Date
BuzzyCode JOTD 16:31 31-Aug-2007
Grumble mumble 07:09 31-Aug-2007
Vasudevan Deepak Kumar 04:47 31-Aug-2007
BuzzyCode = dotnetspider 07:48 30-Aug-2007
Who is BuzzyCode.com ???? 09:39 29-Aug-2007
Hey Nish – Look at this 06:24 29-Aug-2007

(Note: Times are local to Toronto, Canada)

In short, the website in question hardly shows the community spirit it claims to. If they are indeed unaware that they there are a large number of plagarised articles on their site (which is what they claim) and they genuinly want to do something about it by the time they get through deleting the copies I don’t think there will be much left.

Pedes vallis viridis (The Glasgow Pedestrian)

The Glasgow pedestrian (pedes vallis viridis) is a very odd beast. Its actions go against Darwinian evolution. Its behaviour so at odds with its environment that it should have caused its own extinction. But some how it survives.

I cite two specific examples that I’ve witnessed in recent weeks.

The first was in the evening. A car was driving down St. Vincent Street and this old guy with his head down looking determinedly at the ground stormed into the road. The poor driver didn’t have anywhere to go. He hit the brakes but too late. The pedestrian was hit and he got catapulted into the air.

The driver was naturally very shocked and got out of his car to see if the old boy was okay. The man just picked him self off the ground shouted at no one in particular “I’ve got to get to the bus station” and stormed off up Buchanan Street. The driver was just bewildered.

The second incident, and the one to spark off this blog entry, was today on my way home from work. A taxi was travelling down Argyle Street and some guy decides that the best time to cross the street was right now before the taxi passed. The driver hit the brakes and the guy jumped back a bit. The taxi stopped just centimetres away from the pedestrian.

Then the pedestrian did the oddest thing. He placed both palms on the bonnet of the taxi and jumped into the air to the other side of the taxi while making a Michael Jackson-like “Ooww!!” sounds. Then he danced back into the path of the taxi, looked at the driver and said “Ya weeeeeee jobbaaeeeee”

What is a DAL?

I occasionally see posts on forums asking for help with some database
problem. Then I see they’ve been using the the wizards in Visual Studio (which
is okay for a beginner, but should really be ditched once the basic concepts
have been learned). I suggest that they use a DAL and I get lots of positive
signals back that they’ll do that in future. Then a week or two later they’ve
got themselves into another problem and they’re still using wizard generated
code.

So, it occurred to me that just saying “Use a DAL” doesn’t mean anything. If
someone told me that I need to use the finkle-widget pattern I wouldn’t know
what they are talking about. And if a person has never heard the term DAL
before, or never had it explained to them, then it is just as useful as saying
“use the finkle-widget pattern”

So, I figured it would be a good idea to show what a very basic DAL looks
like and to explain what it is.

A DAL is a Data Abstraction Layer. It is the part of the application that is
responsible for communicating with a data source. That data source is typically
a database, but it can be anything you like, such as an XML file, a plain text
file or anything else that data can be read from or written to.

In this example it will be a static class that communicates with a SQL
Server. It picks up the connection string
from the config file. It will communicate with stored procedures and return
DataTables, DataSets or single values. It doesn’t do everything a DAL could do,
but it shows the basic functionality.

Whenever I create DAL classes I try and think about them as if they are a
proxy for a group of actual stored procedures. I give the methods the same name
as the stored procedures, I give each method the same parameter names as the
stored procedure.

A DAL class has to mange the connection, so in this example I have a static
initialiser that gets the connection string from the config file and stores
that.

        private static string connectionString;
        static Dal()         {             connectionString =
                ConfigurationManager.AppSettings["ConnectionString"];         }

On each query a new connection object is created. The reason for this is that
the recommendation is that you acquire-query-release. Acquire a connection,
perform your query, then release the connection back to the pool.

            cmd.Connection.Open();
            int result = (int)cmd.ExecuteScalar();
            cmd.Connection.Close();

The connection Open / Close calls are not necessary when using a DataAdapter
as it will open the connection and then close it again in the Fill method. If
the connection was open before Fill is called then it will stay open.

There are two helper methods that are not publicly available. They are
BuildCommand and BuildBasicQuery.

BuildCommand creates the connection and command object and attaches the
connection to the command. It also tells the command the name of the stored
procedure that is to be called.

BuildBasicQuery uses BuildCommand, but then attaches the command to a
DataAdapter so that it can be used to obtain query results.

The full code of the sample DAL is below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;

namespace Cam.DataAbstractionLayer
{
    public static class Dal
    {
        private static string connectionString;

        /// <summary>
        /// The static initialiser will be called the first time any
        /// method on the class is called. This ensures that the
        /// connection string is available.
        /// </summary>
        static Dal()
        {
            connectionString =
                ConfigurationManager.AppSettings["ConnectionString"];
        }


        /// <summary>
        /// Builds the command object with an appropriate connection and
        /// sets the stored procedure name.
        /// </summary>
        /// <param name="storedProcedureName">The name of the stored
        /// procedure</param>
        /// <returns>The command object</returns>
        private static SqlCommand BuildCommand(string storedProcedureName)
        {
            // Create a connection to the database.
            SqlConnection connection = new SqlConnection(connectionString);

            // Create the command object - The named stored procedure
            // will be called when needed.
            SqlCommand result = new SqlCommand(storedProcedureName,
                connection);
            result.CommandType = CommandType.StoredProcedure;
            return result;
        }

        /// <summary>
        /// Builds a DataAdapter that can be used for retrieving the
        /// results of queries
        /// </summary>
        /// <param name="storedProcedureName">The name of the stored
        /// procedure</param>
        /// <returns>A data adapter</returns>
        private static SqlDataAdapter BuildBasicQuery(
            string storedProcedureName)
        {
            SqlCommand cmd = BuildCommand(storedProcedureName);

            // Set up the data adapter to use the command already setup.
            SqlDataAdapter result = new SqlDataAdapter(cmd);
            return result;
        }

        /// <summary>
        /// A sample public method. There are no parameters, it simply
        /// calls a stored procedure that retrieves all the products
        /// </summary>
        /// <returns>A DataTable containing the product data</returns>
        public static DataTable GetAllProducts()
        {
            SqlDataAdapter dataAdapter = BuildBasicQuery("GetAllProducts");

            // Get the result set from the database and return it
            DataTable result = new DataTable();
            dataAdapter.Fill(result);
            return result;
        }

        /// <summary>
        /// A sample public method. It takes one parameter which is
        /// passed to the database.
        /// </summary>
        /// <param name="invoiceNumber">A number which identifies the
        /// invoice</param>
        /// <returns>A dataset containing the details of the required
        /// invoice</returns>
        public static DataSet GetInvoice(int invoiceNumber)
        {
            SqlDataAdapter dataAdapter = BuildBasicQuery("GetInvoice");
            dataAdapter.SelectCommand.Parameters.AddWithValue(
                "@invoiceNumber", invoiceNumber);

            DataSet result = new DataSet();
            dataAdapter.Fill(result);
            return result;
        }

        /// <summary>
        /// A sample public method. Creates an invoice in the database
        /// and returns the invoice number to the calling code.
        /// </summary>
        /// <param name="customerId">The id of the customer</param>
        /// <param name="billingAddressId">The id of the billing
        /// address</param>
        /// <param name="date">The date of the invoice</param>
        /// <returns>The invoice number</returns>
        public static int CreateInvoice(int customerId,
            int billingAddressId, DateTime date)
        {
            SqlCommand cmd = BuildCommand("CreateInvoice");
            cmd.Parameters.AddWithValue("@customerId", customerId);
            cmd.Parameters.AddWithValue("@billingAddressId",
                billingAddressId);
            cmd.Parameters.AddWithValue("@date", date);

            cmd.Connection.Open();
            int result = (int)cmd.ExecuteScalar();
            cmd.Connection.Close();
            return result;
        }
    }
}

So, that is that. A very basic introduction to creating a DAL.

Tags:

More Sony Rootkit mayhem

A couple of years ago I blogged about a badly written Rootkit Sony were using to hide DRM software that hackers managed to abuse to hide their malware. And after that debacle you would have thought Sony would have learnt their lesson. But no… They’re at it again it seems.

After that bit of absurdity I decided to boycott Sony products and I managed to go all the way until a couple of months ago when I got a new phone (and it was mostly because I wasn’t paying enough attention to the brand and more to the feature set). Looks like I’ll be boycotting them again – which is a pity for them as I was looking at buying a new PVR DVD Recorder and of the ones I’ve looked at so far Sony had the only one with all the features that I wanted. Looks like I’ll just have to keep looking.

You can find out more from this article on ComputerWorld.com: Deja vu all over again: Sony uses Rootkits, charges F-Secure.

Tags:

db4o: An Embeddable Database Engine for Object-Oriented Environments

Just posted details about this event for Scottish Developers in Glasgow.

The unique design of db4o’s native object database engine makes it the ideal choice to be embedded in equipment and devices, in packaged software running on mobile or desktop platforms, or in real-time control systems – in short: in all Java and .NET environments, where no database administrator (DBA) is present. db4o is used by some of the world’s most innovative companies, including Ricoh, Boeing, BMW, Bosch, Seagate, and Intel.

Jim Paterson describes the key features of db4o, and shows how to save objects in the database, use the db4o query mechanisms, control transactions and object activation, refactor databases, replicate data to a relational database and use db4o in a web app. You will also find out about extensive the developer resources provided by the db4o community.

Jim is a Lecturer in the School of Engineering and Computing at Glasgow Caledonian University. He is an author of “The Definitive Guide to db4o”, the first book to be published about db4o, and has written articles for the onJava and ASP Today websites. He has a particular interest in teaching software development. He has a PhD in Physics, and worked previously as a research physicist and as a software engineer.

Map of the venue showing nearby transport links

Room 16 is on Level 2 of the Continuing Professional Development Centre. The CPDC is on the left side (just past the bookshop) as you enter the university from the pedestrian entrance on Cowcaddens Road.

The event is FREE and all are welcome.

Tags:

How to… Run a .NET application without the framework

This is a question that comes up on forums with surprising regularity. It is usually at the point the poster is trying to run an application on someone else’s computer or create an autorun application or similar and discovers they they can’t unless the person already has the appropriate framework installed.

Well, never fear, there is a solution, albeit an expensive one. It is the Salamander .NET Linker, Native Compiler and Mini-Deployment Tool.

Finally, a disclaimer: I’ve never tried the above tool. I have no need for it. The only reason this post exists is that so many people have asked the question that I’m creating the post for my own reference purposes only.

Tags:

Curious about stats on my blog and website

Recently I added Google Analytics to my website and blog. It has been quite interesting to see what statistics it gave back.

For my blog a large number of people never leave the home page with 17% of all hits there. I do have quite a few recent posts up there and I guess there isn’t any reason for them to go any further than that.

The next most popular page is a post on “Why is it so hard to hire good software developers?” with 11% of the share. It is a relatively new topic so I’m sure that over time that will drop. However, it isn’t the newest topic around, so perhaps it is something people want to find out about. Perhaps others who are searching for software developers like to hear that there are people in the same boat. For people looking for a job, perhaps there are looking to see what employers are looking for.

What is more interesting is seeing the pages that have been up for a while. With 9% of all page views in the last week is a post on “Visual Studio 2005 on Vista” detailing my troubles trying to get VS2005 installed on Vista. This is obviously a problem that a lot of people are running in to.

With 5% of all page views in the last week is a post about a “SQL Exception because of a timeout”. So it is obvious that people are looking for information on that topic too.

However, what surprised me the most was that the single biggest search term that brought people to my blog was nothing to do with technology. The most searched term to bring people to my blog included the word “chocolate” e.g. “Chocolate Cake” or “Chocolate Crunch”. And it brought them to a page with a recipe for “Chocolate Crunch Cake

On to my website and I was interested to see that the most viewed page was a beginners article on “Passing values between forms in .NET” with a staggering 43% of page views.

The second most viewed page on my website was the article to go with the session I gave at DDD5 on “An Introduction to Mock Objects” with a mere 6% of page views.

So, what about SQL Injection Attacks (the article I consider to be the most important). It has just 4% of page views. Well, at least some people are concerned about database security. I just wish it were more people considering the number of times I see on forums some really poorly written code to get something out of a database.

All in all, I think this information has given me some ideas on what people are interested in and what they want to read. I hope I can therefore provide more information on related subjects that are of use to people.