Globalisation with jQuery

Download Sample application

Introduction

Recently, Microsoft announced three jQuery plugins as Official plugin.

  • jQuery Client Templating
  • Data linking
  • Globalization

I found all of them very cool feature for web development.
I have already written articles about the first two. Please find the link below.

I think, you all must have found the above articles very useful and will be using in near future or some of you might have started using this. I would request you all that to share your views about the article, which will be very helpful for me in better writing.

Now, In this article, I am going to discuss the last feature that is Globalization. When we say Globalization, the thing that comes in our mind is resource files. ASP.NET itself provides very good facility to cater the needs of Globalization.But which requires a postback, so it doesn’t look nice and not good in performance as well.

jQuery also provides us a way to implement the globalization, with supported plugin.

Again, I am writing few common points that I wrote in my last two Articles, for the new readers.

What is Globalization

As per MSDN “Globalization is the process of designing and developing
applications that function for multiple cultures
.”

So Globalization allows us to develop an application, which provides the option to localize the application in different cultures/languages. Now as we are working in global environment and serving the entire world, it becomes the necessity, to provide the globalization feature to our application.

So in this article, I am going to discuss, How we can provide the Globalization feature with the help of jQuery.

Prerequisite

  • jQuery library
  • Plugin for Globalization

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can download from the following link.

Download jQuery

To download plugin for Globalization,
click here

Globalization with jQuery:

So in this article, I am going to discuss, How we can utilise the Globalization feature of jQuery.

jQuery provides us the power to format and parse date, number and currencies in different cultures.  jQuery plugin defines over 350 cultures that currently supported by the plugin.

There are languages those are common in few regions/countries, but the formatting of numbers, currencies and date varies. Like English is spoken in several countries USA, UK and other various European countries. For these we have several cultures defined, that is used to identify the uniqueness amongst these countries.

This plugin comes in two flavors.

One file jQuery.glob.all.js includes around 350 cultures currently. So with this we need to include only this file for all
the cultures supported by the plugin. Another way,Plugin has also culture specific js files, that can included based on cultures that are supported by the application.

Some common APIs of the Plugin:

jQuery.culture:This holds the culture information that is currently set and is used in default case, i e while formatting various values this culture is used if no culture is specified.

jQuery.preferCulture:This method is used set the culture that user prefers and this culture is used for all the formatting, parsing etc done on the page. Actually as the method name suggests, it selects the best match culture that’s JavaScript is included in the page.

jQuery.format:
This method is used to format the date, number and currency in the given format string. This method is widely used.

jQuery.findClosestCulture:
This method works in similar way as preferCulture but it returns the best matching culture and don’t set the jQuery.culture to it.

jQuery.localize:
This method allows us to extend the specific culture and returns or set
the localized value.

There are many more functions like jQuery.parseInt, jQuery.parseFloat, jQuery.parseDate etc provided by the plugin, that can be used for several specific purposes.I have discussed some of them.

Let’s see some Examples:

Here In this section, I’ll be showing you some examples.

First Example:: In this example, I am displaying the stock deatils of Infosys on a specific date. It includes the price and number of unit sold on a specific date in two different cultures. Let’s see the running application.

 

 

 

 

 

 

 

 

 

Now lets move to the code. First let’s see the aspx code

<table style="border:1px solid black; font-family:Verdana; font-size:small">
            <tr>
                <td colspan="2"><h3>English - US</h3></td>
            </tr>
            <tr>
                <td>Stock Name</td>
                <td><span id="Text1" >Infosys</span></td>
            </tr>
            <tr>
                <td>Stock Price </td>
                <td><span id="price"/></td>
            </tr>
            <tr>
                <td>Day</td>
                <td><span id="date"/></td>
            </tr>
            <tr>
                <td>Units Transacted</td>
                <td><span id="unitsTransacted" /></td>
            </tr>
            <tr>
                <td colspan="2"><h3>France - French </h3></td>
            </tr>
            <tr>
                <td>Stock Name</td>
                <td><span id="Span1">Infosys</span></td>
            </tr>
            <tr>
                <td>Stock Price </td>
                <td><span id="price1"/></td>
            </tr>
            <tr>
                <td>Date</td>
                <td><span id="date1"/></td>
            </tr>
            <tr>
                <td>Units Transacted</td>
                <td><span id="unitsTransacted1" /></td>
            </tr>
        </table>

