Archive for May, 2007

No Silver Bullet vs. Agile Software

In 1986, Frederick P. Brooks published No Silver Bullet, a small treatise that makes an important distinction in terms of software development–between accidental difficulties and inherent difficulties.

Accidental difficulties are things like a slow compiler, a difficult language syntax, etc. — things which can, by and far, be surmounted by technology, eventually–faster CPUs, more memory, and everyone’s happy!

Inherent difficulties, on the other hand, deal with difficulties inherent to software that will not be overcome by technology.  Things like software complexity, good design, integration of complex parts, and so on.

While Brooks makes some good points, we can extract, from his article, why Agile Software methodologies increase the success rate of software projects by a great degree.

Complexity: Software is made up of multiple differing and complex parts.  System-wide complexity is difficult to overcome.  The larger a piece of software becomes, the more complex.  Agile software solves this by using architectural spikes and iterative design–only the minimum necessary architecture comes out, and iterative design keeps the relative complexity low.

Conformity: Software is made up of multiple different parts and offers many different interfaces to mesh–between two classes, between interfaces, between users and the system, between the system and the underlying OS.  Agile software solves this with early integration and iterative usability testing, where integration between different parties becomes resolved very early on.

Changeability: Software, once released, comes under pressure to change–change from external users, from coders, from testers, from stakeholders.  Agile software solves this with iterative development which includes refactoring and burn-down–so architectural changes get implemented and bugs get fixed, before problems can grow and expand.

Invisibility/Abstraction: Software deals with invisible and abstract entities–classes, interfaces, delegates, database query plans, pointers–concepts that take serious brain-power to comprehend.  While not unique to agile software, agile software solves this with UML diagrams, class diagrams, and other concrete geometrics.

So while there may be "no silver bullet" in software development, Agile Software methodologies provide a strong and compelling base from which to deal with the inherent complexities of software development.

By Ashiq Alibhai

How To Isolate Code To Run only on Certain Servers

Occasionally with websites, the need arises to have a block of code that executes only on a particular set of servers–whether local development servers, or client servers, or production servers.  In particular, you may find this useful if you have code you want to run only on development servers.  How, then, can you accomplish this?

One simple yet elegant solution is to make a class which provides the information you need.  Observe the following class:

public sealed class HostSafety

        private static string[] safeHosts = {
           // etc.

Notice HostSafety is sealed–everything in it is static, so there’s no overhead in terms of extra data stored, and you don’t need to create instances to use it.

Then, simply add a function to check if the current host is safe:

public static bool IsCurrentHostSafe()
    string userHost = HttpContext.Current.Request.Url.Host;
    foreach (string curHost in HostSafety.safeHosts)
        if (curHost == userHost)
            return true;

    return false;

That’s it!  All you need to do is wrap your safe-host code in an if(…) function call!

public void someMethod() {
    // Do some stuff ...
    // Do more stuff ...
    // ...

    // Read from a developer-only file
    if (HostSafety.IsCurrentHostSafe()) {
       StreamReader debugFileReader = ...
       // etc.

…and voila, you have your host-safe code!

By Ashiq Alibhai

Use Enum (C#) instead of magic numbers

Enumerations (enums) make your code much more readable and understandable.  If you are ever writing code that looks like

if (_mode == "5")

which I see time and time again, STOP!  It will be so difficult for future developers to understand what your code is supposed to do, and it will require you to add another line saying

// mode 5 is read only 

However, if you did something nicer like,

if (_mode == Mode.Read)

You have automatically documented your code and made it easier to nderstand.  One way to reduce the amount of documentation that you have to put in the code is to use tricks such as Enums (C#) to make the code sufficiently clear.

A magic number is a number you use in the code, that is ‘magical’, in the sense that nobody knows where it came from.  Like the above example, 5 is a magic number.

Instead of writing the following code:

int _pageMode;
if (_pageMode == 2) {
    Response.Write("You are in edit mode");
} else if (_pageMode == 3) {
    Response.Write("You are in read only mode");

You can write the following C# code to take advantage of enums:

enum Mode {
Default, Edit, ReadOnly
Mode _pageMode;

if (_pageMode == Mode.Default)
    Response.Write("Default mode");
} else if (_pageMode == Mode.Edit)
    Response.Write("Edit mode");

There is more to enums, you can give each item in the enum a value as well.  If you are storing your enum in a viewstate or session, you can still use it as an enum.  For example,

if ((Mode)Session["mode"] == Mode.Read)
New - Aug 14 07 - Enum is VB.NET is also similarly easy


enum Age
Young = 50
Old = 70
TooOld = 90
end enum

or just

enum Season
end enum

Usage VB.NET

if mySeason = Season.Fall then
  'do something
end if


  1. enum (C# – msdn)
  2. A nice article on enums by Nishant

It is not necessary to convert the Mode.Read into an integer and then compare it as integer values.

Proper Use of Static Functions

Here is a quick refresher on static functions.  A static function is static because you do not need to create an instance of the

class in order to use it.  Some popular static functions are located in the Math library, for example, Math.Min(x,y).  When you
are calling Math.Min, you do not have to type in Math m = new Math(); before calling the Min function, you simply call it.
Another good example of where you can find static functions is in the SqlHelper Source Code.

Here is some example of code that I feel should have been written as a static function.

if (!this.IsPostBack)
	DataOperations od = new DataOperations();
	myGrid.DataSource = od.GetSalesRecords(_user, _company, _startDate);

And The GetSalesRecords function is implemented as follows:

public DataTable GetSalesRecords(int user, int company, DateTime d)

    SqlParameter[] sqlParams = new SqlParameter[] { 
        new SqlParameter("@user", user),
        new SqlParameter("@company", company),
        new SqlParameter("@d", d)

    string sql = "select * from sales where userid=@user and companyID=@company and recorddate > @d";
    return SqlHelper.ExecuteDataset(conn, CommandType.Text, sql, sqlParams);

This is a perfectly good example of when this GetSalesRecords(..) function should be implemented as a static function.

Here is a quick checklist to judge whether your function should be static.

  1. You have no need of class or member variables
  2. Compact – You have all the information you need passed to you from the parameters
  3. Stateless – You can do your operation and return the result without having to store anything permanently or keep any state.

Thus, this function should be static!  Here’s an idea how you can fix it

1. Make your function obsolete and put the second parameter as false.  This will cause it to give a warning on compile, but
will not cause an error and your site will still compile.  This allows you to phase it out slowly.

	[Obsolete("Use static version instead",false)]
	public DataTable GetSalesRecords(int user, int company, DateTime d)
    	return GetSalesRecordCompact(user,company,d);

2. Create your overload that is static and will do the actual meat and potatoes of the operation (i.e. in the above example,
all we have to do is copy our original function)

	/// <summary>
	/// Returns the sales records for the user <paramref name="user"/> 
	/// in the company <paramref name="company "/> after date <paramref name="d"/>
	/// </summary>
	/// <param name="user">the user name</param>
	/// <param name="company">company id</param>
	/// <param name="d">beginning date</param>
	/// <returns></returns>
	public static DataTable GetSalesRecords(int user, int company, DateTime d)
	SqlParameter[] sqlParams = new SqlParameter[] {
		new SqlParameter("@user", user),
	        new SqlParameter("@company", company),
        	new SqlParameter("@d", d)

	string sql = "select * from sales where userid=@user and companyID=@company and recorddate > @d";
	return SqlHelper.ExecuteDataset(conn, CommandType.Text, sql, sqlParams);

As a bonus, you can also put proper XML documentation.  As well, create the SqlParameters array in the most efficient way

This way, you do not have any code duplication (all your business logic is in the static function), you have added a note to
future developers to stop using the non-static version, and they will save the original call of creating the object unecessarily!

However, if your function was storing some member variables for the class, and needed to be persisted, then in that case
this whole argument does not apply and you can pretend you never saw this article.

What are some of the consequences of static functions?

  • You need to consider thread safety – you have to make sure that the function is ‘thread safe’, i.e. it can be executed
    multiple times without each one thread interfering with the other.
  • More to come here

Cheers to static functions!

Prefix tables with dbo. in your SQL

Here’s a SQL power tip – to speed up your query and stored procedure executions a bit.  Prefix your tables and stored procedures with dbo.

Select * from dbo.[Users] where UserID = @UserID


EXEC dbo.UsersLookup ….

By prefixing with dbo, Our database makes one less call.  Normally, when you do not use the dbo keyword, on a query such as Select * from Users where UserID = @UserID, it will first check the user’s schema to see if that table exists for them. 

i.e. if you are logged on as server administrator (sa), it will attempt to do a
Select * from sa.Users where UserID = @UserID

Then, if that table does not exist under sa, it will try again under dbo (main schema)
Normally, this is 1 extra redundant call that you want to avoid.

This helps the database engine encourage re-use and caching of queries.  The database engine will have an easier time recognizing that this is the same query that was just called, and will be more likely to cache and re-use your execution and decrease execution run time.

Visual SourceSafe 2005 Tip (VS2005) – Keywords

Using Visual SourceSafe, we can put some text at the top of our source file and it will automatically be updated by SourceSafe when you check in the file.  See below for an example.

// Last updated by:
// $Author: Sameera $
// $Date: 4/13/07 11:16a $

This will allow you to quickly see who was the last person who checked in the file.

HttpContext Can Break Object Oriented Principles

A situation came up when I was coding..  I was debugging a certain class, and somehow some value was mysteriously changing, and when I did a search in the code, I could not figure out how it was changing.  Somehow the Session value for "SalesCode" was changing yet there was no reference to it.

The culprit??  One of the functions in a business object in App_Code was using HttpContext.Current without having that explained and documented and also without having it as one of the parameters..

Thus, using HttpContext.Current can break OOP (Object Oriented Principles).

If you want to make a change to the HttpContext (Session, or what not), pass it!

Here is the code that was messing with my session:

public static void SetSalesCode(int newValue)
   HttpContext.Current.Session["SalesCode"] = newValue;

I modified the code, so that it still achieves the same effect, but it is much more obvious what it
does and easier to track down

public static void SetSalesCode(int newValue, HttpContext htc)
   htc.Session["SalesCode"] = newValue;

Successful Server Migration using the HOSTS file

When migrating your site from one server to another there are many factors involved in having a successful and transparent migration with no down time.One of the tricks you can use to test your site after you have moved servers is to edit your Windows HOSTS file in order to ‘trick’ your machine into thinking that your site is actually somewhere else, even before updating the nameservers.

For example, you have your live site – on a server with IP address, but you are moving it to another server now because you have outgrown your original server.

Say you already have uploaded the files to the new server and as well populated your mySql or Sql Server databases.

Now, before updating the A record on the nameservers, you can update your local machine to point to the new server, say by editing the file C:\WINDOWS\system32\drivers\etc\HOSTS (its a simple text file, you can use notepad to edit it)

Simply add one line 

that way your local machine will know the new IP address and you can make sure the site is working perfectly before updating the nameservers to point to the new address.

Make sure you reload your browser after doing this.

Also, a nice tip is to use a browser extension/addon that shows you the IP address of the site you are visiting, so you can confirm its the new site.

.NET Predicates (and a .RemoveAll() example)

A predicate is a function that returns true or false and can be used for example to filter your results.. For example your .NET RemoveAll(…) function can actually do things like:

Remove all records that say …

  • "start with S"
  • or "are 5 letters long"
  • etc etc..
  • whatever you wanna do.. GO WILD!

And knowing this, plus using our .NET 2.0 anonymous methods, we can do the above filtering in a single line!  We don’t even need to write a special predicate function.

For example if you have a general list of ints, and you want to remove all ints that are equal to the value 5, you can do the following:

yourList.RemoveAll(new System.Predicate<int>( delegate(int val) { return (val == 5); }));

The keyword delegate(int val) { … } allows you to create an anonymous method.

Follow Up

Benefits of using ConnectionStrings Element Instead of AppSettings

In .NET 1.0 we used ConfigurationSettings instead of ConfigurationManager

With .NET 2.0 we can use ConfigurationManager.ConnectionStrings, and gain 3 benefits.  Actually, if you just did a search and replace and changed ConfigurationSettings.AppSettings to ConfigurationManager.AppSettings you would not get the same special benefits that you would get by using the special ConnectionStrings element.

Here are three benefits you will get:

  1. We can encrypt our connection strings on the fly using reg_iis.exe (or by other methods)
  2. We can add SQL Cache Dependencies
  3. By putting connection strings in the right place, we can take advantage of any new features that come out that use the ConnectionStrings element

 The incorrect way of storing connection strings:

Dim objConn As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))

Here is the new node we can add to Web.Config

     <connectionStrings >

            <add name="DefaultConnection" connectionString="server=(yourserver);uid=whatever;pwd=your_plaintext_stored_password;database=DEV123"

providerName="System.Data.SqlClient" />


To use the updated connectionstring element, see below (C# example)


This is the preferred way to store and use your connectionstrings in .NET 2.0, allows you to do advanced stuff like encrypting your connection strings, using sqlParameterCache, etc..  If you want to encrypt your connection strings, the first step is putting them in the right place

ConfigurationManager is part of the Microsoft Application Blocks

Follow Up

There are other benefits too that I did not document here.

Optimization WordPress Plugins & Solutions by W3 EDGE