jQuerify your ASP.NET apps - Microsoft Community Tech Days 2010

Happy to say that I have presented at Microsoft Community Tech Days 2010 on "jQuerify your ASP.NET apps" at Microsoft Hyderabad. The event, organized by Microsoft User Group Hyderabad (MUGH), had 400+ audience in Developer and IT Pro track!!

jQuery based PPT

Presentation: Click here

Demos:  Click here

I chose to prepare my presentation using jQuery itself, instead of power point, which would itself be a demo. The response from the audience was really encouragingSmile

Note: I used a lot of plugins in my demos but had to tweak them to meet my needs. So please don't use the versions which I am using in my demos as-is. Suggest you to download the original versions from the urls in the plugin files.

It was a great experience interacting with several enthusiastic developers and geeks. I've personally learnt a lot! Hope to meet you'll again. Please write to me in case of any doubts about using jQuery with ASP.NET

Happy coding Smile

When is AJAX an overkill for your ASP.NET-jQuery web applications? Part-2

In my previous article, I have discussed about few scenarios where AJAX can be an overkill for our web apps. I would like to add few more such scenarios in this post.

(4) Heavy dropdowns: 

A dropdown control enforces the user to select a value, preventing the entry of unwanted choices. This would make sense if a dropdown has limited options. But we tend to populate the dropdown with hundreds/thousands of options (probably this is the case with list of all cities in a country).

The scenario gets worse when we make an AJAX call to fill such huge dropdowns. There are many articles which show 'how to fill a dropdown using AJAX', but none of them stress on the limit of options. So, for a dropdown with 3000 options you are adding 3000 DOM elements, thereby degrading the performance of your page. Imagine 5 such dropdowns in a page!

Another scenario could be a row having a dropdown with 300 options, which repeats for ‘n’ times! These are unseen dangers which slow down your site.

Bottom line: Use dropdowns when you want to display limited(say ~50) elements. For anything more than this, use auto complete feature(You may choose between local/remote data based on number of records). The same rule holds good for cascading dropdowns. Keep your DOM as small as possible!

(5) Accordions: 

This is another beautiful UI technique almost similar to Tabs, the main difference being-tabs appear horizontally whereas accordions appear vertically. The problems faced in accordions are exactly the same ones which I have explained for tabs (please refer to my previous article).

Bottom line: If your page is too huge, do not fetch the entire DOM for building an accordion. On page load, build accordion structure and fetch the content of first pane only. On clicking the next header, remove markup from the previous pane and populate the current pane. This way, your page will always contain limited number of elements(though huge DOM manipulations can cause a little delay).

(6) Page load AJAX Calls/Multiple domains:

If you profile most of the web apps, they make a number of AJAX calls on page load for business functionality. e.g., If you are trying to fill 5 dropdowns on page load using AJAX calls, you are inviting performance problems.In most cases, we can get rid of such calls by injecting JavaScript objects into the page

Bottom line: If AJAX calls on page load are still unavoidable, instead of making multiple calls, make only a single call. In your web method, hit multiple controllers and fetch the desired response and club the responses using .NET’s Dictionary object. This way, you will reduce some network traffic.

You may also try to move some of your web services to different domains and access the data through JSONP.  The maximum number of parallel calls per domain in IE8/FF3 are 6. This means, by chance if you are making more than 6 AJAX calls, the remaining would be queued. By splitting your services across multiple domains, you can still make more than 6 calls in parallel!

On a closing note, I think I’m writing more of theoretical aspects without any code, but I don’t want to lose these experiences in the darkness of my memories. Following these simple guidelines helped me solve many performance bottlenecks in a large scale project. I feel this would be useful for developers at all levels while taking design decisions. Do let me know your views!

Follow me on twitter for live updates. Happy coding :)

When is AJAX an overkill for your ASP.NET-jQuery web applications? Part-1

AJAX libraries have simplified developer’s life by providing clean & easy-to-use API. Their usage is so simple that we developers over use it, without realizing the performance impacts. In this article, I would like to explain few scenarios in which AJAX can be an overkill for your web apps.

