Thursday, February 27, 2014

MVC : Various Ways of Passing Data in ASP.NET MVC Application

In this article i will talk about how we can transfer the data from Controller to View or passing data between actions of a controller.

Model

The best and recommended way to pass the data from a Controller to View is by using Model classes. If we create a strongly typed view than that view is capable of accessing the object/model that is being passed to it from the controller.

ViewModel

Now consider a scenario where we need to create a view which needs data from two or more classes/models. How can we create a strongly type view that can extract data from two models. The answer to this is that we cannot. But we can create a new class that can contain these classes' objects in it and this class can be passed as the model class to the view. Now this class is created to be used as model on some views. All such classes are called as ViewModels.

ViewData and ViewBag

To transfer small amount of data, we can use Viewdata andViewBag.

ViewBag comes with all the benefits of ViewData with an additional benefit that type casting is not required.

TempData

Now the problem with all the above ways of data transfer was that the data is only alive for current request. The data is lost if a redirection takes place i.e. one Action redirects to another action. For the scenarios where we need to persist the data between actions/redirection another dictionary object calledTempData can be used. It is derived from TempDataDictionary. It is created on top of session. Its will live till the redirected view is fully loaded.

Sessions

Session is the way to persist the data till the current session is alive. If we need some data to be accessible from multiple controllers, actions and views then Session is the way to store and retrieve the data.

Model