Above as you can see, I am displaying Stock details Infosys in two different cultures English-US and France-French.
Now lets jump to script. Here the script that I have include. These are

 <script src="scripts/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="scripts/jquery.glob.js" type="text/javascript"></script>
    <script src="scripts/globinfo/jQuery.glob.all.js" type="text/javascript"></script>

So I have included three files here. First the jQuery file the common Global file and last one is the file that contains all culture specific details.
Now rest javascript code is

       // Set culture
        jQuery.preferCulture("en-US");

        // Formatting price
        var price = jQuery.format(3899.888, "c");
        //Assigning stock price to the control
        jQuery("#price").html(price);

        // Formatting date
        var date = jQuery.format(new Date(2010, 11, 15), "D");
        //Assigning date to the control
        jQuery("#date").html(date);

        // Formatring units trabsacted
        var units = jQuery.format(45678.576, "n2");
        //Assigning units to the control
        jQuery("#unitsTransacted").html(units);

        // Set culture
        jQuery.preferCulture("fr-FR");

        // Format price
        var price = jQuery.format(3899.888, "c");
        //Assigning stock price to the control
       jQuery("#price1").html(price);

        // Format date available
        var date = jQuery.format(new Date(2010, 11, 15), "D");
        //Assigning date to the control
        jQuery("#date1").html(date);

        // Format units in stock
        var units = jQuery.format(45678.576, "n2");
        //Assigning units to the control
        jQuery("#unitsTransacted1").html(units);

As you can see from the above code, that I have used the preferCulture method to set the culture and format method to format the various data like price, date and units here.

So above one is the simple example which describes that how the plugin works.

Changing culture dynamically:

Now in this example, I am talking about another scenario where user may want to select the culture dynamically, and want to get the page updated accordingly.

In my sample example, I am having one dropdown, user selects the culture and page is getting updated accordingly.
First lets see the application.

 

 

 

 

 

 

 

 

Now let’s jump on the code.First let’s view the aspx code

 <table style="border:1px solid black; font-family:Verdana; font-size:small">
            <tr>
                <td style="font-weight:bold">Select Culture</td>
                <td>
                    <select id="ddlCultures">
                        <option value="en-US">English - US</option>
                        <option value="en-IN">EngLish - India</option>
                        <option value="en-AU">EngLish - Australia</option>
                        <option value="fr-FR">French - France</option>
                        <option value="es-MX">Spanish - Mexico</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td style="font-weight:bold">Stock Name</td>
                <td> <span id="Text1">Infosys </span></td>
            </tr>
            <tr>
                <td style="font-weight:bold">Stock Price</td>
                <td><span id="price"/></td>
            </tr>
            <tr>
                <td style="font-weight:bold">Day</td>
                <td><span id="date"/></td>
            </tr>
            <tr>
                <td style="font-weight:bold">Units Transacted</td>
                <td><span id="unitsTransacted"/></td>
            </tr>
        </table>

Now let’s see the scripts included

<script src="scripts/jquery-1.4.2.js" type="text/javascript"></script>
<script src="scripts/jquery.glob.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.en-US.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.en-IN.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.en-AU.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.fr-FR.min.js" type="text/javascript"></script>
<script src="scripts/globinfo/jQuery.glob.es-MX.min.js" type="text/javascript"></script>

As you can see above,I have included culture specific files instead of one common files for all the cultures. Because the size of common files for all 350 cultures could be a performance overhead. As we know, that these are specific
cultures that are going to be used in the application, then we should go for culture specific files.