The motto is to help fellow developers take better design decisions at an early stage, rather than repenting and fine tuning later. Below are real time problems, faced in a large scale ASP.NET/jQuery AJAX based web app, which should be given a serious thought:

(1) AJAX based navigation: 

“Keep DOM manipulations to the minimum” is what every JavaScript library says, but over use of AJAX based navigation defeats this purpose and you may rethink the design, unless your client specifically wants it.

If you are wondering what AJAX based navigation means, check jqGrid demos site. There are no post backs at all even while navigation. Content pages are fetched via AJAX and injected into a parent page, with a huge DOM manipulation.

If the page is small with very less number of DOM elements, AJAX navigation is fine. As the number of elements increase in the page, injecting the page takes longer time and beyond a point, causes ‘stop running script’ error, as discussed in my previous article. Typically, business applications contain hundreds of controls in a page, causing severe performance bottlenecks.

If you see Facebook, the Home, Profile, Account etc links on the top do a full post back and fetch the page, while any other operation is an AJAX call, which is a cooler approach.

Bottom line: AJAX navigation has performance problems when pages are huge. But it can solve problems like maintaining state by storing data in DOM elements, reducing session variables and reducing load on the server. So weigh these choices before taking a call.

You may find the total number of elements in the page using the jQuery code, $(‘*’).length; So be cautious of this count while injecting a page. In a complex page like Yahoo.com, there are about 780 elements (each html tag corresponds to one element). Make sure your page is having not more than 1000 DOM elements. If the count is running into thousands, then split your pages.

(2) Client side templating:

If you liked asp.net repeater and are looking for client side templating, hold on! There is a difference between asp.net repeater and client side templates.

In the case of a repeater, processing takes place on the server and not much load is on the browser. However, in the case of templates, processing as well as injection is on the client. Imagine templating 100 rows, with each row containing 30 elements. You end up having 3000 elements which is alarming!

I can give you the example of twitter.com or facebook.com. Both have a ‘more’ sort of button at the bottom, which fetch more records. What happens if you want to see the posts of last ten days? You end up with thousands of DOM elements and your browser slows down.

Bottom line: In terms of performance, what is apparent to the developer is only the time taken to process the template. But what is hidden is, the time taken for clearing events, handling memory leaks, cleaning missing tags and injecting the template. All this happens in jQuery’s .html() method.

So, if you want to template huge data, make sure you are implementing pagination. Again, as in the above case, $(‘*’).length is the key.

(3) Tabs:

Thanks to this fancy UI technique, which gives a wizard sort of appearance to the content. If you are looking only at the fundo part of it, you are getting into problems! The scenario gets worst when you have AJAX tabs which fetch huge pages.

Let’s say each page has ~700 elements. So if you have 5 tabs, you are having ~3500 elements. Imagine having blur, click, live events for so many elements. It’s a complete mess! Also, you will be running into context related issues, since 2 tabs can have 2 different controls with the same ID. When you are on an active tab, the content of the rest of the tabs is only hidden, but not removed. So your app’s performance is bad yet again.

Bottom line: If you want to use tabs with optimal performance, make sure you are clearing the mark up of the tabs which are not active. At any point of time, make sure your $(‘*’).length is always less than 1000, for better results.

I think I have covered quite a lot. I’m still facing several bottlenecks in my beautiful project and trying to figure out the solutions with my architect. Will cover more scenarios in my next article.

Happy coding :)

Update: This second part of this article is continued in my next blog post.

Introduction to ASP.NET AJAX Library Beta - Microsoft Virtual Tech Days

Happy to say that I have presented today in Microsoft Virtual Tech Days(VTD) on ASP.NET AJAX Library(BETA)Smile

You can download the presentation here: http://www.slideshare.net/novogeek/introduction-to-asp-net-ajax-librarybeta

I have also uploaded working demos. You can find them here: http://labs.novogeek.com/VTD18Mar2010/index.htm

