Translate

Sunday, July 22, 2012

Introduction to asp.net MVC (theoretical)

What is MVC?

MVC (Model View Controller) is a design pattern that was introduced in 1979. At that time it was called Thing Model View Editor. This pattern separates out the concerns within an application to three parts called Model, View and Controller.

In an MVC application, this is what the Model, View and Controller is meant for

Model: This holds the business logic.

View: This layer holds the markup (layout of the display). It receives data from the controller. It uses that data to generate the HTML response.

Controller: This is the code that interacts with the user. When a request comes in to an application, it first goes to the controller. The controller is the one who decides which model to use and which View to return to the user. It controls everything, hence the name controller.

What is asp.net MVC?

 If you are coming from the java world, you might have used struts web framework for MVC development. Microsoft provided its own framework in a downloadable installation package to facilitate the use of MVC pattern. The installation package includes templates and tools for Visual Studio 2010, it also includes the assembly System.Web.Mvc.dll. The System.Web.Mvc dll contains classes and interfaces that support the ASP.NET Model View Controller (MVC) framework. The use of asp.net mvc makes building asp.net web applications using MVC pattern a lot more easier.

Comparison of asp.net MVC to Webforms.

By the separation of concerns (into model view and editor) as shown above, MVC makes large applications easier to maintain. This is the biggest reason for the use of MVC. Test driven development is easier in MVC. Many developers also like the fact that they have a much more granular level of control (which makes development a little bit more complicated) over the application. As far as performance is concerned, besides the fact that the HTML rendered wouldn't include a viewstate in MVC, there is not much performance gain by moving from webforms to MVC.


Wednesday, July 18, 2012

Where should business logic reside in a website?

In my experience, there have been more advantages than drawbacks of having business logic in the web/wcf application instead of having it inside stored procedures.

Advantages of having business logic in the application:
1> Compared to SQL server, it is easier to scale a web application (through use of load balancers for example).
2>Debugging with break points is a lot easier in a web application.
3>If you have multiple database servers, then web application can be a common location for all business logic.
4>Application code is a lot easier to integrate with source control.
5>You can apply sophisticated design patterns on your business code, thus leading to a more maintainable and scalable business code.

Advantages of business logic in a stored procedure:
1> If the data manipulation is done in the database and only the final result set is passed to the application, network load can be greatly reduced. This is particularly true if you have to sift through Giga Bytes of data (reporting applications for instance) before presenting the end result to the user.
2>Performance tuning is easier.

Monday, July 16, 2012

c# Interface tutorial


Most of the interfaces you come across are a collection of method and property signatures. It can also have signatures of events or indexers.

Example of an Interface


using System;

namespace ConsoleApplication
{
    public interface IPrinter
    {
        void Print();

    }
}

Any one who implements an interface must provide definitions to what ever is in the interface. For example, any class that implements the IPrinter interface must implement a Print Method. For example


using System;

namespace ConsoleApplication
{

    class Program
    {
        static void Main(string[] args)
        {
            DilbertsPrinter prn = new DilbertsPrinter();
            prn.Print();            
        }

    }

    public class DilbertsPrinter:IPrinter
    {
        public void Print()
        {
            Console.WriteLine("My Printer");
        }
    }
}



You cannot instantiate an interface, but you can set a variable of an Interface type to a class that implements that interface. For example I can do this,


IPrinter printer1 = new DilbertsPrinter();
printer1.Print();

The  printer1.Print() will call the print method on the class DilbertsPrinter. Through the interface variable  printer1, if you try calling a method on the class  DilbertsPrinter, which is not a part of the interface IPrinter, it will throw a compile time error.

This is a very important property, which is extensively used when applying the programming to an interface design principle.


 A few points to note about an interface:

  • An interface can only have signatures of methods, properties, events and indexers. Trying to add fields or anything else will throw compile time errors.
  • A class can implement more than one interface.
  • An interface itself can inherit from multiple interfaces.
  • You cannot add access modifiers (public, private etc) to the members of an interface. All the  members of an interface are by default public. 
  • The interface itself (not its members) can have all the modifiers (private,public etc) if it is defined inside a class. If it is defined in a namespace, it can only be public. (Most interfaces are defined inside a namespace and not a class.)

Further reading:
http://msdn.microsoft.com/en-us/library/ms173156(v=vs.110).aspx

Sunday, July 8, 2012

IsNumeric C#

There is no inbuilt IsNumeric function in C#. The function below does the same as the isNumeric function does in VB