Now javascript code

     LoadPage("en-US");

     jQuery("#ddlCultures").change(function() {
         var selectedCulture = this.value;
         LoadPage(selectedCulture);
     });

        function LoadPage(selectedCulture) {

            jQuery.preferCulture(selectedCulture);

            var price = $.format(3899.888, "c");
            jQuery("#price").html('12345');

            // Format date available
            var date = $.format(new Date(2011, 12, 25), "D");
            jQuery("#date").html(date);

            // Format units in stock
            var units = $.format(45678, "n0");
            jQuery("#unitsTransacted").html(units);
        }

In this code, I have taken a dropdown with multiple cultures. One can select the desired culture and page will be modified accordingly. I have used the same form but I have called preferculture method based on the selection of dropdown.

Rest code is same as above example.

Picking culture info from Browser:

Sometimes user also set culture preferences in the browser. And lots of applications rely on it. So we can also read the culture information from the browser and can load the page accordingly. To get the culture information we
can use the following.

  var language = "<%= Request.UserLanguages[0] %>";
  jQuery.preferCulture(language);

Conclusion:

This feature is very useful for the applications targeting the entire Globe. As you are moving forward for RIA applications, this plugin of jQuery could be key.

Hope you all must have enjoyed my above article. Please share your valuable feedback, that will help me a lot for better writing.

Feedback and Suggestions:

Hope you all must have enjoyed my above article. Please share your valuable feedback, that will help me a lot for better writing.

Exploring Client Callback

Download Demo

Client Callback is one of very important features, provided by ASP.NET. Earlier I was not aware on this. In my last application, I implemented this and got a very good result.

This is another way to avoid full post back on the page and can be a great alternative of the Ajax update panel.

Also I was looking for a good article but could not find one, explaining the details. So thought of sharing to you all.

There are various ways, update a part of page without a full page post back, Like update panel, callback etc. But I found callback, is a very useful approach certain times. When we used to display the data.

So here, in this Article I will be discussing the Client Callback, How to implement this, their pros n cons,and how it is handled by the ASP.NET.

What is Client Call back:

We can define the Client Call back like  this “Client Call back provides us a way to call a server side code/method asynchronously and fetch some new data without page refresh.”

So one can initiate Client callback from JavaScript and get the result that can be shown on UI after any required modification. Lets take an pictorial overview.

How to implement Client Callback: To implement call back, one need to follow the below steps.

Things required at Server Side

1 – Implement interface ICallbackEventHandler on any page or control where implemented.

2 – Need to implement two methods RaiseCallbackEvent and GetCallbackResult provided by the interface ICallbackEventHandler.

3 –  RaiseCallbackEvent event is called to perform the Callback on server

4- GetCallbackResult event returns the result of the callback

(Note: There is a property IsCallback of page returns true, if callback is in progress at server.)

Things required at Client Side:

Apart from the above steps, we also require few Client script to complete the Callback functionality. These are

1 – A function that is registered from server and called by any function that want to initiate the callback. It also takes one argument, that can be passed to server.

2- Another function, that is called after finishing the callback, which returns the callback result

3 – On more helper function that performs the actual request to the server. This function is generated automatically by ASP.NET when you generate a reference to this function by using the GetCallbackEventReference method in server code.

Lots more thing written, Not lets jump to code

Here in my example: I have a button and a textbox which is taking Sex type. And on clicking of this button, I am initiating the callback and sending the the type as an argument and accordingly

creating the result and sending it back to the client. And at client side I am displaying in a Client side Div.

So this is a demo, for How to use callback.

Server side code:

I have taken a global variable string, that is used to hold the response, sent to the client as.

string result;

And

public void RaiseCallbackEvent(String eventArgument)
 {
 if (eventArgument == "M")
 {
 result = "You are Male";
 }
 else if (eventArgument == "F")
 {
 result = "You are Female";
 }
 else
 {
 result = "Cannot say";
 }
 }
 

The above method is called at server side, which has one argument, that is passed from the Client. It takes here the textbox value and return the result accordingly.

Another Server side method that is called,

public string GetCallbackResult()
 {
 return result;
 }

