Quote for the Week

"Learn to enjoy every moment of your life"

Friday, January 30, 2015

S.O.L.I.D Architecture principle in C# (Part 5)

Continue to Thursday, January 29, 2015
------------------------------------------------------

Dependency Inversion Principle (DIP)


Dependency Inversion Principle or DIP states that:

High-level modules should not depend on low-level modules. Both should depend on abstractions. 
Abstractions should not depend on details. Details should depend on abstractions.

Consider that you are developing an application that deals with user management (creating a user, managing their passwords, etc.). After every user management task you wish to send a notification to the user as well as to the administrator about the activity performed. The following code shows a simplified implementation of this system.

public class EmailNotifier
{
    public void Notify(string email, string message)
    {
        //send email here
    }
}

public class UserManager
{
    EmailNotifier notifier = new EmailNotifier();

    public void CreateUser(string userid,string password,string email)
    {
        //create user here
        notifier.Notify(email, "User created successfully!");
    }

    public void ChangePassword(string userid, string oldpassword,string newpassword)
    {
        //change password here
        notifier.Notify(email, "Password changed successfully");
    }
}
The EmailNotifier class has just one method - Notify() that accepts an email address and a notification message. Inside, it sends an email to the specified address notifying the user of the change. The UserManager class declares an instance of EmailNotifier class and uses it in methods such as CreateUser() and ChangePassword(). So far so good. Now assume that instead of email notification you want to send SMS based notifications. To cater to this change you not only need to write another class (say SMSNotifier) but also need to change UserManager class because UserManager uses EmailNotifier. This problem arises due to the fact that high level module UserManager depends on a concrete low level module EmailNotifier.

Let's change our classes to follow DIP.

public abstract class NotifierBase
{
    public abstract void Notify(string message);
}

public class EmailNotifier:NotifierBase
{
    public string EmailAddress { get; set; }
    public override void Notify(string message)
    {
        //send email here
    }
}

public class SMSNotifier : NotifierBase
{
    public string MobileNumber { get; set; }
    public override void Notify(string message)
    {
        //send SMS here
    }
}

public class UserManager
{
    public NotifierBase Notifier { get; set; } 

    public void CreateUser(string userid,string password,string email)
    {
        //create user here
        Notifier.Notify("User created successfully!");
    }

    public void ChangePassword(string userid, string oldpassword,string newpassword)
    {
        //change password here
        Notifier.Notify("Password changed successfully");
    }
}
Now, the code defines an abstract class NotifierBase that defines the Notify() method. The two classes EmailNotifier and SMSNotifier inherit from the NotifierBase class and provide the necessary implementation details. More importantly the UserManager class no longer uses a specific concrete implementation. It uses a NotifierBase abstraction in the form of the Notifier public property. This public property can be set by the consumer of the UserManager class either to an instance of EmailNotifier class or to an instance of SMSNotifier class or any other class that inherits from NotifierBase class. Thus our code now depends on abstractions and not on the concrete implementation.

Summary

SOLID principles of object oriented programming allow you to write structured and neat code that is easy to extend and maintain. SOLID principles include Single Responsibility Principle (SRP), Open/Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP) and Dependency Inversion Principle (DIP).


Thursday, January 29, 2015

S.O.L.I.D Architecture principle in C# (Part 4)

Continue to Wednesday, January 28, 2015

-----------------------------------------------------

Interface Segregation Principle (ISP)


Interface Segregation Principle or ISP states that:

No client should be forced to depend on methods it does not use. 
Many client-specific interfaces are better than one general-purpose interface.

What does that mean? Let's take an example. Suppose you are building an order processing system that accepts orders from the customers and places them in the system for dispatch and further processing. The orders can be accepted through various channels such as an ecommerce website, telephone and cash on delivery. To deal with this kind of processing you created the following abstract class:

public abstract class OrderProcessor
{
    public abstract bool ValidatePaymentInfo();
    public abstract bool ValidateShippingAddress();
    public abstract void ProcessOrder();
}