Let us first see how we can create a strongly typed view which will display the data that is being passed to it from the controller. Lets have a simple Model like:
public class Book
{
public int ID { get; set; }
public string BookName { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
}
Now let us create a simple Action called SampleBook and create a book object in it and then pass it on to the view.
public ActionResult SampleBook()
{
Book book = new Book
{
ID = 1,
BookName = "Sample Book",
Author = "Sample Author",
ISBN = "Not available"
};

return View(book);
}
Now lets add a strongly typed View for this action which will use Book model to retrieve the data. Lets also use the "Details" scaffold so that we don't have to write the code to access the data from the model(just for the demonstration purpose).
Now if we look at the code for the View we can see that the data is being extracted from the Model which is an object of Book type passed from the controller.
When we run the application:

ViewModel

Now let us say we need a View that should display the data from multiple models. Lets say we have one more class which is getting some custom message and it should be displayed on the page whenever aBook data is being displayed. Now this message data is contained in a separate model as:
public class Message
{
public string MessageText { get; set; }
public string MessageFrom { get; set; }
}
Now we need to pass two objects to the View one Book object and another Message object. Now to do this we need to create a new class i.e. the ViewModel class which will contain these two object in it.
public class ShowBookAndMessageViewModel
{
public Book Book { get; set; }
public Message Message {get;set;}
}
Now let is create one more action in our controller. This action will create this ViewModel object and pass it to the view.
public ActionResult SampleBook2()
{
Book book = new Book
{
ID = 1,
BookName = "Sample Book",
Author = "Sample Author",
ISBN = "Not available"
};

Message msg = new Message
{
MessageText = "This is a Sample Message",
MessageFrom = "Test user"
};

ShowBookAndMessageViewModel viewModel = new ShowBookAndMessageViewModel
{
Message = msg,
Book = book
};

return View(viewModel);
}
Now let us create a strongly typed view that will use this ViewModel class to extract the data.
And now let us see the code that we need to extract the data from this ViewModel and show it on the View.
And when we run the application we can see that data can be extracted from this ViewModel class and then corresponding data from Book and Message class and be extracted and shown on the View.
 

ViewData

We have discussed that the ViewData can be used to pass simple and small data from controller to the view Let is see how we can pass a simple message string from Controller to View using ViewData.
public ActionResult Index()
{
ViewData["Message"] = "This Message is coming from ViewData";

return View();
}
And now this data can be extracted from the view as:
And when we run the application:
Note: We are not type casting the data in view because it is simple string. If this data would have been of some complex type, type casting would become inevitable.

ViewBag

Now let us try to implement the same functionality like above but by using ViewBag instead of ViewData.
public ActionResult Index2()
{
ViewBag.Message = "This Message is coming from ViewBag";

return View();
}
And now this data can be extracted from the view as:
And when we run the application:

TempData

Now let us say we have an action method redirect to another action method and we need to pass some data from one action method to another action method. To do this you we will have to use TempData.
public ActionResult SampleBook3()
{
Book book = new Book
{
ID = 1,
BookName = "Sample Book",
Author = "Sample Author",
ISBN = "Not available"
};

TempData["BookData"] = book;
return RedirectToAction("SampleBook4");
}

public ActionResult SampleBook4()
{
Book book = TempData["BookData"] as Book;

return View(book);
}
Now when the SampleBook3 action will be called it will create a Book type, put it in a TempData variable and then redirect to action SampleBook4. Now in SampleBook4, the data will be extracted from theTempData and then the View for the SampleBook4 will be shown which is a strongly typed view and is capable of showing the data from the Book model.

Session

Use of sessions has nothing new for the the web developers. We can use session variables to persist the data for a complete session. To demonstrate this let us implement the above functionality using sessions instead of TempData.
public ActionResult SampleBook5()
{
Book book = new Book
{
ID = 1,
BookName = "Sample Book",
Author = "Sample Author",
ISBN = "Not available"
};

Session["BookData"] = book;
return RedirectToAction("SampleBook6");
}

public ActionResult SampleBook6()
{
Book book = Session["BookData"] as Book;

return View(book);
}
Now when the SampleBook5 action will be called it will create a Book type, put it in a session variable and then redirect to action SampleBook6. Now in SampleBook6, the data will be extracted from the Session and then the View for the SampleBook6 will be shown which is a strongly typed view and is capable of showing the data from the Book model.
Note: The sample application contains complete application demonstrating all the techniques. Please refer to the sample application for better understanding.

Point of interest

In this article we saw various ways of passing the data between controllers and view and between action in a controller.

FACADE DESIGN PATTERN

According to GoF’s definition, facade pattern is :
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
real world example :
In this example we need to start computer. Computer class acts as facade which encapsulates other complex classes represented by: HardDrive class, Memory class and CPU class. Each of this classes has operations which must be performed when Start() method of Computer class is called.
public class Computer
{
private readonly CPU _cpu;
private readonly HardDrive _hardDrive;
private readonly Memory _memory;

private const long BootAddress = 1;
private const long BootSector = 1;
private const int SectorSize = 10;

public Computer()
{
_cpu = new CPU();
_hardDrive = new HardDrive();
_memory = new Memory();
}

public void Start()
{
_cpu.Freeze();
_memory.Load(BootAddress, _hardDrive.Read(BootSector, SectorSize));
_cpu.Jump(BootAddress);
_cpu.Execute();
}
}

public class CPU
{
public void Freeze()
{
Console.WriteLine("CPU is frozen");
}

public void Jump(long position)
{
Console.WriteLine("Jumping to position: {0}", position);
}

public void Execute()
{
Console.WriteLine("Executing...");
}
}

public class HardDrive
{

public byte[] Read(long lba, int size)
{
var bytes = new byte[size];
var random = new Random();
random.NextBytes(bytes);
return bytes;
}
}

public class Memory
{
public void Load(long position, byte[] data)
{
Console.WriteLine("Loading data: ");
foreach (var b in data)
{
Console.Write(b+ " ");
Thread.Sleep(1000);
}

Console.WriteLine("\nLoading compleded");
}
}

class Program
{
static void Main()
{
var computer = new Computer();
computer.Start();
}
}
Real Example Using Car  -


class CarModel
{
public void SetModel()
{
Console.WriteLine(" CarModel - SetModel");
}
}
class CarEngine
{
public void SetEngine()
{
Console.WriteLine(" CarEngine - SetEngine");
}
}
class CarBody
{
public void SetBody()
{
Console.WriteLine(" CarBody - SetBody");
}
}
class CarAccessories
{
public void SetAccessories()
{
Console.WriteLine(" CarAccessories - SetAccessories");
}
}
public class CarFacade
{
CarModel model;
CarEngine engine;
CarBody body;
CarAccessories accessories;

public CarFacade()
{
model = new CarModel();
engine = new CarEngine();
body = new CarBody();
accessories = new CarAccessories();
}

public void CreateCompleteCar()
{
Console.WriteLine("******** Creating a Car **********\n");
model.SetModel();
engine.SetEngine();
body.SetBody();
accessories.SetAccessories();

Console.WriteLine("\n******** Car creation complete **********");
}
}
class Program
{
static void Main(string[] args)
{
CarFacade facade = new CarFacade();
facade.CreateCompleteCar();
Console.ReadKey();
}
}



Wednesday, February 26, 2014

Important URL

Video Tutorial

http://tech.priyo.com/tutorial/2014/11/26/27096.html
Java Script
জাভাস্ক্রিপ্ট 
http://tech.priyo.com/tutorial/2014/11/16/26878.html
C#
http://tech.priyo.com/tutorial/2014/11/18/26904.html











Upload multiple files in asp.net

http://www.codeproject.com/Articles/667604/Upload-multiple-files-in-asp-net-2


Angularjs(code)
http://code.angularjs.org/


SOLID

http://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp

JavaScript
http://ejohn.org/apps/learn/#2

Session Time Out Warning

http://www.codeproject.com/Articles/711196/Session-Time-Out-Warning-Message-Using-jQuery-in-A


Entity Framework, Inversion of Control, Unity Framework, Repository & Unit of Work Pattern and MVC

http://www.codeproject.com/Articles/547016/Code-First-Approach-using-Entity-Framework-Inv

















Monday, February 17, 2014

Design Patterns

The GoF Design Patterns are divided into 3 categories :(B.C.S.) Creational Patterns, Structural Patterns and Behavioral Patterns. I am going to explain each GoF Design Pattern in detail and will show you examples of how to write good C#  code that implement those patterns.
http://www.dotnettricks.com/learn/designpatterns

Creational Patterns

The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First President of States

Structural Patterns

To remember structural pattern best is (ABCDFFP)
  • Adapter Pattern: Match interfaces of classes with different interfaces
  • Bridge Pattern:: Separate implementation and object interfaces
  • Composite: Simple and composite objects tree
  • Decorator: Dynamically add responsibilities to objects
  • Facade: Class that represents subclasses and subsystems
  • Flyweight: Minimize memory usage by sharing as much data as possible with similar objects
  • Proxy: Object that represents another object

Behavioral Patterns

Note :- Just remember Music……. 2 MICS On TV (MMIICCSSOTV).
  • Mediator: Encapsulates and simplifies communication between objects
  • Memento: Undo modifications and restore an object to its initial state
  • Interpreter: Include language elements and evaluate sentences in a given language
  • Iterator: Give sequential access to elements in a collection
  • Chain of Responsibility: Pass requests between command and processing objects within a chain of objects
  • Command: Encapsulate a method call as an object containing all necessary information
  • State: Change object behavior depending on its state
  • Strategy: Encapsulate algorithms within a class and make them interchangeable
  • Observer: Notify dependent objects of state changes
  • Template Method: Define an algorithm skeleton and delegate algorithm steps to subclasses so that they may be overridden
  • Visitor: Add new operations to classes without modifying them
http://www.tutorialspoint.com/design_pattern/design_pattern_quick_guide.htm

Creational Patterns

Singleton PatternEnsure a class has only one instance, and provide a global point of access to it.

Ex:
public class Singleton
{
 private static Singleton _instance;
 private Singleton()
 {
  ...
 }

 public static Singleton GetInstance()
 {
  if (_instance== null)
   _instance= new Singleton();

  return _instance;
 }
 ...
 public void doSomething()
 {
  ... 
 }
}




2

3
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. 

Problem

For example we have a scenario where based on user input we need to call particular class methods. I have a customer input screen. He enters his choice whether they want to buy a bike or a car. 
Ex:
/
// Interface//
public interface IChoice
{
    string Buy();
}

//
// Factory Class//
public class FactoryChoice
{
    static public IChoice getChoiceObj(string cChoice)
     {
        IChoice objChoice=null;
        if (cChoice.ToLower() == "car")
        {
            objChoice = new clsCar();
        }
        else if (cChoice.ToLower() == "bike")
        {
            objChoice = new clsBike();
        }
        else
        {
            objChoice = new InvalidChoice();
        }
        return objChoice;
    }
}
 
//Business classes//Carpublic class clsBike:IChoice
{
    #region IChoice Members
 
    public string Buy()
    {
        return ("You choose Bike");
    }
 
    #endregion
}
 
//Bikepublic class clsCar:IChoice
{
 
    #region IChoice Members
 
    public string Buy()
    {
        return ("You choose Car");
    }
 
    #endregion
}
From the client class call the factory class object and it will return the interface object. Through the interface object we will call the respective method.
//Client classIChoice objInvoice;
objInvoice = FactoryClass.FactoryChoice.getChoiceObj(txtChoice.Text.Trim());
MessageBox.Show(objInvoice.Buy());
In future if we need to add a new vehicle then there is no need to change the client class, simply return that object using the factory class.

Advantages

Suppose we want to add a decoupled structure and don’t want to disturb the client environment again and again, this pattern is very useful. The factory class will take all the burden of object creations.
 

Proxy Design Pattern

Definition

Provide a surrogate or placeholder for another object to control access to it. 

   public interface Subject
    {
       void PerformAction();
    }    
    public class RealSubject : Subject
    {
    public void PerformAction()
    {
        Console.WriteLine("RealSubject action performed.");
    }
    }    
    public class Proxy : Subject
    {
    private RealSubject _realSubject;    
    public void PerformAction()
    {
    if (_realSubject == null)
    _realSubject = new RealSubject();    
    _realSubject.PerformAction();
    }
    }

Decorator Pattern


Decorator pattern is used to add new functionality to an existing object without changing its structure.

class DecoratorPattern
    {
        private interface IPizza
        {
            int GetPrice();
        }
 
        private class Pizza : IPizza
        {
            public int GetPrice()
            {
                return 10;
            }
        }
 
        //Decorator 1
        private class PizzaWithCheese : IPizza
        {
            private IPizza _pizza;
            private int _priceofCheese;
 
            public PizzaWithCheese(IPizza pizza, int priceofCheese)
            {
                _pizza = pizza;
                _priceofCheese = priceofCheese;
            }
 
            public int GetPrice()
            {
                //get price of the base pizza and add price of cheese to it
                return _pizza.GetPrice() + _priceofCheese;
            }
        }
 
        //Decorator 2
        private class PizzaWithChicken : IPizza
        {
            private IPizza _pizza;
            private int _priceofChicken;
 
            public PizzaWithChicken(IPizza pizza, int priceofChicken)
            {
                _pizza = pizza;
                _priceofChicken = priceofChicken;
            }
 
            public int GetPrice()
            {
                //get price of the base pizza and add price of chicken to it
                return _pizza.GetPrice() + _priceofChicken;
            }
        }
 
 
        public static void Test()
        {           
            var pizzaWithCheese = new PizzaWithCheese(new Pizza(), 5);
            var pizzaWithChicken = new PizzaWithChicken(new Pizza(), 6);
 
            //pizza with chicken and cheese is easy to build now.
            //we can keep decotaring the base pizza with as many decorators as necessary at runtime
            var pizzaWithChickenAndCheese = new PizzaWithChicken(pizzaWithCheese, 6);
 
            Console.WriteLine("Total for cheese pizza: " + pizzaWithCheese.GetPrice());
            Console.WriteLine("Total for chicken pizza: " + pizzaWithChicken.GetPrice());
            Console.WriteLine("Total for cheese + chicken pizza: " + pizzaWithChickenAndCheese.GetPrice());
        }
    }

Factory Method:

http://dotnetfreakblog.wordpress.com/2013/03/02/factory-design-pattern-in-c/


http://www.newguid.net/vs2008-vs2010/2010/design-patternsc-basic-example-strategy-pattern/
http://dotnetfreakblog.wordpress.com/2013/11/10/strategy-design-pattern-using-c/
http://www.blackwasp.co.uk/Strategy.aspx

Adapter Pattern

http://www.c-sharpcorner.com/UploadFile/40e97e/adapter-pattern-in-C-Sharp/
https://csharpdesignpatterns.codeplex.com/wikipage?title=Adapter%20Pattern&referringTitle=Home
Interviewquestion
http://interviewquestion.wordpress.com/design-patterns/
http://computerauthor.blogspot.in/2011/03/design-pattern-interview-questions.html
http://dotnetinterviews.com/Design-Patterns-Questions-Answers.aspx

Template Method
http://www.codeproject.com/Articles/482196/Understanding-and-Implementing-Template-Method-Des
http://sourcemaking.com/design_patterns/template_method/c-sharp-dot-net
Pattern in Bangla 
http://hasin.me/2014/05/14/singleton-design-pattern/