It just returned the result that is generated by the method RaiseCallbackEvent.

Also, we need to register some Client side script at Page load.

Here, we need to create a Callback reference, that is the Client side method that is called, after finishing the callback. and assign that reference, in the method that initiate callback from Client.

Lets see the code,

protected void Page_Load(object sender, EventArgs e)
 {
 //Creating a reference of Client side Method, that is called after callback on server
 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
 "ReceiveServerData", "");

 //Putting the reference in the method that will initiate Callback
 String callbackScript = "function CallServer(arg, context) {" +
 cbReference + "; }";

 //Registering the method
 Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
 "CallServer", callbackScript, true);
 }

We should also write one line at pageload, because no code is required to be executed when call back is in progress

if (Page.IsCallback)
 return;

Client Side ( aspx) code:

There are two javascript function. First is called to initiate the callback.And other one is called after finsihing server side callback events to update the UI.

Let’s see first one

function InitiateCallBack() {
 // gets the input from input box
 var type = document.getElementById('txtType').value;
 //Intiate the callback
 CallServer(type,'');
 }

It is called from when user clicks on button. Now let’s move other function

// Called after the server side processing is done
 function ReceiveServerData(arg, context) {
 //arg: hold the result
 //Updating the UI
 document.getElementById('divCallbacl').innerHTML = arg;
 }

And my aspx code is like this.

<div>
 <span>Enter your Sex(M/F):</span>
 <input id="txtType" type="text" />
 <input id="Button1" type="button" value="button" onclick="InitiateCallBack();"/>
 <div id="divCallbacl">
 </div>

Above are self explanatory.

ClientCallback: Digging deep

As I said, it gives faster response, it actually trim down the page life cycle. Many of events does not execute. We’ll see it. Also to distinguish, at server side, whether it is a normal postback or a Callback. One will find the property isCallback true, which shows that it is a callback request, which I have suggested to use at Pageload earlier. Also the IsPostBack property will also be true.

One more thing, viewstate  information is retireved and available at server but any changes made in it, does not persist. As we’ll see the Callback lifecycle Saveviewstate event doesn’t fire. Which also leads in better performance.

Now lets see the lifecycle comparison between normal postback and a Callback

 

 

 

 

 

 

 

 

 

 

 

As above we can see, SaveViewstate and render events does not get fired on server. So it does two things, one we get better performance and on flip side we cannot save viewstate so we should keep in mind while implementing this.

Where to use, where not to:

– Callback is light action and gives us better performance over normal Update Panels.

– One should use Client Callback, for display purpose only. Because we would not get the updated/entered data from the UI on server.

– Also viewstate does not get maintained across during Postback. So one should not rely on it.

Data linking with jQuery

Download Sample

Recently, Microsoft anounced three jQuery plugins as Official plugin.

  • jQuery Client Templating
  • Data linking
  • Globalisation.

In my last article, I discussed about the jQuery Templating. You can view that Article here .

So I think, you all must find Templating article very useful. Because, by the time
web applications development is evolving, we are moving towards Client side
development/scripting, to provide fast and very trendy/flashy look and feel.

So in this article, I am going to discuss another very cool feature, ie
Data linking.This helps us linkling the data and the UI.

What is jQuery:

jQuery is a JavaScript library that works on top of the JavaScript.
jQuery provides a very simple way for HTML document traversing,
DOM manipulation, event handling, animating, and Ajax interactions for
rapid web development. That could have been very complex while working
with normal JavaScript.

jQuery is becoming more and more popular day by day. Even it was integrated
with VS2008 and also available with VS2010.
jQuery is open source. Due to its features,
Microsoft started to support jQuery team and also working with them,
to provide better web based tools to their Clients.

Prerequisite:

  • jQuery library
  • A plugin for datalinking
  • JSON library

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can
download from the following link.

Download jQuery

To download JSON library,
click here

Data Linking:

Data kinking provides us a way, to link our data/objects to UI controls.
Means, if the controls get updated, the underlying data object would
also be updated. In the same way, if the data objects get updated,
the controls on UI will also get updated (In case of two way linking).

