Tanzim Saqib on .NET discovery

January 11, 2008

ASP.NET AJAX Best Practices: Problem with switch

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:26 am

Unlike .NET languages or any other compiler languages, JavaScript interpreter can not optimize switch block. Especially when switch statement is used with different types of data, it’s a heavy operation for the browser due to conversion operations occur in consequences, it’s an elegant way of decision branching though.

January 10, 2008

ASP.NET AJAX Best Practices: Avoid using Array.length in a loop

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 1:10 pm

In one of my earlier posts, I talked about DOM element accessing in a loop but forgot to talk about a very common, yet performance issue in AJAX. We often use code like the following:

var items = []; // Suppose a very long array
for(var i=0; i<items.length; ++i)
    ; // Some actions

It can be a severe performance issue if the array is so large. JavaScript is an interpreted language, so when interpreter executes code line by line, every time it checks the condition inside the loop, you end up accessing the length property every time. Where it is applicable, if the contents of the array does not need to be changed during the loop’s execution, there is no necessity to access the length property every time. Take out the length in a variable and use in every iteration:

var items = []; // Suppose a very long array
var count = items.length;
for(var i=0; i<count; ++i)
    ; // Some actions

January 8, 2008

Make web.config work in Volta

Filed under: Volta — tanzimsaqib @ 9:24 pm

Ever wondered how to make web.config work in Volta first CTP release? Simply add a web.config file and add content to it? Unfortunately this is not the case in Volta at least in the first CTP. Five steps to get it done:

  1. Add a web.config file
  2. Add content to simply by copying from other web.config file
  3. Right click on web.config from the Solution Explorer and then Properties
  4. Choose Build Action to Embedded Resource
  5. In your Volta Page Designer CS file, add the following line of code:
[assembly: VoltaFile("web.config")]

 

ASP.NET AJAX Best Practices: Avoid getters, setters

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 8:08 pm

Make minimum use of setters and getters if possible. Such accessors look like .NET like kind of beautiful properties, but these create new more scopes for JavaScript interpreter to deal with. If applicable, try directly setting/getting the private variable itself rather implementing methods for getters, setters.

January 6, 2008

ASP.NET AJAX Best Practices: Avoid using your own method while there is one

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 2:11 pm

Avoid implementing your own getElementById method that will cause script to DOM marshalling overhead. Each time you traverse the DOM and look for certain HTML element requires the JavaScript interpreter to marshalling script to DOM. It’s always better to use getElementById of document object. So, before you write a function, make sure similar functionality can be achieved from some other built-in functions.

January 5, 2008

ASP.NET AJAX Best Practices: Careful with DOM element concatenation

Filed under: AJAX, JavaScript, Performance — tanzimsaqib @ 11:14 am

It’s a very common bad practice. We often iterate through array, build HTML contents and keep on concatenating into certain DOM element. Every time you execute the block of code under the loop, you create the HTML markups, discover a div, access the innerHTML of a div, and for += operator you again discover the same div, access its innerHTML and concatenate it before assigning.

function pageLoad()
{
    var links = ["microsoft.com", "tanzimsaqib.com", "asp.net"];

    $get('divContent').innerHTML = 'The following are my favorite sites:'

    for(var i=0; i<links.length; ++i)
        $get('divContent').innerHTML += '<a href="http://www.' + links[i] + '">http://www.' + links[i] + '</a><br />';
}  

However, as you know accessing DOM element is one the costliest operation in JavaScript. So, it’s wise to concatenate all HTML contents in a string and finally assign to the DOM element. That saves a lot of hard work for the browser.

function pageLoad()
{
    var links = ["microsoft.com", "tanzimsaqib.com", "asp.net"];
    var content = 'The following are my favorite sites:'

    for(var i=0; i<links.length; ++i)
        content += '<a href="http://www.' + links[i] + '">http://www.' + links[i] + '</a><br />';

    $get('divContent').innerHTML = content;
}  

January 4, 2008

ASP.NET AJAX Best Practices: Use more "var"

Filed under: AJAX, JavaScript — tanzimsaqib @ 11:03 am

