3 August 2013

ASP.Net Page Life Cycle Events

ASP.Net Page Life Cycle Events:

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.

Following are the page life cycle events:

PreInit  PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.

Init  Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.

InitComplete InitComplete event allows tracking of view state. All the controls turn on view-state tracking.

LoadViewState  LoadViewState event allows loading view state information into the controls.

LoadPostData  during this phase, the contents of all the input fields defined with the
tag are processed.

PreLoad  PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.

Load the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.

LoadComplete  the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.

PreRender  the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.

PreRenderComplete  as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.

SaveStateComplete  state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.


UnLoad  the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.


Alternative to View State in MVC in Asp.net

Alternative to View State in MVC in Asp.net

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. TempData preserves value for current and next request.

TempData - http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html


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


Consistency level in Azure cosmos db

 Consistency level in Azure cosmos db Azure Cosmos DB offers five well-defined consistency levels to provide developers with the flexibility...