Means once you linked your data with the controls, you don’t need think about
the data object. The syncing between data object and your UI will be taken care
by the jQuery plug in.

So you can imagine, you dont need to get the updated data from the
controls and update the object, which is required at the time
of saving the data at server. Which requires lot more code to be
written and also error prone.

There are several options to link the data.

  • One way Linking
  • Two way Linking

One Way Linking:

One can link the UI controls to some object. Means the object will
always be in sync with UI. Whenever the Data in UI will get changed the underlying
object will also get updated. So one need not worry about the data once it is
done, one can send the object directly to the server for further processing

I have explained it with one sample.

In my example, there is form named as Add Vehicle, where user can enter the
Vehicle name and its price, then click on the Add Vehicle to add the vehicle
at server side.
One can also see the state of the underlying object at any point of time, using
Show Updated Object button.
Now lets go through the code.

Lets see aspx code first

 <table>
            <tr>
                <td colspan="2"><h2>Add Vehicle to Vehicle Store</h2></td>
            </tr>
            <tr>
                <td>Vehicle Name</td>
                <td><input id="txtVName" type="text" /></td>
            </tr>
            <tr>
                <td>Price</td>
                <td><input id="txtVPrice" type="text" /></td>
            </tr>
            <tr>
                <td><input id="btnShow" type="button" value="Show updated object"
                 onclick="ShowUpdatedData();"/> </td>
                <td><input id="btnAdd" type="button" value="Add vehicle to store"
                 onclick="AddVehicle();"/> </td>
            </tr>
        </table>

Here I have two input box to enter the name and price of the vehicle, and two
buttons, one to show the object and other one to add it.

Now lets move to Javascript code,

 var vehicle = {};
 //linking the UI controls with vehicle object
        $(document).ready(function() {
        $(vehicle)
            .linkFrom('Name', '#txtVName', 'val')
            .linkFrom('Price', '#txtVPrice', 'val')
    });

Here I have a global variable vehicle that is linked with the using
linkForm method for the plugin as shown above.

I have also written the code for adding the data at server, using
jQuery Ajax Call as

 function AddVehicle() {
        var inputs = new Object();
        inputs.vehicle = JSON.stringify(vehicle);
        $.ajax({
            type: "POST",
            url: "AddVehcle.aspx/AdVehicle",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        });

    }
    function ShowStatus(result) {
        alert(result.d);
    }
    function AjaxFailed(result) {
        alert('Ajax failed');
    }

    //to show the state of the object
     function ShowUpdatedData() {
        alert([vehicle.Name, vehicle.Price]);
    }
    

Also lets have a look at server side code


public partial class AddVehicle : System.Web.UI.Page
{
public static List lstVehicle = null;
protected void Page_Load(object sender, EventArgs e)
{

}
//This method adds one vehicle
[WebMethod()]
public static string AdVehicle(string vehicle)
{
if (lstVehicle == null)
{
lstVehicle = new List();
}
JavaScriptSerializer ser = new JavaScriptSerializer();
Vehicle objVehicle = ser.Deserialize(vehicle);
lstVehicle.Add(objVehicle);
return "Vehicle added sucessfully";
}
}

public class Vehicle
{
public string Name { get; set; }
public decimal Price { get; set; }
}

The above code is self-explanatory.AdVehicle() is called to add a vehicle using Ajax call.

Now lets run the application,
Here I have entered data about one vehicle,

Now when I click to see the updated object, ShowUpdatedData
then get to see the vehicle object as below

Converters:

There is also a good feature provided. We may not
want to save the data as we show at UI. Like if there is some price or quantity,
we may want to format the quantity in some manner before saving. So for that
we can put some converters at the time of linking as

 $(document).ready(function() {
    $(vehicle)
        .linkFrom('Name', '#txtVName', 'val')
        .linkFrom('Price', '#txtVPrice', 'val',
        //Converter that will be called before updating the underlying object
        function(value) { return value.replace(/[^0-9.]/g, "") }
        );
     });

