Useful links of the week #21

Abstract SQL
ADO.NET Sql classes wrapper; provides a clean fluent interface library that allows you to write very concise code and avoid the repetitiveness of ADO.NET. It can be used in all types of applications, even supports CLR stored procedures. It is written in C# 2.0.

Gridify for ASP .NET MVC
Easy solution for grids on top of ASP.NET MVC
Make grids from your data tables in a really lightweight manner! How lightweight? Well, exactly TWO line changes. You don’t have to add new action parameters or anything. Really simple!

Paypal adaptive payments using .Net (C#)
This is a C# project to help you interface with the PayPal adaptive payments API.

In The Box
In the Box is a high quality, multi-media training that is consumed within Visual Studio 2010.  Content is navigated and delivered using a next generation computer based training (CBT) experience, the Visual Studio 2010 Feature Extension

ASP .Net 4.0 Code Samples Collection

10 Essential Tools to build ASP .Net Websites

TweetSharp
TweetSharp is the most complete, and most effective client library for communicating with Twitter. TweetSharp works how you want to: simple service, fluent interface, or LINQ provider. It’s designed so that you write less, and get more, from Twitter’s API.

Team Foundation Server Administration Tool 2.1
TFS Administration Tool 2.1, is the first version of the TFS Administration Tool which is built on top of the Team Foundation Server 2010 object model. TFS Administration Tool 2.1 can be installed on machines that are running either Team Explorer 2010, or Team Foundation Server 2010.

Visual Studio 2010 Code Samples 2010-12-13

How to write fluent interface with C# and Lambda

The Interface Segregation Principle (ISP)

The Interface Segregation Principle (ISP) is another principle about OOD.

It simply states that:

“CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES
THAT THEY DON’T USE”

If we return back to the first OOD principle, the Single Responsibility Principle, it can be said that this principle should also apply to interfaces or to abstract class, in addition to the concrete classes.

Therefore, one interface should mean one responsibility, without creating the so-called “fat interfaces”, i.e. interfaces that contain too many methods/properties that relate to more than 1 responsibility.

To find an example of violation of this principle does not need to go too far, just peek inside the .Net framework itself .

If we take a look inside the abstract class MembershipProvider, which is the class which all providers, default and custom,  inherit from, we’ll be looking at 28 abstract methods, which must be provide an implementation in case of creation of custom membership provider.

  public abstract void Initialize(string name,
      NameValueCollection config)
  public abstract string ApplicationName { get; set; }
  public abstract bool EnablePasswordReset { get; }
  public abstract bool EnablePasswordRetrieval { get; }
  public abstract bool RequiresQuestionAndAnswer { get; }
  public abstract bool RequiresUniqueEmail { get; }
  public abstract int MaxInvalidPasswordAttempts { get; }
  public abstract int PasswordAttemptWindow { get; }
  public abstract MembershipPasswordFormat PasswordFormat { get; }
  public abstract int MinRequiredNonAlphanumericCharacters { get; }
  public abstract int MinRequiredPasswordLength { get; }
  public abstract string PasswordStrengthRegularExpression { get; }
  public abstract bool ChangePassword(string username,
      string oldPwd, string newPwd)
  public abstract bool ChangePasswordQuestionAndAnswer(
      string username, string password, string newPwdQuestion,
      string newPwdAnswer)
  public abstract MembershipUser CreateUser(string username,
      string password, string email, string passwordQuestion,
      string passwordAnswer, bool isApproved, object
      providerUserKey, out MembershipCreateStatus status)
  public abstract bool DeleteUser(string username,
      bool deleteAllRelatedData)
  public abstract MembershipUserCollection GetAllUsers(int  
     pageIndex,
     int pageSize, out int totalRecords)
  public abstract int GetNumberOfUsersOnline()
  public abstract string GetPassword(string username, string answer)
  public abstract MembershipUser GetUser(string username,
      bool userIsOnline)
  public abstract MembershipUser GetUser(object providerUserKey,
      bool userIsOnline)
  public abstract bool UnlockUser(string username)
  public abstract string GetUserNameByEmail(string email)
  public abstract string ResetPassword(string username,
      string answer)
  public abstract void UpdateUser(MembershipUser user)
  public abstract bool ValidateUser(string username,
      string password)
  public abstract MembershipUserCollection FindUsersByName(
      string usernameToMatch, int pageIndex, int pageSize,
      out int totalRecords)

This methods has to do with authentication, persistence, retrieve of user based on various criteria, password management, and so on.

All these abstract methods must be implemented even if the client code that uses the feature is only interested in some of these aspects mentioned above.

In this way, the methods that you do not care end up being defined as follows:

public override int GetNumberOfUsersOnline()
{
    throw new NotImplementedException();
}

This approach has several problems, including:

  • Indirect and especially useless  coupling between clients that use the functionality. If additional functionality is required, all clients must be modified, even those not interested in new features;
  • Clients are misled because some methods explicitly raise an exception;
  • Code maintenance is more difficult;

The Liskov Substitution Principle (LSP)

The Liskov Substitution Principle (LSP) is another principle  that has to do with software design and namely with inheritance.

This principle takes its name from Barbara Liskov, U.S. scientist in computer science.

This principle simply states that

“CLASSES THAT USE REFERENCES TO BASE CLASSES MUST BE  ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT”

In other words, if we have a class (say Class C)  that use a reference to a base class inside (Class B), then Class C MUST be able to use a reference with ANY derivate class of Class B (present and future), without knowing it and especially without changing the logical behaviour.

It ‘s very easy to violate this principle when overriding virtual methods defined in a base class.

Let’s consider an example like this:

public class BaseClass
{
   protected double n1;
   protected double n2;
  
   public BaseClass(double a, double b)
   {
      this.n1 = a;
      this.n2 = b;
   }
  
   public virtual double Multiply()
   {
      return this.n1 * this.n2;
   }
}
 

This class simply accepts 2 double numbers by it’s constructor, and by a virtual method returns the two numbers multiplied together.

Now, let’s create a derived class like this:

public class DerivedClass : BaseClass
{
   const double COEFFICIENT = 1.1;

   public DerivedClass(double a, double b)
       : base(a, b) { }

   public override double Multiply()
   {
      return base.Multiply() * COEFFICIENT;
   }
}
 

This class is derived by the first one and simply overrides the virtual method “Multiply” defining another implementation of it where the result of the multiplication is further multiplied by a fixed coefficient.

Therefore, having a method that takes a reference to BaseClass, like this:

public double DoSomeWork(BaseClass b)
{
   return b.Multiply();
}

we can pass as a parameter any derived class, as in the example below:

BaseClass b = new BaseClass(-5, 20);
double result = DoSomeWork(b);
Console.WriteLine(result);

DerivedClass d= new DerivedClass(-5, 20);
double result2 = DoSomeWork(d);
Console.WriteLine(result2);
 

Very trivial, right ? And everything works fine.

But when you develop your derived class and specifically when the virtual method is redefined, you must pay attention to some situations that, if they occur, involving the violation of the Liskov substitution principle. Specifically, a general rule to keep in mind is that a derived class should *not* require additional conditions or either provide fewer conditions than those required by the base class.

For example, what would happen if you change the redefinition of the method Multiply in this way  ?

 public override double Multiply()
 {
   if (this.n1 < 0)
        throw new InvalidOperationException(
             "Number n1 cannot be negative");
 
    return base.Multiply() * COEFFICIENT;
 }
  

The overridden method adds an additional condition, namely that the parameter n1 cannot be negative by raising an exception, and then is demanding something more than its base class that takes two double numbers instead through its constructor, also providing negative numbers. This additional condition required makes the base class and derived class not interchangeable anymore and therefore the Liskov Substitution Principle is violated.

The LSP can be violated in different ways, but everyone has to do with inheritance. Therefore you must take extreme care when you redefine virtual methods.