Regarding the demos, I have converted the aspx files to .htm files, so that you can simply save the demos from the browser. (Same code as shown in VTD).

Please let me know in case of any issues. Thank you once again for the warm response Smile

Handling AJAX exceptions of ASP.NET using jQuery

Exception handling is an important feature in any business application. In simple words, it is all about catching ugly errors thrown by server and displaying them in a user friendly manner to the end user. (Of course, logging exceptions/notifications etc may also be a part of exception handling. )

ASP.NET provides API for handling exceptions and displaying them in custom error pages. Custom error pages can also be defined for different HTTP error status codes, which provides good experience to end users in case of exceptions.

However, if you are using AJAX in your ASP.NET application(I’m using jQuery library for AJAX), you would not like to redirect users to a custom error page, as that kills the primary motto of AJAX. You would instead like to display error messages in the same page, as in facebook or twitter. So here is how this can be done using jQuery:

jQuery’s $.ajax method has a special function, $.ajaxSetup, where global settings can be made for handling AJAX requests. If you use this global function, you need not write error callbacks for each of your AJAX requests. All erroneous AJAX requests will be handled by the global error callback in $.ajaxSetup function. We can take advantage of this and write our exception handling wrapper.

$.ajaxSetup({
    error: function(XHR, errStatus, errorThrown) {
 
        if (XHR.status == 0) {
            alert('You are offline!\n Please check your network.');
        } else if (XHR.status == 404) {
            alert('Requested URL not found.');
        } else if (XHR.status == 500) {
            var errorMessage = 'Internal server error';
            try {//Error handling for POST calls
                var err = JSON.parse(XHR.responseText);
                errorMessage = err.Message;
            }
            catch (ex) {//Error handling for GET calls
                $('#divMaster').append('<div id="divErrorResponse" class="DisplayNone">' + XHR.responseText + '</div>');
                errorMessage = 'Page load error: ';
                errorMessage += $('#divErrorResponse').find('h2 i').html();
            }
            alert(errorMessage);
        } else if (errStatus == 'parsererror') {
            alert('Error.\nParsing JSON Request failed.');
        } else if (errStatus == 'timeout') {
            alert('Request timed out..Please try later');
        } else {
            alert('Unknown Error.\n' + XHR.responseText);
        }
    }
});

In the above code, we are checking for status codes(which are self explanatory) and handling error conditions based on these codes. Most of the times, the status code will be “500”, which says “Internal Server Error”. i.e., error in your server side code. Please refer this article from Encosia.com, which explains the core of what I am writing now.

Now, this “500 – Internal Server Error” may arise in both GET as well as POST requests. In POST request, if your web method throws error, it returns a JSON object, which you can parse as explained in the above link. But this does not work in case of GET requests.

Assume that you are loading a remote page into a master page using jQuery AJAX. If your “Page_Load” event throws exception, your response would be in HTML format (unlike the case of POST request, where the response is JSON object), which you cannot parse using JSON.parse or eval(). To differentiate between GET & POST responses, I’m simply using JSON.parse() in try() method. If it throws exception, it is surely due to a GET response, which is html. For better user experience, you may use jGrowl plugin for displaying error messages.

Conclusion: For exceptions in GET requests, you can query the resultant html using jQuery’s DOM selectors and display user friendly messages. For exceptions in POST responses, you can simply parse the resultant JSON object and display user friendly messages. If you feel there could be a better way of handling exceptions in GET requests, let me know.

Hope this article saves the time of folks who are facing similar problems. Happy coding :)

Using .NET’s Register Script methods with jQuery’s $(document).ready()

In ASP.NET web apps, most of the times we would need to call JavaScript functions in page_load event of code behind, for various valid reasons. In such scenarios, we simply use .NET’s Register Script methods for emitting JavaScript code, which is absolutely fine.

If you are using jQuery, you would write the logical flow of events to be executed in $(document).ready() function. However, if you are using Register script methods with jQuery, the output will not be as expected. I have faced this problem yesterday and want to share the reason and simple solution.