As you can see, I have a converter with Price, that will return only numbers and dot.
Lets see it running

What it is doing, its taking the value from the textbox converting it with the
conerter and the setting to property Price of the vehicle object.

Two way linking:

It also do all the things as above but have one more feature. You can also update the object from code also,  as soon as object will get updated that will also be reflected in the UI.

This feature can be very use full in editing/searching feature.You searched
some data and now want to update it. Now you can update UI as well as underlying
object, both UI and data will always be in sync.

I have discussed it with one sample

In my example, Lets we have a list of person at server. One can fetch the
details of an existing person.One also update the existing person or can add a
new person.

So I have created one class person as

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string SSN { get; set; }
    public string Gender { get; set; }
    public string ContactNo { get; set; }

}

My aspx page is as

<table>
            <tr>
                <td> Name </td>
                <td>
                    <input id="txtPersonName" type="text" />
                    <input id="Button1" type="button" value="GetPersonDetails"
                    onclick="PopulatePersonDetails();"/>
                </td>
            </tr>
            <tr>
                <td colspan="3"> <b>Person Details</b></td>
            </tr>
            <tr>
                <td>Name</td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td>Age</td>
                <td><input id="txtAge" type="text" /></td>
            </tr>
            <tr>
                <td>SSN</td>
                <td><input id="txtSSN" type="text" /></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input id="txtGender" type="text" /></td>
            </tr>
            <tr>
                <td>Contact Number</td>
                <td><input id="txtCNo" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input id="Button3" type="button" value="Show Updated JS Object"
                     onclick="ShowUpdatedData();"/>
                    <input id="Button2" type="button" value="Add/Update Person"
                     onclick="UpdateorAddData();"/>
                </td>
            </tr>
        </table>

As you can see, in my page I have put the input boxes for every property of
person.

At the start of the page I have also, provided a input box to enter the person name and
a button to fetch the requested person from the server.

I have provided two more buttons, One to see the updated objects in javascript alert
and another one to update the data at the server. It actually looks the list for the SSN if it found then update the existing record else add the new
person. We’ll see the code in a moment.

Now lets move the Javascript code that is written.
The code that is used to link the data

First I have declared one global object that object will be linked to the UI controls
as
var person = {};

and the code for linking the data is

//Linking the controls from the object
 $(document).ready(function()
    {
        $(person)
        .linkBoth('Name','#txtName','val')
        .linkBoth('Age','#txtAge','val')
        .linkBoth('SSN','#txtSSN','val')
        .linkBoth('Gender','#txtGender','val')
        .linkBoth('ContactNo','#txtCNo','val');

    });

As from the above you can see, that person object is used and
linked using linkBoth method, which takes three parameters
first the name of the property of the object,
second the id of the control with sign #
third val
Now, after this you don’t need to worry about the data, all things will be taken care the
plugin itself.

Rest javascript method, I have used

// To fetch the detail from the server of the entert person name
 function PopulatePersonDetails() {

        var inputs = new Object();
        inputs.name = document.getElementById('txtPersonName').value;

        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/GetPerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        });

        // To be called when ajax call succeeded
        //If no object will be found, it'll show an error message as
        //'Person Not found' else call update the person object
         function AjaxSucceeded(result) {
            if (result.d == 'null')
                alert('Person Not found');
            else
                $(person).attr(JSON.parse(result.d));
        }

        //Will be called, if ajax call gets failed somehow.
        function AjaxFailed(result) {
            alert('Ajax failed');
        }
    }

For the functionality of the updating or adding the person
object at server we have following methods

    //This function get the global variable person object
    //which is always sync with with UI and sends it
    //to server to add/update
    function UpdateorAddData() {

        var inputs = new Object();
        inputs.person = JSON.stringify(person);
        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/AddUpdatePerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        });

        }

        //This function is to show the status whether a new person is added or updated
         function ShowStatus(result) {
            alert(result.d);
        }

As I have linked the object to the UI controls, so I am just picking or updating
the person object, that always gives the most updated and synced data.

