29 August 2013

HTTP Modules vs Global.asax Files

HTTP Modules vs Global.asax Files
You can implement much of the functionality of a Http modules in the application's Global.asax file, which enables you to respond to application events. However, modules have an advantage over the Global.asax file because they are encapsulated and can be created one time and used in many different applications. By adding them to the global assembly cache and registering them in the Machine.config file, you can reuse them across applications.

The advantage of using the Global.asax file is that you can handle other registered events such as Session_Start and Session_End. In addition, the Global.asax file enables you to instantiate global objects that are available throughout the application.
You should use a module whenever you must create code that depends on application events, and when the following conditions are true:
  • You want to re-use the module in other applications.
  • You want to avoid putting complex code in the Global.asax file.
  • The module applies to all requests in the pipeline (IIS 7.0 Integrated mode only).

18 August 2013

GAC - Global Assembly cache

GAC - Global Assembly cache
The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.


Worker Process and Application Pool in asp.net

Worker Process and Application Pool in asp.net
Worker Process:

Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.

Application Pool:  

Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools.


15 August 2013

Serialization and DeSerialization in C#

Serialization and DeSerialization in C#


Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Serialization Graphic

The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Binary Serialization

Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams.

XML Serialization

XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to XML.System.Xml.Serialization contains the classes necessary for serializing and deserializing XML.

SOAP Serialization

XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. As with regular XML serialization, attributes can be used to control the literal-style SOAP messages generated by an XML Web service.

Basic Serialization

The only requirement in basic serialization is that the object has the SerializableAttribute attribute applied. The NonSerializedAttribute can be used to keep specific fields from being serialized.
When you use basic serialization, the versioning of objects may create problems, in which case custom serialization may be preferable. Basic serialization is the easiest way to perform serialization, but it does not provide much control over the process.

Custom Serialization

In custom serialization, you can specify exactly which objects will be serialized and how it will be done. The class must be marked SerializableAttribute and implement theISerializable interface.

12 August 2013

Html.TextBox vs Html.TextBoxFor in MVC

Html.TextBox vs Html.TextBoxFor in MVC

Html.TextBox and Html.DropDownList are not strongly typed and hence they doen't require a
strongly typed view. This means that we can hardcore whatever name we want.

On the other hand, Html.TextFor and Html.DropDownListFor are strongly typed and requires
a strongly typed view, and the name is inferred from the Lambda expression.

Whether we use Html.TextBox and Html.DropDownlist or Html.TextBoxFor and Html.DropDownListFor,
the end result is the same. they produce the same Html.


Nested List in C#

Nested List in C#

Consider there are two Class

 public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public List< Addresses > { get; set; }

    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string ZipCode { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }

Procedure used to add multiple class in the List
var personDetails = new List< Person >
                              {
                                  new Person
                                  {
                                      Id = 1, FirstName = "Arun",
                                      LastName = "Prakash",
                                      Addresses = new List< Address >
                                                      {
                                                          new Address{Line1 = "Hope College",Line2 = "Coimbatore"}
                                                 
                                                      }
                                  },
                                                                                                     
                                  new Person{
                                      Id = 2, FirstName = "Sanjay",
                                      LastName = "Ramasamy",
                                      Addresses = new List< Address >
                                                      {
                                                          new Address{Line1 = "Anna Salai",Line2= "Chennai"}
                                                     
                                                      }
                                  }
                              };

5 August 2013

Html.RenderPartial vs Html.Partial, Html.RenderAction vs Html.Action

Html.RenderPartial vs Html.Partial, Html.RenderAction vs Html.Action 


@Html.Partial("Details")
@Html.Action("Index", "Home")

and

@{ Html.RenderPartial("Details"); }
@{ Html.RenderAction("Index", "Home"); }

Html.Partial returns a string, Html.RenderPartial calls Write internally, and returns void.

You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial.

Html.RenderPartial -The result will be written to the Response stream during the execution.

The same is true for Html.Action and Html.RenderAction.


MVC 3 Ajax Json Sample

MVC 3 Ajax Json Sample 





























Create model name PersonDetails.cs
using System.Collections.Generic;

namespace MVCJsonAjax.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public List< Address > Addresses { get; set; }
    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string ZipCode { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }

}


Create Controller - SaveController.cs

using System.Web.Mvc;
using MVCJsonAjax.Models;

namespace MVCJsonAjax.Controllers
{
    public class SaveController : Controller
    {
        //
        // GET: /Save/

        [ActionName("SaveData"),HttpGet]
        public ActionResult SaveData()
        {
            return View();
        }


     [ActionName("SaveData"), HttpPost]
        public JsonResult SaveData(Person objPerson,Address objAddress)
         {

             JsonResult result = new JsonResult();

            // Save logic - save person and address details

             result.Data = "Saved Successfully";
             return result;
        }
 
    }
}

Create View for ActionResult SaveData()

@using MVCJsonAjax.Models
@{
    ViewBag.Title = "SaveData";
}
< h2 >
    Save Data< /h2 >

    < div>
    < div id="message" >
    < /div>
< /div >


