Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, 2 September 2008

What's New C# 3: Extension methods

Extension methods allows developer to add extra method to an existing class without creating a derivative of it or without modifying the original class code. Lets take an example of the standard C# library String class. We want to add a method to validate if the string length is zero or not. An extra method can be added to this class by simple implementing a method using extension method syntax. Extension method signature looks like this :

static <returnType> methodName( this CalssToExtend thisObject, additional parameters list.....)

{

methods body

}

So in our example of string class if we add a method called IsZero to return true when check passed; it will look like


public static bool IsZero( this string thisObj )

{

return thisObj.Length== 0;

}
The 'this' word before the first parameter in the method identifies which class this method relates to. In this case it's string class.

A working example is as follows.

=====================

using System.Collections.Generic;

namespace ConsoleApplication1
{
public static class Program
{
private static void Main(string[] args)
{
var postcode = "SL2 8FF";
var flag = postcode.IsPostcode();
// var costs = new List();
// var sum = costs.
}
}

static class Extension
{
///
/// An extension method to String class to check whether this string is a postcode.
///

///
///
public static bool IsPostcode(this string input)
{
return false;
}

///
/// And extension method to List to return sum of all entry of the list
///

///
///
public static double Sum( this IList inputList )
{
var sum = 0.0;
foreach( var item in inputList )
sum += item;
return sum;
}
}
}

====================

Few points to remember:


  • Extension method implementer class has to be static class.

  • All extension methods must be static

Advantage:



  • Don't need to derive a class to extend it. This is specially useful when a class is not derivable.

  • Methods are visible in intellisense drop down menu.

  • Extension can be added to interfaces. When a extension is added to a Interface it's applied/available to all its derive classes.

Tuesday, 13 November 2007

nHibernate and multithreading - I

nHibernate is no doubt is a great open source utility to encapsulate database connectivity. It has lot of feature that can make your system robust. You can read more details about nHibernate from nHibernate.org.

But when it comes to multi-threading programming you have to be very cautious in your development. There are plenty of place it can work differently than you want it to be. Concurrency is a big think to keep in mind. I don't mean that nHibernate can't handle multi-threading or concurrent request. Rather is very efficient in multi threading, but the programmer has to be vigilant while setting properties and use method call to manipulate or to retrieve data.



In this post I want to discuss about stale data in multithreaded environment cache. Lets consider a web service which exposes two methods UpdateUser() to update user profile and GetUser() to retrieve a user details. In a typical scenario application uses this web service will make a call to UpdateUser and then GetUser to read updated details.

In some scenario it might happen that the GetUser return old user profile, instead of latest updated one. At a first glance it might look impossible, as you are updating first and then calling get. But it happens.

Lets see what going on the the web service side. When any one makes a request to a web service web server handle using separate thread. In most scenario server uses thread pooling to minimise thread creation overhead. Along with that as nHibernate suggests the Session is not shared among threads. the resultant is that the primary cache is separate for separate threads. resultant is calls reading data from different data cache. So now even if GetUser is called after UpdateUser if they are handled by different thread in the server, the UserProfile object may be out of sync. This is happens b'cus nHibernate try to read data from cache if it's available.

To solve this issue caller simply has make sure that nHibernate picks up the data from database not from the cache. This can be done in very simple way. Use pessimistic Locking. ISession provides Lock() to do that.

example:

work in thread one:

ISessionFactory sessions;
IList profiles;
UserProfile profile;
....
ISession session = sessions.OpenSession();
...
ICriteria criteria = session.CreateCriteria(typeof(UserProfile));
profiles= criteria.List();

....
//do some updating

Profile profile = profiles[0];
profile.HomePhone = "0208 212 3333334";
session.SaveOrUpdate(profile);


while reading data:

Profile profileToRead = profiles[0];
session.Lock( profileToRead, LockMode.Read); // this will ensure profile updating, and will not return stale data.

In this scenario Session does a version number check of the cache object with actual data store. If they are different it updated the cache with latest version of the object and thus it always returns updated data.