Saturday, July 16, 2011

Extension method (3)

You may use extension method to increase the code readability too. For example, we often ensure that the object instance return by some function is not null before using.

CustomerClass customer = GetCustomerObject();

if (customer == null)
{
   // do this..
}
else
{
   // do that..
}

Wtih the extension method feature in C#, you may declare a new method call IsEmpty() which looks like this:

public static bool IsEmpty(this object obj)
{
  return (obj == null);
}

Now, you may do with your new IsEmpty() method:

CustomerClass customer = GetCustomerObject();

if (customer.IsEmpty())
{
   // do this..
}
else
{
   // do that..
}

Aside from improving the code readability, why we have to declare such IsEmpty() method instead of using "x == null"? This is what you are going to gain if you are using VS2010. When you type "." after the variable and follow by "Is", VS2010 will shortlist the methods that starts with "Is". Press Tab key to auto-complete the method name and you may move on to other code. This definitely will shorten the development time.

Note: you may rename this function to IsNull() or whatsoever.

Thursday, July 7, 2011

Updating database structure

Problem:


How to patch the database structure when upgrading the program?

Solution:


1. Create a class using the 'plug and play' concept (please refers to this topic). This class contains all the SQL scripts to be executed.
2. Upon the application startup, check the database version and run all the necessary SQL script to update the database structure.

Class design:


1. DBUpdate class:
  • This class stores the necessary patch for the given version.
  • Attributes: db_version, release_datetime & sql_script.
2. DBUpdateList class:
  • This class contains the DBUpdate object instance and it is responsible for executing all the patches.
  • Attributes: release_datetime & DBUpdate class type (note: it's not required to instantiate this object or otherwise will take up some memory and slowing down the application startup).

Flow:


1) Get the last patch date/time that stores in the database.
2) Get the list of the patches that is newer than the value get from step 1.
3) Execute all the necessary patches against the database.
4) Get the newest date/time among the patches that has been executed.
5) Update the last patch date/time into the database.
The purpose of storing the last patch date/time is to avoid all the patches being run each time the application starts. So, the application startup performance will not be affected much.

Friday, June 24, 2011

Extension method (2)

In my previous article, I have created an extension method call StrToInt for String class. Now, the question is what if a string object instance is null value and it's calling the extension method? Will the program crash? The answer is NO.

Try this out:

string s = null;
int i = s.StrToInt();

Thursday, April 14, 2011

Extension method

This is a new feature that has been added to C# in C# 3.0. One of the usefulness of extension method is to shorten the codes that we used to write.

For example, we want to convert a string value to integer. Normally, we will write code like this:

int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }

Instead of doing this, we may already have declared a static function which will do the conversion like this:

public class MyClass
    {
        public static int StrToInt(string s)
        {
            int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }
        }
    }

So, we will write our code like this:

int i = MyClass.StrToInt("1234");

Now, with extension method, the data type conversion call will be shorten:

    public static class MyClass
    {
        public static int StrToInt(this string s)
        {
            int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }
        }
    }

    public class Test11
    {
        public void MyTestMethod()
        {
           // We don't have to write like this anymore:
           //int i = MyClass.StrToInt("1234");

           // Now, we can do this:
            int i = "1234".StrToInt();
        }
    }

Wednesday, February 23, 2011

Dynamic sorting using Linq Expression

You may wonder how to avoid hard coding the sorting order in the list. Here is one of the solution using Linq Expression:

class MyClass
{
   public int age { get; set; }
   public string name { get; set; }
}

MyClass[] arr =
{
   new MyClass() {age = 10, name ="abc" },
   new MyClass() {age = 20, name ="xyz" },
   new MyClass() {age = 30, name ="cde" }
};


// create the parameter
ParameterExpression param = Expression.Parameter(typeof(MyClass), "i");

// create the property to be used base on the 
// type (ie, MyClass) in the param variable. 
// you may change the "name" to any other field.
Expression prop = Expression.Property(param, "name");

// construct the lambda expression.
Expression> lambda 
   = Expression.Lambda>(prop, param);

// compile it to a function.
Func compile = lambda.Compile();

// now, we can use the function by passing it 
// to the OrderBy() proc.
var v3 = arr.OrderBy(compile);

string s;
foreach (var item in v3)
{
   s = item.name;
}

Thursday, December 30, 2010

WCF TCP Port Sharing

Check this out. WCF allows you to share the same port among the services.

http://msdn.microsoft.com/en-us/library/ms734772.aspx
http://msdn.microsoft.com/en-us/library/ms731810.aspx

The article below has a diagram that depicts the port sharing:
http://www.codeproject.com/KB/WCF/Port_Sharing__in_WCF.aspx

Configuration:
http://blogs.msdn.com/b/drnick/archive/2006/04/14/configuring-http.aspx

Sunday, November 21, 2010

Open source Zip library

DotNetZip is an open source Zip library which is written in managed code. You may freely use it:

http://dotnetzip.codeplex.com/