Less use of “var” can result into wrong calculation as well as mistake in logic control. And also JavaScript interpreter finds it hard to determine the scope of the variable if var is not used. Consider the following simple JavaScript code:

function pageLoad()
{
    i = 10;
    loop();
    alert(i);   // here, i = 100
}

function loop()
{
    for(i=0; i<100; ++i)
    {
        // Some actions
    }
}

Here you see, the loop uses the variable i used before in pageLoad. So, it brings a wrong result. Unlike .NET code, in JavaScript variables can go along with the method calls. So, better not confuse the interpreter by using more “var” in your code:

function pageLoad()
{
    var i = 10;
    loop();
    alert(i);   // here, i = 10
}

function loop()
{
    for(var i=0; i<100; ++i)
    {
        // Some actions
    }
}

January 3, 2008

Make HTML controls discoverable in Volta Control

Filed under: .NET, C#, Volta — tanzimsaqib @ 2:12 pm

 

When a Volta control is rendered, the ID attribute of the generated HTML is changed to something like _vcId_1_DivName which is inconvenient to find from code. But the ID attribute stays the same in case of Volta Page, so it is discoverable by ID like this:

Div divContent = Document.GetById<Div>("divContent");

However, if you add HTML controls to the control like the following, the ID is not changed during the rendering:

public VoltaControl1() : base("VoltaControl1.html")
{
    InitializeComponent();

    Button btnClick = new Button();
    btnClick.InnerText = "Click!";
    btnClick.Id = "btnClick";
    this.Add(btnClick);
}

If you don’t prefer this way and seriously want to write your own HTML in the control’s html page, you might find the following snippet useful. But, remember in this case you will use name attribute of the html element instead of ID.

// Usage: var element = GetElementByName(Document.GetElementsByTagName("div"), "divWidget");
private HtmlElement GetElementByName(HtmlElementCollection elements, string name)
{
    foreach (var element in elements)
    {
        DomAttribute nameAttribute = element.Attributes.GetNamedItem("name");
        if (nameAttribute != null)
            if (nameAttribute.Value == name)
                return element;
    }

    return null;
}

January 2, 2008

Making cross domain AJAX call using Volta

Filed under: .NET, C#, Volta — tanzimsaqib @ 12:56 pm

 

Making a cross domain AJAX call in Volta is piece of cake. Volta compiler generates necessary client codes to make it work. Here is a snippet that can make an AJAX call to some Url and fetch data:

public void DownloadPhotos()
{
    IHttpRequest request = HttpRequestFactory.Create();
    request.AsyncSend("POST", URL, string.Empty,
        delegate(string response)
        {
            OnPhotosLoaded(new PhotosLoadedEventArgs(response));
        });
}

Both IHttpRequest and HttpRequestFactory classes can be found in the Microsoft.LiveLabs.Volta.MultiTier namespace. AsyncSend method performs the asynchronous call and calls back the delegate defined where OnPhotosLoaded event is fired to notify the subscriber of this event that the data has just arrived.

Namespace Alias Qualifier – to get rid of crazy coding

Filed under: C# — tanzimsaqib @ 1:00 am

Let us say somebody in your company loves crazy coding and really do not bother about his/her codes affect others. (S)He put class name System and a constant Console and now wondering how come a simple Console.WriteLine does not compile:

class System
{
    int Console = 10;

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!"); // Compile time error
        System.Console.WriteLine("Hello World!"); // Compile time error
    }
}

Making use of global::System.Console must solve your problem:

class System
{
    int Console = 10;

    static void Main(string[] args)
    {
        global::System.Console.WriteLine("Hello World!");
        global::System.Console.WriteLine("Hello World!");
    }
}

However, ever thought of a scenario where there can be same class name under two different namespaces? Here comes the role of Namespace Alias Qualifier. In namespace declaration by “using”, aliases can be assigned to namespaces so that they might be useful in later part of the code as shorthand and most importantly will solve the problem of ambiguity:

using sys = System;
using mine = MyProject.Process;
...
...
sys.Console.WriteLine(mine.Console["width"]);
« Newer PostsOlder Posts »

Blog at WordPress.com.