.NET framework provides two methods for emitting JavaScript to the client. They are:

  1. RegisterClientScriptBlock (Client-side script is emitted just after the <form runat=”server”> tag)
  2. RegisterStartupScript (Client-side script is emitted just before the </form> tag)

Note: These methods are now moved to ClientScriptManager class from Page class.

The below screenshot explains the difference clearly:

 

Okay. Now that the difference between the two is clear, let us go forward. Consider the below simple JS code:

function fnTestScript(msg) {
    console.log(msg);
}
 
$(document).ready(function() {
    fnTestScript('This is from document.ready');
});

We am defining a method fnTestScript(parameter) and calling it in jQuery’s ready() function. Now, in page_load event of server, let us call this method using Register script methods.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       'Using "RegisterClientScriptBlock" method to emit JS code.
       Dim strScript As New StringBuilder
       strScript.Append("<script language='javascript'>")
       strScript.Append("fnTestScript('This is from RegisterClientScriptBlock');")
       strScript.Append("</script>")
       ClientScript.RegisterClientScriptBlock(Me.GetType(), "TestScript", strScript.ToString())
 
       'Using "RegisterStartupScript" method to emit JS code.
       Dim strScript2 As New StringBuilder
       strScript2.Append("<script language='javascript'>")
       strScript2.Append("fnTestScript('This is from RegisterStartupScript');")
       strScript2.Append("</script>")
       ClientScript.RegisterStartupScript(Me.GetType(), "TestScript", strScript2.ToString())
   End Sub

Can you guess what the output will be? Here it is:

RegisterScriptsOrder

The reason is simple. .NET is injecting the script inline, into the DOM. So its functions are called before $(document).ready(), which fires after DOM is loaded. This means, your logical sequence of JavaScript calls has gone for a toss!

The solution is even more simple. Just add $(document).ready() in your function definition:

function fnTestScript(msg) {
    $(document).ready(function() {
        console.log(msg);
    });
}

Now your sequence of JavaScript calls will be like this:

RegisterScriptsOrder2

Q: Can you call $(document).ready() multiple times?
A: Yes!
This is another difference between this method and JavaScript’s window.onload, which is rarely mentioned in articles. The order of execution depends only on the order in the code.

Hope this article saves the time of others who face similar problem!

Passing JSON objects in .NET 3.5

In my previous post, I have explained how to pass complex types using jQuery and JayRock in .NET 2.0 framework. I was digging a bit into Dave’s example (using complex types to make calling services less complex) in .NET 3.5 framework, to find how easier JSON serilaization/deserialization can be made.

When a Web service class is decorated with “ScriptService” attribute, which is in the System.Web.Script.Services namespace in .NET 3.5, the web service returns data in JSON format [MSDN]. Whether the returned value is a string or an object, it will be in JSON format. So no need of writing chunks of code for serializing objects explicitly.

Therefore, all that we need to do is to simply decorate our web service class with “ScriptService” attribute and  return an object from the server. So, to create a JSON object like this:

{"d":{"FirstName":"Krishna","LastName":"Chaitanya","City":"Hyd","State"
:"Andhra","Country":"India"}}

We can simply return a person object like this:

<WebMethod()> _
    Public Function fnFetchDetailsClass() As Person
        Dim objPerson As New Person
        Try
            objPerson.FirstName = "Krishna"
            objPerson.LastName = "Chaitanya"
            objPerson.City = "Hyd"
            objPerson.State = "Andhra"
            objPerson.Country = "India"
        Catch ex As Exception
 
        End Try
        Return objPerson
    End Function

In some situations (like in client side templating), we might need to create custom, complex JSON objects on the fly. In such situations, we can make use of .NET’s “ListDictionary” and “ArrayList” classes.

The above example can be re-written using ListDictionary as:

