Thursday, August 26, 2010

Move viewstate to bottom of the page

                                     Recently i have got a problem with in my application..That  is index page having 44,0000(nearly 9 pages ) characters length of viewstate .Hmmm.....I would like to move all the .net stuff __VIEWSTATE to the bottom of the page.

      

                                        The reason is That  page would be much more search engine friendly and it would render faster in the browser.So i have implemented fuctionality to render the viewstate on bottom of the page .I have overrided the "RenderControl" event in master page.here is the code



///

/// Code for moving the Viewstate to bottom of the page

///


///


public override void RenderControl(HtmlTextWriter writer)

{

using (System.IO.StringWriter stringWriter = new System.IO.StringWriter())

{

using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))

{

base.Render(htmlWriter);

string html = stringWriter.ToString();

int beginPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"")

{

int endPoint = html.IndexOf("/&gt;", beginPoint) + 2;

string viewstateInput = html.Substring(beginPoint, endPoint - beginPoint);

html = html.Remove(beginPoint, endPoint - beginPoint);

int formEndStart = html.IndexOf("") - 1;

if (formEndStart &gt;= 0)

{

html = html.Insert(formEndStart, viewstateInput);

}

}



writer.Write(html);

}

}



}





Copy this code and paste into master page .run the application .Now you can see _viewstate renders in bottom of the page .

Thursday, August 5, 2010

Position update progress at mouse click in asp.net which support all browsers.

I have got a new requirement .That is position the update progress control to display on the screen where the user clicks with the mouse. I have goggled and get some code which is not working in different browsers .So I have implemented it to work with all browsers.


Copy the below code and paste in new .js file  name it as "AjaxProgressHandler.js"

Clickhere to download the sample project.AjaxCustomProgress sample project 
 
function close_popup(pop_id)
 {
    var popup = pop_id;
    document.getElementById(popup).style.display = 'none';
}
function openSpecXY(pop_id, posX, posY)
 {
    var popup = pop_id;
    document.getElementById(popup).style.left = posX + 'px';
    document.getElementById(popup).style.top = posY + 'px';
    document.getElementById(popup).style.display = 'block';
}

function showhide(id)
 {
    if (document.getElementById) {
        obj = document.getElementById(id);
        if (obj.style.display == "none") {
            obj.style.display = "";
        }
        else {
            obj.style.display = "none";
        }
    }
}
// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all ? true : false
// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)
// Set-up to use getMouseXY function onMouseMove
document.onclick = getMouseXY;
// Temporary variables to hold mouse x-y pos.s
var mousePosX = 0
var mousePosY = 0
var lastPopUp;
// Main function to retrieve mouse x-y pos.s

function getMouseXY(e) {
    try {
        if (IE) { // grab the x-y pos.s if browser is IE
            mousePosX = event.clientX + getScrollXY()[0]
            mousePosY = event.clientY + getScrollXY()[1]
        } else {  // grab the x-y pos.s if browser is NS
            mousePosX = e.pageX
            mousePosY = e.pageY
        }
        // catch possible negative values in NS4
        if (mousePosX < 0) { mousePosX = 0 }
        if (mousePosY < 0) { mousePosY = 0 }
    } catch (e) {
    }
}
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}
function open_popupRelative(popUpDivID, divApproxWidth, divApproxHeight, closeLastPopUp) {
    //alert(getScrollXY()[1]);alert("open_popupRelative is" + popUpDivID);
    if (!divApproxWidth) {
        divApproxWidth = 0;
    }
    if (!divApproxHeight) {
        divApproxHeight = 0;
    }
    if (closeLastPopUp) {
        if (lastPopUp) {
            //alert(lastPopUp);
            close_popup(lastPopUp);
        }
    }
    var popup = popUpDivID;
    if (popup != "flexInner" && popup != "productlist") {
        lastPopUp = popup;
    }
    var divElement = document.getElementById(popup);
    divElement.style.left = mousePosX - divApproxWidth + 'px';
    divElement.style.top = mousePosY - divApproxHeight + 'px';
    //alert('x:'+mousePosX+'::y:'+mousePosY+'divX:'+divApproxWidth+'divY:'+divApproxHeight);
    divElement.style.display = 'block';
}
if (document.images) {
    img1 = new Image();
    img2 = new Image();
    img1.src = "4-0.gif";
    img2.src = "4-0.gif";
}
function cancelMyAjaxPostBack() {
    try {
        Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
    } catch (e) { }
}
function pageLoad() {
    Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(showMyLoading);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(stopMyLoading);
}
function showMyLoading(sender, args) {
    open_popupRelative('ajax_req_process_div', 0, 0, 1);
}
function stopMyLoading(sender, args) {
    close_popup('ajax_req_process_div');
    if (args.get_error() != undefined) {
        args.set_errorHandled(true);
    }
}







Execute the application .have a fun
 


Tuesday, August 3, 2010

Tips to improve Performance of Web Application

Hi all ,

From last few days i am working on improving the performance of application .I have worked with yslow and fiddler performance analyzer tools.Some of Important points i have collected .It will use full for every developer .


1. Make fewer HTTP requests

Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads. Some ways to reduce the number of components include: combine files, combine multiple scripts into one script, combine multiple CSS files into one style sheet, and use CSS Sprites and image maps.