< script type =" text/javascript ">
    $(document).ready(function () {
         
        $('#btnSubmit').click(function () {
         
            var Person =
            {
                FirstName: $('#Item1_FirstName').val(),
                LastName: $('#Item1_LastName').val()
            };

            var Address =
                {
                    Line1: $('#Item2_Line1').val(),
                    Line2: $('#Item2_Line2').val(),
                    ZipCode: $('#Item2_ZipCode').val(),
                    City: $('#Item2_City').val(),
                    State: $('#Item2_State').val(),
                    Country: $('#Item2_Country').val()
                };

                var obj = { "Per": Person, "Add": Address};

            $.ajax({
                url: '/Save/SaveData',
                type: "POST",
                data:JSON.stringify({objPerson: Person ,objAddress: Address }),              
                cache: false,
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                success: function (result) {
                    $('#message').html(result).fadeIn();

                }
            });

            return false;
        });
    });




@model Tuple< Person, Address >
@using ( Html.BeginForm() )
{
    < table >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item1.FirstName)
                @Html.TextBoxFor(m => m.Item1.FirstName)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item1.LastName)
                @Html.TextBoxFor(m => m.Item1.LastName)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.Line1)
                @Html.TextBoxFor(m => m.Item2.Line1)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.Line2)
                @Html.TextBoxFor(m => m.Item2.Line2)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.ZipCode)
                @Html.TextBoxFor(m => m.Item2.ZipCode)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.City)
                @Html.TextBoxFor(m => m.Item2.City)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.State)
                @Html.TextBoxFor(m => m.Item2.State)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.Country)
                @Html.TextBoxFor(m => m.Item2.Country)
            < /td >
        < /tr >
        < tr >
            < td >
                <  input type="submit" value="Submit" id="btnSubmit" / >
            < /td >
        < /tr >
    < /table >

}



4 August 2013

Dynamic v. Strongly Typed Views in MVC C# Razor Engine

Dynamic vs. Strongly Typed Views

Dynamic
Because we’re using a dynamic and not a strongly typed view, intellisense doesn’t help us. The completed code is shown below:

@model dynamic
         
@ {
    ViewBag.Title = "IndexNotStonglyTyped";
}

Index Not Stongly Typed< /h2 >



< p >
 < ul >
@foreach (var blog in Model) {
   < li >
    < a href="@blog.URL">@blog.Name< /a >
   < /li >  
}
 < /ul >

< /p >

Strongly Typed Views
When it is strongly typed view.

5658.StrongView[1]

Inside the new view template we get intellisense support.

7002.intellesince[1]


Handle Multiple Submit button in MVC C#

Handle Multiple Submit button in MVC C#

View
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
< input type="submit" name="submitButton" value="Send" / >
< input type="submit" name="submitButton" value="Cancel" / >

<% Html.EndForm(); %>

Controller
public class MyController : Controller {
    public ActionResult MyAction(string submitButton) {
        switch(submitButton) {
            case "Send":
                // delegate sending to another controller action
                return(Send());
            case "Cancel":
                // call another action to perform the cancellation
                return(Cancel());
            default:
                // If they've submitted the form without a submitButton,
                // just return the view again.
                return(View());
        }
    }

    private ActionResult Cancel() {
        // process the cancellation request here.
        return(View("Cancelled"));
    }

    private ActionResult Send() {
        // perform the actual send operation here.
        return(View("SendConfirmed"));
    }

}






Delegates Example in C#

//Delegates Example in C#

using System;
using System.Windows.Forms;

namespace DelegatesTesting
{
    public partial class DelegatesTest : Form
    {
        public DelegatesTest()
        {
            InitializeComponent();
        }



        //Delegate Declaration
        public delegate int PointtoAddFunction(int i, int j);
     
        private void btnSubmit_Click(object sender, EventArgs e)
        {

            //Point the Delegate object with Method
            PointtoAddFunction handler = AddFunction;

            //Invoke the Method
            MessageBox.Show(handler(10, 12).ToString());

        }

        //Method
        public int AddFunction(int i, int j)
        {
            return i + j;
        }    
    }
}



Datatable to List in C# using Linq

Datatable to List in C# using Linq

//StudentDetails Class with Entity Details
 public class StudentDetails
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public string ClassName { get; set; }
        public string Section { get; set; }
    }
  

//Dataaccess part, Microsoft Sqlhelper class  used
 public List GetStudentDetails(int studentID)
        {
            DataSet ds = new DataSet();
            SqlParameter[] SqlParam = null;
            SqlParam = new SqlParameter[1];
            SqlCommand SqlCmd = new SqlCommand();
            List objStud = new List();
            try
            {
                SqlParam[0] = new SqlParameter("@StudentID", SqlDbType.Int);
                SqlParam[0].Value = studentID;
                SqlHelper.FillDataset(DBconnection(), CommandType.StoredProcedure, "usp_Get_StudentDetails", ds, new string[] { "Display" }, SqlParam);
               
 objStud = ds.Tables[0].AsEnumerable().Select(data => new StudentDetails() { StudentID = (int)data["StudentID"], StudentName = (string)data["StudentName"], ClassName = (string)data["ClassName"], Section = (string)data["Section"] }).ToList();
                return objStud;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (ds != null)
                {
                    ds.Dispose();
                }
                objStud = null;
            }
        }


MVC Menu

MVC Menu

1. MVC Programming Model in Asp.net

2. Setting the Default Page or Route in MVC application


3. Difference between Asp.Net MVC and Web Forms


4.ViewBag, ViewData, TempData and View State in MVC

5.Alternative to View State in MVC in Asp.net

6.Handle Multiple Submit button in MVC C#

7.Html.TextBox vs Html.TextBoxFor in MVC

8.Html.RenderPartial vs Html.Partial, Html.RenderAction vs Html.Action





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




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...