<WebMethod()> _
Public Function fnFetchDetails() As ListDictionary
    Dim jsonObj As New ListDictionary
    Try
        jsonObj.Item("fname") = "Krishna"
        jsonObj.Item("lname") = "Chaitanya"
        jsonObj.Item("city") = "Hyd"
        jsonObj.Item("state") = "Andhra"
        jsonObj.Item("country") = "India"
        Return jsonObj
    Catch ex As Exception
        jsonObj.Item("Error") = "Error at server"
        Return jsonObj
    End Try
End Function

Thus, using JSON is made easier in .NET 3.5.

Here is a simple demo which makes things clear. (I have used jQuery for making AJAX calls.)

(Note: ListDictionary stores values in Name/Value pairs, which is useful in building JSON Object. Similarly, an ArrayList can be used to build JSON Arrays. Therefore, these two can be used instead of JsonObject and JsonArray classes of Jayrock in my post Converting ASP.NET DataTable to JSON using JayRock.)

Passing complex types to service calls using jQuery & JayRock

Scenario: Consider a web form having several fields, whose values are to be submitted to the server through an AJAX call.

ComplexTypes

This can be easily achieved using jQuery’s $.ajax(), passing all the form elements (like first name, last name, city etc) as parameters to the AJAX call.

However, in reality, most of our web forms contain large number of input fields and hence the $.ajax() method will be overloaded with several parameters both at the client side as well as at the server side. This is cumbersome and is not a good programming practice.

Solution: The best practice in this scenario is to build a Data Transfer Object (DTO) on the client side and pass it to the server. This is what Dave Ward explained in his excellent article - “Using complex types to make calling services less… complex”.

If you are working on NET 3.5 framework, Dave’s article is the solution. In .NET 3.5, the System.Web.Script.Services Namespace can be imported, which makes webservices accessible in JavaScript. Also, it has the ability to accept JSON object from client side code and parse it at the server.

However, in .NET 2.0 framework, JSON object cannot be parsed inherently and hence have to use libraries like JayRock. Here is how you can achieve the same using JayRock. The difference is in the way how you pass your “data” parameter in ajax call.

$('#btnSubmit').click(function() {
 
        //Build JSON object by looping through all text boxes
        var objDetails = {};
        $('input[type=text]').each(function() {
            objDetails[this.name] = this.value;
        });
        
        //Stringify the JSON object using the below method from json2.js
        var jsObj = JSON.stringify(objDetails);
 
        //jQuery ajax call. Note the data parameter, which is different from normal ajax parameter.
        $.ajax({
            type: "POST",
            url: "CTypesHandler.ashx",
            data: "{'id':'1','method':'fnAjaxMethod','params':{'obj':" + jsObj + "}}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: fnSuccess,
            error: function(xhr, status, errorThrown) {
                alert('Error' + errorThrown);
            }
        });
 
        function fnSuccess(response) {
            var obj = response.result.details;
            $('#divMessage').html(obj.FirstName + ' ' + obj.LastName + ' resides at ' + obj.City + ', ' + obj.State + ', ' + obj.Country);
        }
    });

Here is a simple demo. You can appreciate the demo if you can see how data is being requested and returned, in json format,  using firebug. (Few optimizations are yet to be done.)

Thanks to Praveen (my Technical Architect) for helping me with the concept. Thanks to Dave for replying to several of my queries.

Reading RSS feeds in ASP.NET

I was trying to build a nice home page for my site and was googling around for web 2.0 sites. Suddenly, I landed on SEOMoz.org and then on pageflakes.com. I then thought of building a mashup start page.So, tried to understand how Microsoft Popfly (an online mashup creator) works. Though its a excellent product, I thought of trying my own code.Tried for RSS readers in ASP.NET and landed on 4Guys4mRolla (very good article) and finally on Code Project .(It's a complete article. So no need to explain it here). It's all about an RSS toolkit which can be added to Visual StudioToolbox.This excellent ASP.NET custom control(which made life easy) can be downloaded from CodePlex.

Any one interested in learning about mashups, have a quick overview of these links without wasting much time!