public static bool IsNumeric(string s)
{
            
    decimal result;

    decimal.TryParse(s, out result);

    if (result!=0)
    {
        return true;
    }
    else
    {
        decimal.TryParse((s + 1), out result);
        if (result != 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

c# difference between null and dbnull

In my experience DBNull can be interpreted as database null. If the database returns a null, you need to check it against DBNull.value to catch it.

Cases where you would check for null

In the code

int? i=null;

if (System.DBNull.Value.Equals(i))
{
    Console.WriteLine("DBNull");
}
else if (i == null)
{
    Console.WriteLine("null");//code enters here
}

null is what gets printed out.

In the code below, we try to access a non existent field

DataSet ds = new DataSet();

if (System.DBNull.Value.Equals(ds.Tables[""]))
{
    Console.WriteLine("DBNull");
}
else if (ds.Tables[""]== null)
{
    Console.WriteLine("null");//code enters here
}

          
 again null is printed out.

Cases where you would check for DBNull.value 

Here dr is an instance of the SqldataReader class. Assume that the database returns null as the value for the column "xxx"

while (dr.Read())
{
    if (dr["xxx"]==null)
    {
        Console.WriteLine("NULL");
    }
    else if (System.DBNull.Value.Equals(dr["xxx"]))
    {
        Console.WriteLine("DBNull");//code enters here
    }

}

DBNull is what gets printed out



However note that neither checking null of nor DBNull.value will work if the index is out of range. If we check for an index or a column that doesn't exist, it will throw an index out of range exception.



Saturday, July 7, 2012

C# check if DateTime variable is null



using System;
using System.Text;

namespace ConsoleApplication
{

    class Program
    {
        static void Main(string[] args)
        {

            DateTime dt1 = new DateTime();
            DateTime? dt2=null ;

            isDateTimeNull(dt1);
            isDateTimeNull(dt2);

        }

        static void isDateTimeNull(DateTime? dt)
        {
            if(dt.GetHashCode()==0)
            {
                Console.WriteLine("DateTime is unassigned");
            }
        }
    }
}


Output:










In stackoverflow.com I found another way for checking null datetime


 DateTime datetime = new DateTime();
 if (datetime == DateTime.MinValue)
 {
    //unassigned
 }




Sunday, July 1, 2012

Observer Pattern Tutorial (Introduction to Observer Pattern in C#)


An observer pattern (also called a publisher subscriber pattern) consists of a subject and many observers. The subject notifies the observer in case of a change in state. The image below shows a real life scenario that imitates the observer pattern. Here the recruiter of a company is the subject and the job hunters are the observers.






































In .net, events are an implementation of the observer pattern. 

An example implementing Observer Pattern

 Suppose you want to write an application where any time a particular SQL server goes down, you want certain groups to be notified. The diagram below shows at a high level what we are trying to achieve.



The Subject (the notification service) should be able to

  • Add an observer
  • Remove an Observer
  • Notify an Observer


The Observers (John and Steve's teams) should be able to take the appropriate action when notified.


 Before we proceed let me mention here, it is assumed that the reader is aware of the programming to an interface design principle.

The class diagram to achieve this is shown below.

































This same problem can be solved using the .net standard event pattern



Shown below is the complete code.

using System;
using System.Collections.Generic;
using System.Threading;

public interface INotificationObserver
{
    void OnServerDown();
}

public interface INotificationService
{
    void AddSubScriber(INotificationObserver obs);
    void RemoveSubScriber(INotificationObserver obs);
    void NotifyObserver();
}

internal class Playground
{
    //This is the entry point for the application
    private static void Main(string[] args)
    {
        var ns = new NotificationService();

        var Jo = new JohnsObserver(ns);
        var So = new StevesObserver(ns);

        while (true)
        {
            if (PingSqlServer() == false)
            {
                //When SQL server is down notify observer
                Console.WriteLine("Server down!");
                ns.NotifyObserver();
            }
            else
            {
                Console.WriteLine("All is good");
            }
            Thread.Sleep(1000);
        }
    }

    private static bool PingSqlServer()
    {
        //All this method does is randomly return a false
        var random = new Random();

        int i = random.Next(1, 30);
        if (i > 20)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

public class NotificationService : INotificationService
{
    private readonly List<INotificationObserver> _observers;

    public NotificationService()
    {
        _observers = new List<INotificationObserver>();
    }

    public void AddSubScriber(INotificationObserver obs)
    {
        _observers.Add(obs);
    }

    public void RemoveSubScriber(INotificationObserver obs)
    {
        _observers.Remove(obs);
    }

    public void NotifyObserver()
    {
        foreach (INotificationObserver Obs in _observers)
        {
            Obs.OnServerDown();
        }
    }
}


public class JohnsObserver : INotificationObserver
{
    private readonly INotificationService _localRefToNotiServ;

    public JohnsObserver(INotificationService notiServ)
    {
        _localRefToNotiServ = notiServ;
        _localRefToNotiServ.AddSubScriber(this);
    }

    public void OnServerDown()
    {
        //Send email to John
        Console.WriteLine("An email was sent to John");
    }

    public void Unlist()
    {
        _localRefToNotiServ.RemoveSubScriber(this);
    }
}


public class StevesObserver : INotificationObserver
{
    private readonly INotificationService _localRefToNotiServ;

    public StevesObserver(INotificationService notiServ)
    {
        _localRefToNotiServ = notiServ;
        _localRefToNotiServ.AddSubScriber(this);
    }

    public void OnServerDown()
    {
        //Send text message to Steve
        Console.WriteLine("A text was sent to Steve");
    }

    public void Unlist()
    {
        _localRefToNotiServ.RemoveSubScriber(this);
    }
}

  

What is shown above is a push mechanism where in the Subject pushes the update to the Observer. Observer Pattern can also be implemented with a pull mechanism where in the the Observer initiates the Notify mechanism from the Subject.

Further Reading

IObserver<T> Interface
IObservable<T> Interface