Also lets have a look to server side code

public partial class EditPerson : System.Web.UI.Page
{
public static List lstPerson = null;
protected void Page_Load(object sender, EventArgs e)
{
}

//This method will return the searched person.
[WebMethod()]
public static string GetPerson(string name)
{
InitializePersons();
JavaScriptSerializer ser = new JavaScriptSerializer();
// ser.Serialize(persons);
return ser.Serialize(lstPerson.Find(p => p.Name == name));
}

//This method will add or update a person based on SSN
[WebMethod()]
public static string AddUpdatePerson(string person)
{
string status;
JavaScriptSerializer ser = new JavaScriptSerializer();
Person obj = ser.Deserialize(person);
InitializePersons();
Person per = lstPerson.Find(p => p.SSN == obj.SSN);
if (per == null)
{
lstPerson.Add(obj);
status = "New person added";
}
else
{
// Updating the person
lstPerson.Remove(per);
lstPerson.Add(obj);
status = "Person updated";
}

// ser.Serialize(persons);
return status;
}

public static void InitializePersons()
{
if (lstPerson == null)
{
lstPerson = new List()
{
new Person { Age = 27, Name= "Brij",
Gender="Male", ContactNo="123456789",
SSN="CC123456"},
new Person { Age = 18, Name = "Ravi",
Gender = "Male", ContactNo = "987654321",
SSN="AB654321"}
};
}
}
}

Lets see the runing application,

I have few person data at server.When I am entering and clicking
for getting the person details, UI gets updated. While actually I am making
an Ajax call, to get the person data and updating the underlying object
as discussed in above code.

Rest things as per the Vehicle Store example

I have also to added a button, which one can click to see the state of the person
object at any point of time, when one wants.

Please find the full sample in attachment

Conclusion:

I found this feature very useful, while using ajax and jQuery
as I discussed in above example. One should go for the one way or two way linking
based on their requirements.

Hope you all must have enjoyed my above article. Please share your valuable
feedback, that will help me a lot for better writing.

Feedback and Suggestions:

Hope you all must have enjoyed my above article. Please share your valuable
feedback, that will help me a lot for better writing.

Also lets have a look at server side code

ViewState: Various ways to reduce performance overhead

Introduction
In this Article, I am going to explore the Viewstate. View state is one thing that always I liked to use. It makes our life easier. As we all know that Viewstate is one way of maintaining the states in the web applications.

As we know, a web page is created every time when a page is posted to the server.It means The values that user entered in the webpage is going to be vanished after the poastback or submit. To get rid of this problem, ASP.NET framework provides a way to maintain these values by virtue of Viewstate. When we enable the viewstate of any control, the value is going to be maintained on every postbacks or server roundtrips.

But how these values get maintained? It doesn’t come free.View state uses hidden valriable that resides on the page to store the controls values. It means that if a page have lots of controls with viewstate enabled the page size would become heavy, in several of kilobytes ie it will take longer time to download.And also on every postback all the data is posted to the server i e increasing the network tarffic as well.

As in new era application, we use lots of heavy controls like gridview etc, on our page which makes page size exponetially heavy.It is always recommended to use viewsate judiciously and even some programmers try to to avoid using this cause of performace overhead.

Here , I am going to discuss how we can reduce the performance overhead caused by viewstate.

Problems with viewstate:
n our new era application, we generally have lots of rich and heavy controls on our page and also provide lots of functionality on the page with the help of few latest technology AJAX etc. To accomplish our task we use Viewstate a lot but as we know it doesn’t come free it has a performance overhead.

As we know viewstate is stored on the page in form of hidden variable. Its always advised to use viewstate as less as possible. we have also other ways to reduce the performance overhead. So we have several ways,here I am going to discuss the following ways

* By compressing decompressing the viewstate
* Aanother way to store the view state at some other server say on web server.