The OrderProcessor class has three methods ValidatePaymentInfo(), ValidateShippingAddress() and ProcessOrder(). The ValidatePaymentInfo() method is supposed to validate the credit card information and return true if the information is correct. The ValidateShippingAddress() method is supposed to check whether the address is reachable by the available means of transport and if so return true. Finally, the ProcessOrder() will place an order into the system.

Now, assume that you created two concrete implementations of OrderProcessor as shown below:

public class OnlineOrder:OrderProcessor
{

    public override bool ValidatePaymentInfo()
    {
        return true;
    }

    public override bool ValidateShippingAddress()
    {
        return true;
    }

    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

public class CashOnDeliveryOrder:OrderProcessor
{

    public override bool ValidatePaymentInfo()
    {
        throw new NotImplementedException();
    }

    public override bool ValidateShippingAddress()
    {
        throw new NotImplementedException();
    }

    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

The OnlineOrder class is supposed to be used by some ecommerce application that accepts payments through credit cards. The CashOnDeliveryOrder class is supposed to serve cash on delivery orders. These orders won't accept any credit card payments. They accept only cash payments. Can you see the problem there? The two methods ValidatePaymentInfo() and ValidateShippingAddress() throw NotImplementedException because CashOnDeliverOrder doesn't need these methods. However, since the OrderProcessor class provides a general purpose interface the CashOnDeliveryOrder class is forced to write these methods. Thus ISP is being violated in this example.

Now let's fix the problem. The following code shows the corrected version of the classes:

public abstract class OrderProcessor
{
    public abstract void ProcessOrder();
}

public abstract class OnlineOrderProcessor
{
    public abstract bool ValidatePaymentInfo();
    public abstract bool ValidateShippingAddress();
    public abstract void ProcessOrder();
}
public class ECommerceOrder : OnlineOrderProcessor
{

    public override bool ValidatePaymentInfo()
    {
        return true;
    }

    public override bool ValidateShippingAddress()
    {
        return true;
    }

    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

public class CashOnDeliveryOrder : OrderProcessor
{
    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

The above code defines two abstract classes OrderProcessor and OnlineOrderProcessor. The OrderProcessor has only one method, ProcessOrder() whereas OnlineOrderProcessor has three methods - ValidatePaymentInfo(), ValidateShippingAddress() and ProcessOrder(). The ECommerceOrder class inherits from OnlineOrderProcessor and the CashOnDeliveryOrder class inherits from OrderProcessor. Since OrderProcessor doesn't contain the ValidatePaymentInfo() and ValidateShippingAddress() CashOnDelivery need not write them at all. Thus we created multiple client specific interfaces (OrderProcessor and OnlineOrderProcessor) instead of a generic one.

Wednesday, January 28, 2015

S.O.L.I.D Architecture principle in C# (Part 3)

Continue to Tuesday, January 27, 2015
----------------------------------------------

Liskov Substitution Principle (LSP) :


Liskov Substitution Principle or LSP states that:

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

You must be aware that you can use an object of a derived class anywhere where base class is expected. However, when such a substitution occurs the functionality and correctness of the code shouldn't change. Let's understand this with an example. Suppose you have created a class named SpecialCustomers that maintains a list of special Customers (may be they are special because they are frequent buyers, or they purchase high value items). This class is shown below:

public class SpecialCustomers
{
    List<Customer> list = new List<Customer>();
 
    public virtual void AddCustomer(Customer obj)
    {
        list.Add(obj);
    }
 
    public int Count
    {
        get
        {
            return list.Count;
        }
    }
}

The SpecialCustomers class maintains a List of Customer instances (Customer class is not shown in the code for the sake of simplicity). The AddCustomer() method accepts an instance of Customer and adds to the generic List. The Count property returns the number of Customer elements in the List.

Now, let's assume that you create another class - TopNCustomers - that inherits from the SpecialCustomers class. This class is shown below:

public class TopNCustomers:SpecialCustomers
{
    private int maxCount = 5;
 
    public override void AddCustomer(Customer obj)
    {
        if (Count < maxCount)
        {
            AddCustomer(obj);
        }
        else
        {
            throw new Exception("Only " + maxCount + " customers can be added.");
        }
    }
}

The TopNCustomers class overrides the AddCustomer() method of the SpecialCustomers base class. The new implementation checks whether the customer count is less than maxCount (5 in this case). If so, the Customer is added to the List else an exception is thrown.

Now, have a look at the following code that uses both of these classes.

SpecialCustomers sc = null;
sc = new TopNCustomers();
for (int i = 0; i < 10; i++)
{
    Customer obj = new Customer();
    sc.AddCustomer(obj);
}

The code declares a variable of type SpecialCustomers and then points it to an instance of TopNCustomers. This assignment is perfectly valid since TopNCustomers is derived from SpecialCustomers. The problem comes in the for loop. The for loop that follows attempts to add 10 Customer instances to the TopNCustomers. But TopNCustomers allows only 5 instances and hence throws an error. If sc would have been of type SpecialCustomers the for loop would have successfully added 10 instances into the List. However, since the code substitutes TopNCustomers instance in place of SpecialCustomers the code produces an exception. Thus LSP is violated in this example.

To rectify the problem we will rewrite the code like this:

public abstract class CustomerCollection
{
    public abstract void AddCustomer(Customer obj);
    public abstract int Count { get; }
}
 
public class SpecialCustomers:CustomerCollection
{
    List<Customer> list = new List<Customer>();
 
    public override void AddCustomer(Customer obj)
    {
        list.Add(obj);
    }
 
    public override int Count
    {
        get
        {
            return list.Count;
        }
    }
}
 
public class TopNCustomers : CustomerCollection
{
    private int count=0;
    Customer[] list = new Customer[5];
 
    public override void AddCustomer(Customer obj)
    {
        if(count<5)
        {
            list[count] = obj;
            count++;
        }
        else
        {
            throw new Exception("Only " + count + " customers can be added.");
        }
    }
 
