Oddball statistics about my blog

As I’ve mentioned before I’m using Google Analytics to see what people are
interested in on my blog and website. Some of the statistics are beginning to
settle down now. So, here are some interesting stats (well, they are interesting
to me)

Most read blog entry was about installing Visual Studio 2005 on Vista

Top three browsers are IE (69%), Firefox (28%) and Opera (2%)

97% of visitors use Windows, 2% use an Apple Macintosh.

95% of visitors have their screen resolution set at 1024×768 or higher. The
most common setting is 1280×1024 which accounts for 29% of visitors.

1% of visitors came from an IP address registered to Microsoft Corp.

What are developer forums for?

An interesting question. One that seems to have an obvious answer. But there have been a couple of people in the last week that seem to have asked a forum full of random software developers a question they should be asking their client/customer.

I’m not exactly sure why that might be, however, I can possibly guess.

A few weeks ago I asked the question Why is it so hard to hire good software developers? and my colleague also commented on the types of developer that pass through our recruitment process. After that experience I can understand that some developers might have been hired on being able to talk smooth throughout the interview process. Then they get the job and realise that they can’t actually do it. For fear of being fired they jump onto internet forums and seek any type of help they can.

Their lack of ability means that they have some difficulty in working out questions that they should already know the answer to versus questions that they really ought to be asking their client.

Lets take an example. One person was writing a tourist reservation system. He asked what should happen if a person makes a booking without going through a travel agent. This question can’t be answered on a forum for SQL Server. It can only be answered by the client or the business analyst that is liaising with the client.

The question I have to ask these people is: How would a random developer know what your business requirements are?

Another person was a bit more wide ranging in their request. They wanted to know how to develop a “real estate site”. Since the basic principle isn’t any different to any other interactive website surely they should have been asking their client what they wanted in the website.

Maybe I’m wrong in all of this, it is only my idle speculation. If you have a better idea of why some people are asking questions on forums that they should be asking their client or customer I’d like to know.

Tags:

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: