3 August 2013

ViewBag, ViewData, TempData and View State in MVC

ViewBag, ViewData, TempData and View State in MVC

ASP.NET MVC offers us three options ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. 


Similarities between ViewBag & ViewData :
  1. Helps to maintain data when you move from controller to view.
  2. Used to pass data from controller to corresponding view.
  3. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
  1. ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  3. ViewData requires typecasting for complex data type and check for null values to avoid error.
  4. ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:


public ActionResult Index()

{

    ViewBag.Name = "Arun Prakash";
    return View();
}

public ActionResult Index()
{
    ViewData["Name"] = "Arun Prakash";
    return View();

View
@ViewBag.Name 
@ViewData["Name"]

TempData:
Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only

The only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view.

It requires typecasting for complex data type and check for null values to avoid error.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}
public ActionResult About()
{
    var model= TempData["ModelName"];
    return View(model);
}

View State in MVC
ASP.NET MVC does not have ViewState (that of storing the values of controls in the web page).
So ASP.NET MVC pages are incredibly lightweight and your request and response times are much faster.

Alternative to View State in MVC
1. For retaining the values during postback in the MVC page values you can use Ajax, so that values in the     control won't clear.
2. For temporarily storing the value in current and the subsequent requests use TempData.








Handle Null Values in Linq Query (C#)

Handle Null Values in Linq Query (C#)

 Avoid a null reference exception as shown in the following example:

var query1 =
    from c in categories
    where c != null 
    join p in products on c.ID equals
        (p == null ? null : p.CategoryID)
    select new { Category = c.Name, Name = p.Name };
The where clause filters out all null elements in the categories sequence. This technique is independent of the null check in the join clause. The conditional expression with null in this example works because Products.CategoryID is of type int? which is shorthand for Nullable
In a join clause, if only one of the comparison keys is a nullable value type, you can cast the other to a nullable type in the query expression. In the following example, assume that EmployeeID is a column that contains values of type int?:
void TestMethod(Northwind db)
{
    var query =
        from o in db.Orders
        join e in db.Employees
            on o.EmployeeID equals (int?)e.EmployeeID
        select new { o.OrderID, e.FirstName };
}

Use of ternary operator as in the below example and the MobileNo = "N/A" for the null values:
Solution 1
var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
UserId = m.UserId,
MobileNo = (m.MobileNo == null) ? "N/A" : m.MobileNo
};
Solution 2
var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
UserId = m.UserId,
MobileNo = m.MobileNo ?? "N/A" 
};


Reference: http://msdn.microsoft.com/en-us/library/bb882535.aspx




31 July 2013

Covariance .Net Framework 4.0

Covariance .Net Framework 4.0

Covariance preserve assignment compatibility between Parent and Child relationship during dynamic polymorphism

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Covariance
{

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

            List objAthelete = new List();
            objAthelete.Add(new Athelete
            {
                SportName = "100 meter",
                SportsType = "Running"
            });

            IEnumerable Persons = objAthelete;

            Athelete objAth = new Athelete();
            //objAth.PrintAll(Persons);
        }
    }


    public class Person
    {
        public string Name { get; set; }
        public string City { get; set; }
    }

    public class Athelete : Person
    {

        public string SportName { get;set; }
        public string SportsType { get;set; }

        public void PrintAll(IEnumerable objects)
        {
            foreach (Athelete o in objects)
            {
                Console.WriteLine("Sports Name:" + o.SportName + "Sports Type:" + o.SportsType);
            }
        }
    }
}

The following error is thrown when the application is run in .Net framework 3.5, but it support in 4.0 framework.





27 July 2013

Add multiple model in View MVC 3 and MVC 4

Add multiple model in View MVC 3 and MVC 4

Using Tuple it is possible, Add below code in the view.

@model Tuple< Model1,Model2 >

Example : http://pastebin.com/VBPhBBUw


29 June 2013

Set Property Value on Master Page from Content Page ASP.NET

Set Property Value on Master Page from Content Page


Create a property in your master page and you access it from content page:
Master page:
public partial class BasePage : System.Web.UI.MasterPage
{
    private string[] _RequiredRoles = null;

    public string[] RequiredRoles
    {
        get { return _RequiredRoles; }
        set { _RequiredRoles = value; }
    }
}
Content Page:
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load()
    {
        Master.RequiredRoles = new string[] { //set appropriate roles };
    }
}

10 June 2013

ASP.NET Page Life Cycle

ASP.NET Page Life Cycle

Page request - The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start - In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. 

InitializationDuring page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

LoadDuring load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling - If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Render the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

UnloadThe Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.


1 June 2013

LINQ To SQL Vs Entity Framework

LINQ To SQL Vs Entity Framework

LINQ To SQL
LINQ To SQL supports rapid development of applications that query only SQL Server and SQL Server Compact 3.5 databases, providing a 1:1 mapping of your existing Database schema to classes. It does not provide the flexibility to use objects that do not exactly match the tables.

Entity Framework
Entity Framework on the other hand, supports advanced modeling features and ‘loosely coupled and flexible’ mapping of objects to SQL Server. Through extended ADO.NET Data Providers, EF supports other relational databases as well, including Oracle, DB2, MySql etc. EF also allows objects to have a different structure from your database schema. 


Although LINQ To SQL (L2S) is supported by Microsoft, it is not recommended. Entity Framework (EF) is definitely the way to go if you are working on something bigger (enterprise apps), need the flexibility of a solid framework, with the support for multiple databases and much more!


Note: LINQ to Entities is part of the Entity Framework and exposes many of the same features as L2S. It has replaced L2S as the standard mechanism for using LINQ on databases.

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...