ASP.NET WebPages Better Ways To Code

We have been using ASP.NET WebPages since early last year. One of the key issues with the framework is coding and the amount of times you might have to repeat yourself. We have already discussed organizing your website, so in this article we will go over a few techniques which can be used to keep to the DRY (Don’t Repeat Yourself) principal.

If you have a data driven website, you might commonly have code which does this:

var db = Database.Open(“dbName”);

string Query = “SELECT * FROM Table Where Id=@0”;

var data = db.QuerySingle(Query, param);

Then on another page you might have the exact same code, but a different query. So how can you stop repeating yourself?  Well the solution is simple: create a class file which has all the database functions you need.

Sponsored Links

The first thing to do is make sure that in your _AppStart.cshtml file you have a global variable called App.Database which contains your database connection string name. The connection string information should go in the web.config file, which applies to those using SQL Server. If not, then provide your database name if you have SQL Server Compact. When you open the database you can do this:

var db = Database.Open((string)App.Database);

This is ideal because if the database name change,s we only need to update one setting in the _AppStart.cshtml file.

Next in the App_Code folder create a class file (it’s best to name the file after your website name).

App_Code Folder

In the Bakery.cs file we have code which looks like this:

using System;
using System.Collections.Generic;
using WebMatrix.Data;
using System.Web;
using System.Web.Caching;
using System.Collections;
using System.Web.Configuration;
using System.Data.Common;

namespace Bakery
{
    public class Bakery
    {
       //methods for this class

    }


public class dbFunctions
    {
       //methods for this class

    }

}

Within the namespaces are the classes and within the classes are the methods we can call. We have many methods we can call depending on what we want to retrieve.

Your first class Bakery should contain general methods which can be used site wide; for example you might want to return the current connection.

The dbFunctions class should be used to access and write data; for example we get:

    public class dbFunctions
    {
        //SET THE DATABASE NAME
        private static string DatabaseName = "bakery";

        //RETRIEVE ALL CATEGORIES
        public static IEnumerable<dynamic> RetrieveCategories()
        {
            var db = Database.Open(DatabaseName);
            return db.Query("SELECT * FROM Category");
        }


        //RETRIEVE ALL PRODUCTS
        public static IEnumerable<dynamic> RetrieveAllProducts()
        {
            var db = Database.Open(DatabaseName);
            return db.Query("SELECT * FROM Products");
        }


        //RETRIEVE ANY ITEM FROM ANY TABLE
        public static dynamic RetrieveItem(string Query, params object[] args)
        {
            var db = Database.Open(DatabaseName);
            return db.QuerySingle(Query, args);
        }


        //RETRIEVE ANY ITEMS FROM ANY TABLE
        public static IEnumerable<dynamic> RetrieveItems(string Query, params object[] args)
        {
            var db = Database.Open(DatabaseName);
            return db.Query(Query, args);
        }


        ///CREATE, UPDATE OR DELETE DATA
        public static dynamic CUD(string Query, params object[] args)
        {

            var db = Database.Open(DatabaseName);
            db.Execute(Query, args);
            return db.GetLastInsertId;
        }

    }

Then in a page we can call any method. However first you have to add the Bakery namespace into scope.

@using Bakery

You don’t have to put the code into a namespace, it’s just a personal preference.

        <h3>Categories</h3>
        <ul>
            @foreach (var c in dbFunctions.RetrieveCategories())
            {
                <li>@c.CategoryName</li>
            }
        </ul>


        <h3>All Products</h3>
         <ul>
            @foreach (var p in dbFunctions.RetrieveAllProducts())
            {
                <li>@p.Name</li>
            }
        </ul>

Now the code you write is much less. All the methods are static; for those who don’t know what static methods are, it’s a method which can be used without initializing the class, and you don’t want to do this all the time.

dbFunctions functions = new dbFunctions();

functions.RetrieveCategories();

This would be unnecessary,  so once we add the namespace we can simply call the method.

Lastly you should add a WebSiteSettings class which can return website settings such as directory locations or API keys stored in the web.config. To learn more about WebsiteSettings see the article below.

Resources:

Bakery Website