2. Content Delivery Network (CDN)

User proximity to web servers impacts response times. Deploying content across multiple geographically dispersed servers helps users perceive that pages are loading faster.

3. Add Expires headers

Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.

4. Compress components with gzip

Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.

5. Grade A on Put CSS at top

Moving style sheets to the document HEAD element helps pages appear to load quicker since this allows pages to render progressively.

6. Put JavaScript at bottom

JavaScript scripts block parallel downloads; that is, when a script is downloading, the browser will not start any other downloads. To help the page load faster, move scripts to the bottom of the page if they are deferrable.
7. Avoid CSS expressions

CSS expressions (supported in IE beginning with Version 5) are a powerful, and dangerous, way to dynamically set CSS properties. These expressions are evaluated frequently: when the page is rendered and resized, when the page is scrolled, and even when the user moves the mouse over the page. These frequent evaluations degrade the user experience.

8. Make JavaScript and CSS external

Using external JavaScript and CSS files generally produces faster pages because the files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded each time the HTML document is requested. This reduces the number of HTTP requests but increases the HTML document size. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the HTML document size is reduced without increasing the number of HTTP requests.

9. Reduce DNS lookups

The Domain Name System (DNS) maps hostnames to IP addresses, just like phonebooks map people's names to their phone numbers. When you type URL www.yahoo.com into the browser, the browser contacts a DNS resolver that returns the server's IP address. DNS has a cost; typically it takes 20 to 120 milliseconds for it to look up the IP address for a hostname. The browser cannot download anything from the host until the lookup completes.

10. Minify JavaScript and CSS

Minification removes unnecessary characters from a file to reduce its size, thereby improving load times. When a file is minified, comments and unneeded white space characters (space, newline, and tab) are removed. This improves response time since the size of the download files is reduced.

11. Avoid URL redirects

URL redirects are made using HTTP status codes 301 and 302. They tell the browser to go to another location. Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.

12.Remove duplicate JavaScript and CSS

Duplicate JavaScript and CSS files hurt performance by creating unnecessary HTTP requests (IE only) and wasted JavaScript execution (IE and Firefox). In IE, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page. In both IE and Firefox, duplicate JavaScript scripts cause wasted time evaluating the same scripts more than once. This redundant script execution happens regardless of whether the script is cacheable.

12. Configure entity tags (ETags)

Entity tags (ETags) are a mechanism web servers and the browser use to determine whether a component in the browser's cache matches one on the origin server. Since ETags are typically constructed using attributes that make them unique to a specific server hosting a site, the tags will not match when a browser gets the original component from one server and later tries to validate that component on a different server.

13. Make AJAX cacheable

One of AJAX's benefits is it provides instantaneous feedback to the user because it requests information asynchronously from the backend web server. However, using AJAX does not guarantee the user will not wait for the asynchronous JavaScript and XML responses to return. Optimizing AJAX responses is important to improve performance, and making the responses cacheable is the best way to optimize them.

14. GET for AJAX requests

When using the XMLHttpRequest object, the browser implements POST in two steps: (1) send the headers, and (2) send the data. It is better to use GET instead of POST since GET sends the headers and the data together (unless there are many cookies). IE's maximum URL length is 2 KB, so if you are sending more than this amount of data you may not be able to use GET.
15. Reduce the number of DOM elements



A complex page means more bytes to download, and it also means slower DOM access in JavaScript. Reduce the number of DOM elements on the page to improve performance.

16. Avoid HTTP 404 (Not Found) error

Making an HTTP request and receiving a 404 (Not Found) error is expensive and degrades the user experience. Some sites have helpful 404 messages (for example, "Did you mean ...?"), which may assist the user, but server resources are still wasted.

17. Reduce cookie size

HTTP cookies are used for authentication, personalization, and other purposes. Cookie information is exchanged in the HTTP headers between web servers and the browser, so keeping the cookie size small minimizes the impact on response time.

18. Use cookie-free domains

When the browser requests a static image and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic. To workaround this problem, make sure that static components are requested with cookie-free requests by creating a subdomain and hosting them there.




19. Avoid AlphaImageLoader filter

The IE-proprietary AlphaImageLoader filter attempts to fix a problem with semi-transparent true color PNG files in IE versions less than Version 7. However, this filter blocks rendering and freezes the browser while the image is being downloaded. Additionally, it increases memory consumption. The problem is further multiplied because it is applied per element, not per image.

20. Do not scale images in HTML

Web page designers sometimes set image dimensions by using the width and height attributes of the HTML image element. Avoid doing this since it can result in images being larger than needed. For example, if your page requires image myimg.jpg which has dimensions 240x720 but displays it with dimensions 120x360 using the width and height attributes, then the browser will download an image that is larger than necessary.

21. Make favicon small and cacheable

A favicon is an icon associated with a web page; this icon resides in the favicon.ico file in the server's root. Since the browser requests this file, it needs to be present; if it is missing, the browser returns a 404 error (see "Avoid HTTP 404 (Not Found) error" above). Since favicon.ico resides in the server's root, each time the browser requests this file, the cookies for the server's root are sent. Making the favicon small and reducing the cookie size for the server's root cookies improves performance for retrieving the favicon. Making favicon.ico cacheable avoids frequent requests for it.