ViewState Compression/Decompression
We can compress the viewstate to reduce the pagesize. By compressing the viewstate we can reduce the viewstate size by more than 30%. But here the question arises, where to compress and decompress the viewstate. For that we have to dig into the Page life cycle. As we know, viewstate is used by the ASP.NET to populate the controls. So we should compress the viewstate after all the changes are done in the viewstate and saving it after compression and we have to decompress the viewstate just before it is used by asp.net to load all the controls from viewstate . So lets jump to thepage life cycle and see our we can fit our requirement.
Page Life Cycle
As we can see there are two methods,One SaveViewState that is responsible for collecting the view state information for all of the controls in its control hierarchy in this method and persist it it in __viewstate hiddenform field. The view state is serialized to the hidden form field in the SavePageStateToPersistenceMedium() method during the save view state stage, and is deserialized by the Page class’s LoadPageStateFromPersistenceMedium() method in the load view state stage. So here in these methods we can compress and decompress the viewstate. Lets take a pictorial view.
Flow
So here, we need to override the methods SavePageStateToPersistenceMedium()for compressing the viewstate and SavePageStateToPersistenceMedium() for decompressing the viewstate. Here I am going to use GZip for compression that is provided by the .NET itself.And this is available in th namespace System.IO.Compression….
Complete article has been published on CodeProject. To view Click here

A walkthrough to Application State

A walkthrough to Application State

As we all know,web is stateless .A Web page is recreated every time it is posted back to the server.In traditional web programming, that all the information within the page and control gets wiped off on every postback.To overcome this problem,ASP.NET framework provides various ways to preserve the states at various stages like controlstate,viewstate,cookies,session etc.These can be defined in at client side and server side state management.Please see the image below.

Various ways to maintain the state
Application LifeCycle
First I am going to explain ASP.NET Application Lifecycle.One need to really understand the application Lifecycle, so that one code efficiently and use the resources available.Also it is very important to discuss, as we are going to Application level events, objects etc.

ASP.NET uses lazy initialization technique for creating the application domains ie Application domain for an application is created only when the first request is recieved by the web server. We can categorise Application life cycle in several stages.These can be

Stage 1: User first requests any resource from the webserver.

Stage 2: Application recieves very first request from the application.

Stage 3: Application basic Objects are created

Stage 4: An HTTPapplication object is assigned to the request.

Stage 5: And the request is processed by the HTTPApplication pipeline

I’ll explain the points one by one.

Stage 1: The Application life cycle starts when a user hits the URL by typing it to on browser.The browser sent this request to the webserver.When webserver recieves the request from browser, it examines the file extension of the requested file and checks which ISAPI extension is required to handle this request and then passes the request to approriate ISAPI extension.
Application state flow

Note 1: If any extension is not mapped to any ISAPI extension, then ASP.NET will not recieve the request and request is handled by the server itself and ASP.NET authentication etc.. will not be applied.

Note 2: We can also make our own custom handler, to process any specific file extension.

Stage 2: When ASP.NET recieves first request, the Application manager creates an application domain for it,Application domain are very important because they provide the isolation amongst various applications on the webserver and every application domain is loaded and unloaded separately and in application domain an instance of class HostingEnvironment is created which provides access to information about all application resources.
Application Lifecycle

Stage 3: After creating the application domain and hosting environment, asp.net initializes the baisc objects as HTTPContext, HTTPRequest and HTTPResponse. HTTPContext holds objects to the specific application request as HTTPRequest and HTTPResponse.HTTPRequest contains all the informaion regarding the current request like cookies, browser information etc. and HTTPResponse contains the response that is sent to client.

Stage 4: Here all the basic objects are being initialized and the application is being started with creation of HTTPApplication class, if there is Global.asax(It is derived from HTTPApplication class) is there in the application then that is instantiated.
Application Life Cycle

Note: When first time the application is accessed the HTTPApplication instance is created for further reqests it may be used other requests as well.

Stage 5
: There are a lot of events are executed by the HTTPApplication class.Here I have listed down few important ones.These events can be used for any specific requirement.

Page Life Cycle

Complete article has been published on CodeProject. To view Click here