    public override int Count
    {
        get
        {
            return list.Length;
        }
    }
}

Now, the code has CustomerCollection abstract class with one property (Count) and one method (AddCustomer). The SpecialCustomers and TopNCustomers classes inherit from this abstract class and provide the concrete implementation for the Count and AddCustomer(). Notice that in this case TopNCustomers doesn't inherit from SpecialCustomers.

The new set of classes can then be used as follows:

Customer c = new Customer() { CustomerID = "ALFKI" };
CustomerCollection collection = null;
collection = new SpecialCustomers();
collection.AddCustomer(c);
collection = new TopNCustomers();
collection.AddCustomer(c);

The above code declares a variable of CustomerCollection type. Once it points to an instance of SpecialCustomers and then to TopNCustomers. In this case, however, their base class is CustomerCollection and the instances are perfectly substitutable for it without producing any inaccuracies.

Tuesday, January 27, 2015

S.O.L.I.D Architecture principle in C# (Part 2)

Continue to Friday, January 23, 2015
-----------------------------------------------

O: Open/Closed Principle -

The Open/closed Principle says "A software module/class is open for extension and closed for modification".

Let's say you created a class that provides certain functionality. A few months later some need arises such that the class is supposed to provide some additional functionality. In such cases you shouldn't touch the source code of the class that is already built. Instead, you should be able to extend it so as to add the extra functionality.

Let's try to understand this with an example. Suppose that you are building a class that is responsible for calculating taxes on a given income. At the time of development you were told that this class will be used for tax calculation in three countries, say USA, UK and India. The following code shows a simplistic representation of such a class.


public class TaxCalculator
{
    public decimal CalculateTax(decimal amount,string country)
    {
        decimal taxAmount = 0;
        switch(country)
        {
            case "USA":
                //calculate tax as per USA rules
                break;
            case "UK":
                //calculate tax as per UK rules
                break;
            case "IN":
                //calculate tax as per India rules
                break;
        }
        return taxAmount;
    }
}

The TaxCalculator class has a method CalculateTax() that accepts the amount on which the tax is to be calculated and the country whose tax calculation rules are to be applied. Inside, a switch statement checks the country and accordingly the tax is calculated and returned to the caller.

Now, suppose that after a few months you also need to calculate tax in a few more countries. How will you take care of this additional functionality? You will change the CalculateTax() method and add additional cases inside the switch statement. That means any change in the functionality is forcing you to change the core class - TaxCalculator. This is violation of OCP.

Now, let's rewrite our code so that it follows OCP.

public abstract class TaxCalculatorBase
{
    public decimal TotalAmount { get; set; }
    public abstract decimal CalculateTax();
}
 
public class USATax:TaxCalculatorBase
{
    public override decimal CalculateTax()
    {
        //calculate tax as per USA rules
        return 0;
    }
}
 
public class UKTax : TaxCalculatorBase
{
    public override decimal CalculateTax()
    {
        //calculate tax as per UK rules
        return 0;
    }
}
 
public class IndiaTax : TaxCalculatorBase
{
    public override decimal CalculateTax()
    {
        //calculate tax as per India rules
        return 0;
    }
}

The above code creates an abstract class TaxCalculatorBase. This class defines a public property - TotalAmount - and an abstract method CalculateTax(). The CalculateTax() method doesn't have any code since it is an abstract method. The actual tax calculation happens in the derived classes - USATax, UKTax and IndiaTax. These classes provide the concrete implementation of the CalculateTax() method. Tomorrow if tax calculation is needed for a few more countries you need not modify any of the existing code. All you need to do is create another class that inherits from TaxCalculatorBase class and implement the required tax calculation logic inside its CalculateTax() method.

Friday, January 23, 2015

S.O.L.I.D Architecture principle in C#

What is SOLID?



SOLID are five basic principles whichhelp to create good software architecture. SOLID is an acronym where:-
  1. S stands for SRP (Single responsibility principle
  2. O stands for OCP (Open closed principle)
  3. L stands for LSP (Liskov substitution principle)
  4. I stands for ISP ( Interface segregation principle)
  5. D stands for DIP ( Dependency inversion principle)
Day 1:

"S" - Single Responsibility Principle.


The Single Responsibility Principle (SRP) states that:

A class should have only a single responsibility. Only one potential change in the software's specification should be able to affect the specification of the class.

This means that every class, or similar structure, in your code should have only one job to do. Everything in that class should be related to a single purpose. Our class should not be like a Swiss knife wherein if one of them needs to be changed then the entire tool needs to be altered. It does not mean that your classes should only contain one method or property. There may be many members as long as they relate to the single responsibility.

The Single Responsibility Principle gives us a good way of identifying classes at the design phase of an application and it makes you think of all the ways a class can change. A good separation of responsibilities is done only when the full picture of how the application should work. Let us check this with an example.

public class UserService  
{  
   public void Register(string email, string password)  
   {  
      if (!ValidateEmail(email))  
         throw new ValidationException("Email is not an email");  
         var user = new User(email, password);  
  
         SendEmail(new MailMessage("mysite@nowhere.com", email) { Subject="HEllo foo" });  
   }
   public virtual bool ValidateEmail(string email)  
   {  
     return email.Contains("@");  
   }  
   public bool SendEmail(MailMessage message)  
   {  
     _smtpClient.Send(message);  
   }  
}   

It looks fine, but it is not following SRP. The SendEmail and ValidateEmail methods have nothing to do within the UserService class. Let's refract it.

public class UserService  
{  
   EmailService _emailService;  
   DbContext _dbContext;  
   public UserService(EmailService aEmailService, DbContext aDbContext)  
   {  
      _emailService = aEmailService;  
      _dbContext = aDbContext;  
   }  
   public void Register(string email, string password)  
   {  
      if (!_emailService.ValidateEmail(email))  
         throw new ValidationException("Email is not an email");  
         var user = new User(email, password);  
         _dbContext.Save(user);  
         emailService.SendEmail(new MailMessage("myname@mydomain.com", email) {Subject="Hi. How are you!"});  
  
      }  
   }  
   public class EmailService  
   {  
      SmtpClient _smtpClient;  
   public EmailService(SmtpClient aSmtpClient)  
   {  
      _smtpClient = aSmtpClient;  
   }  
   public bool virtual ValidateEmail(string email)  
   {  
      return email.Contains("@");  
   }  
   public bool SendEmail(MailMessage message)  
   {  
      _smtpClient.Send(message);  
   }  
}   

Let's see remaining things on tomorrow's post.

Thursday, January 22, 2015

ObservableCollection in WPF

An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated. This happens because, when binding to an observable collection, WPF automatically adds a CollectionChanged event handler to the ObservableCollecion's events.

The ObservableCollection class exists in the System.Collections.ObjectModel namespace.

I will demonstrate how this works in a simple example:

I have a window with a Button, two TextBoxes and a ListView and each time you click the Button the text of the TextBox is added to the collection and the ListView is updated automatically.

UI

ObservableCollection-in-SQL-Server.jpg


Code File

public partial class MainWindow : Window
{
     private ObservableCollection<Person> person; 
     public MainWindow()
     {
         InitializeComponent();
         person = new ObservableCollection<Person>()
         {
             new Person(){Name="Prabhat",Address="India"},
             new Person(){Name="Smith",Address="US"}
         };
         lstNames.ItemsSource = person;
     }
     private void btnNames_Click(object sender, RoutedEventArgs e)
     {
         person.Add(new Person() { Name = txtName.Text, Address = txtAddress.Text });
         txtName.Text = string.Empty;
         txtAddress.Text = string.Empty;
     }
}
public class Person
{
     public string Name { get; set; }
     public string Address { get; set; }
Here a Person class has the 2 properties Name and Address.  One observableCollection object is created with a Person type and bound to the ListView. See:

lstNames.ItemsSource = person;
By doing so, we can dynamically insert, update and remove items from the ListView, as in:

person.Add(new Person() { Name = txtName.Text, Address = txtAddress.Text });

XAML File

<Grid>
         <Grid.ColumnDefinitions>
             <ColumnDefinition/>
             <ColumnDefinition Width="*"/>
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="*"></RowDefinition>
         </Grid.RowDefinitions>
         <StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5,5,5">
             <TextBlock x:Name="lblName" Text="Name"></TextBlock>
             <TextBox x:Name="txtName"></TextBox>
             <TextBlock x:Name="lblAddress" Text="Address"></TextBlock>
             <TextBox x:Name="txtAddress"></TextBox>
             <Button Grid.Column="0" Width="100" Height="20" Margin="5,5,5,5" x:Name="btnNames" Click="btnNames_Click" Content="Add"></Button>
         </StackPanel>
         <ListView x:Name="lstNames" Margin="5,5,5,5" Grid.Column="1" Grid.Row="0">
             <ListView.View>
                 <GridView x:Name="grdNames">
                     <GridViewColumn Header="Name"  DisplayMemberBinding="{Binding Name}"/>
                     <GridViewColumn Header="Address"  DisplayMemberBinding="{Binding Address}"/>
                 </GridView>
             </ListView.View>
         </ListView>
 </Grid>
The ObservableCollection is already bound to the Listview. So all we need to do in the XAML file is to specify the binding member for each column. We can do that by the "DisplayMemberBinding" attribute and "Binding" markup extension. See:

<GridViewColumn Header="Name"  DisplayMemberBinding="{Binding Name}"/>

Tuesday, January 20, 2015

Ways of Assigning value for Drop down list using jquery

You know, sometimes small things will take long time to implement. Usually this will happen if we are not familiar with them. For this, plenty of documentation is available around, we should read it before starting it. So, here I am talking about JQuery and the features of it. I know how to select a value in a drop down and populate it using plain javascript. But when comes to JQuery, for me it took sometime to find a way to do that. Below is the way on how to populate a dropdown value as selected.

$("#ddlSource option[value='1']").attr("selected", "selected");

Here, ddlSource is the ID of the HTML select [drop down list] control. The meaning of the above statement is, find the control which has the ID "ddlSource" and in it find the option which has give value and select it. "1", I am using for example. You can pass any value.
If you are using the server side controls, and want to populate the value in JQuery, then use below statement.

$("#<%=ddlSource.ClientID %> option[value='1']").attr("selected", "selected");

But this is not the right way of doing it. You can change the server side drop down values on client side, but which results you the error message "Invalid Postback or Callback event" when submitting data to server. So, take care when you deal with server side controls in javascript.

For best practice Please try to use 

<select runat="server" ID="ddlSource"></select> instead of <asp:DropDownList /> 

to avoid the invalid callback error messages. I know, the immediate question in your mind, how to get the value using <select> control in C# code. Use below code for it.

string selectedValue = Request.Form[ddlSource.UniqueID]; //UniqueID is because Form is expecting name instead of ID..

Monday, January 19, 2015

Dependency Injection in .Net

Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class.

For example, Suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.


We can modify this code by the DI different ways. We have following different ways to implement DI :

Constructor Injection


  1. This is the most common DI.
  2. Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor when instantiating that class.
  3. Injected component can be used anywhere within the class.
  4. Should be used when the injected dependency is required for the class to function.
  5. It addresses the most common scenario where a class requires one or more dependencies.

    public interface IService
    {
        void Serve();
    }
 
    public class Service : IService
   {
        public void Serve()
       {
          Console.WriteLine("Service Called");
           //To Do: Some Stuff
       }
   }
 
   public class Client
   {
    private IService _service;
 
    public Client(IService service)
    {
       this._service = service;
     }
 
     public void Start()
    {
      Console.WriteLine("Service Started");
       this._service.Serve();
       //To Do: Some Stuff
     }
   }

   class Program
   {
     static void Main(string[] args)
     {
       Client client = new Client(new Service());
       client.Start(); 
       Console.ReadKey();
     }
  }

The Injection happens in the constructor, by passing the Service that implements the IService-Interface. The dependencies are assembled by a "Builder" and Builder responsibilities are as follows:
  • knowing the types of each IService.
  • according to the request, feed the abstract IService to the Client.

Property injection

  1. Also called Setter injection.
  2. Used when a class has optional dependencies, or where the implementations may need to be swapped. Different logger implementations could be used this way.
  3. May require checking for a provided implementation throughout the class(need to check for null before using it).
  4. Does not require adding or modifying constructors.   

  public interface IService.
  {
    void Serve();
  }
 
  public class Service : IService
 {
    public void Serve()
   {
     Console.WriteLine("Service Called");
    //To Do: Some Stuff
    }
  }
 
  public class Client
  {
     private IService _service;
 
     public IService Service
    {
      set
    {
      this._service = value;
    }
    }
 
   public void Start()
   {
      Console.WriteLine("Service Started");
      this._service.Serve();
      //To Do: Some Stuff
    }
  }

 class Program
 { 
 static void Main(string[] args)
 {
 Client client = new Client();
 client.Service = new Service();
 client.Start();
 
 Console.ReadKey();
  }
 }

Method injection

  1. Inject the dependency into a single method, for use by that method.
  2. Could be useful where the whole class does not need the dependency, just the one method.
  3. Generally uncommon, usually used for edge cases.
    public interface IService
   {
     void Serve();
    }
 
    public class Service : IService
    {
       public void Serve()
      {
        Console.WriteLine("Service Called");
        //To Do: Some Stuff
      }
    }
 
    public class Client
   {
      private IService _service;
 
      public void Start(IService service)
     {
        this._service = service;
        Console.WriteLine("Service Started");
       this._service.Serve();
      //To Do: Some Stuff
     }
   }
  class Program
  {
     static void Main(string[] args)
     {
     Client client = new Client();
     client.Start(new Service());
 
     Console.ReadKey();
    }
  }

Key points about DI

  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing