« January 2008 | Main | April 2008 »

February 2008

February 25, 2008

How to make your web site work in all browsers

When we develop a web page with features which may not work in all browsers we need to ensure that the web page works with all browsers by programming the DOM elements. We do this by adding an event handler to an event exposed by a DOM element using $addhandler.

For those of you who are not familiar, a DOM element is a element of a DOM tree. A DOM tree is a hierarchical representation of all HTML elements which we place in the web page. An event handler helps to associate a function with an event. For example,

Object             Event Handler

Button              onclick
Text                onchange,  Onfocus

Note that this definition of event handler pertains to JavaScript.

Firstly, let us see how to attach code to Dom events using Javascript. If you use Javascript earlier, we will acquitted with the event model. We can program each DOM element of the DOM tree of a web page by associating events and code in event handlers as we will see below.

Let us take the example of a button. A HTML button element can raise a click event when it's clicked by the user. We will associate the function validcheck(), to the event handler onclick of the button object. The following code does this.

<input type=”button” name=cmdsubmit” onclick=” validcheck()>

A number of different types of event handlers can be triggered by different events.Common events that can trigger JavaScripts are mouse actions ,keyboard actions , actions on form fields.

This method of attaching code to DOM events will not work in all browsers. This is because, different browsers implement the DOM programming differently. So, your web page working on one browser may not work on other browsers.

The Microsoft Ajax Library provides to the problem by including an abstract API which abstracts the operations made on Dom elements. This API eliminates the need to know which functions are supported by the DOM implementation of a particular browser whether it is a Internet explorer, Firefox, Safari or Opera.

The abstraction API consists of two classes: Sys.UI.DomElement and Sys.UI.DomEvent.


Sys.UI.DomEvent Class
 

The Sys.UI.DomEvent Class is included in the Microsift Ajax library to provide cross browser compatibility to DOM events.  This class contains in the Namespace: Sys.UI. We use the DomEvent class to add, remove, modify, and handle client events.

Sys.UI.DomEvent addHandler Method
 

This method is a class of the Sys.UI.DomEvent and  enables us to add a DOM event handler to the DOM element.

Sys.UI.DomEvent.addHandler(element, eventName, handler);

Term              Definition

element          The element that exposes the event.
eventName     The name of the event.
handler           The client function that is called when the event occurs.

The class  Sys.UI.DomEvent addHandler can also be written as $addHandler.

Use the addHandler method to add a DOM event handler to the element that exposes the event. The eventName parameter should not include the "on" prefix. For example, specify "click" instead of "onclick". This method can be accessed through the $addHandler shortcut method.

$addHandler(element, eventName, handler);

The below example demonstrates how a blur event occurs when a text field on a form loses focus. This example also demonstrates the $addhandler will result in cross browser compatibility.

<form id="form1" runat="server">
<asp:ScriptManager ID="TheScriptManager" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function pageLoad() {
            var txtName = $get('txtName');                

            $addHandler(txtName,                              
               'blur', txtName_focus);                
        }

        function pageUnload() {
            $removeHandler($get('txtName'),                     
                'blur', txtName_focus);                
        }                                                         

        function txtName_focus(evt) { 
                      var count = $get("txtName").value.length;
                       $get("count").innerHTML="";
                       $get("count").innerHTML = count;

                                                                

        }

    </script>
    <span>Please type some text:</span>
    <input type="text" id="txtName" />                
    <span id="count">Number of characters</span>
    </form>

The above program displays the number of characters entered in the textbox when the textbox loses the focus.

February 22, 2008

Pros and cons of Programming models (AJAX)

Server Centric Programming Model

Compared to the client-centric programming model, the Server-centric programming model is easy to implement. All we need to know is develop the Asp.net application and then wrap certain areas of the page with UpdatePanels. By doing so, we will be using the minimal Ajax implementation.

Using UpdatePanels means posting the entire page to the server. Even when the required update to the web page is minimal, every asynchronous postback results in more server side processing. This results in downgraded performance.

From coding point of view, using UpdatePanel control results in elegant code. Sections of the page are wrapped by the UpdatePanels and all Ajax processing is taken up by the UpdatePanel control.

The server-centric approach denies granular level of control to the developer which is needed for sophisticated interactive web applications.

Client-Centric programming model

The Client-centric approach is adopted to build sophisticated interactive web applications. Such application scan be developed by using JavaScript, which means a high degree of expertise.

The Client-centric approach involves using ScriptManager control which enables calling of methods of a class bypassing the asp.net page life cycle. Which means, optimum usage of server resources.

Because we use client side DHTML controls, during a response, only required data from the server is rendered. This reduces the network traffic.

From a coding point of view, JavaScript code used for various features of a web page results in more maintenance.

The client-side approach has its own limitations as it cannot handle rich UI elements like menus, treeviews, grids, etc.




February 21, 2008

ASP.Net AJAX Programming models

When we set out to develop AJAX based web applications, we need to make a clear choice whether the application is going to be based on :

  • Server-centric programming model   
  • Client-centric programming model
  • Hybrid or a mixture of  Server-centric programming model and  Client-centric programming model

Many a times this decision is based on the existing applications which needs to be upgraded. Often factors like skills of a programmers available determine the choice of the programming model. Note that there are no clear guidelines which can help us to decide on the programming model. In this blog post we will see how a client-centric model and server-centric model is implemented.

Server-centric programming model

  • The application logic (written in VB.Net or C# )and user interface is hosted on the server.
  • This model is more like a minimal ajax implementation because we use only ScriptManager control, UpdatePanel control and almost no JavaScript code.
  • For existing applications to be upgraded to Ajax, we can retain the core Application logic and UI.
  • Flicker free increamental updates by using only the ScriptManager control, UpdatePanel control.

In the example below, we use the <UpdatePanel> tag and one of its child tags <ContentTemplate> to allow to refresh the label. By using the above tags, we are leveraging the power of Ajax to refresh the label without the need to postback the entire page.

The Server-Centric programming model involves adding the UpdatePanel control and placing all Asp.net controls within it. Note that in every Asp.net Ajax page, we need to place the one ScriptManger control.
The functionality of the below code is to increament the counter of the Label control when user clicks on the PartialButton.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode=Always ChildrenAsTriggers=true>
<ContentTemplate>
<asp:Button ID="PartialButton" runat="server" text="Partial Post Back" OnClick="InsideButton_OnClick" />
<br />
<br />
Counter (Partial):
<asp:Label ID="PartialLabel" Text="1" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
   
<script runat="server">

Sub InsideButton_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
  PartialLabel.Text += 1
End Sub
   
</script>

Client-centric programming model

The client-centric model is chosen when there is a compelling need to provide rich user experience in your application. In this programming model, both application logic and UI is implemented in the browser. The rich user experience is implemented using JavaScript, DHTML. Web service calls are used to retrieve the data from the server.

To learn more on creation of web services click here : Create a Web Service

So, the client-centric programming model requires a high level of Javascript expertise and atleast one team member should posses the knowledge of security issues of a web application.

In the example given below, we will add a new web service called myservice.asmx. this web service takes the string as input and returns the same. Note that in every client-centric application, a web service has to be used to retrieve the data from the server. As the given example is only for demonstration purposes, the input and returning value is the same and the example is straight forward. As the programs become sophisticated the input and return values will be varied.

In  the below code, we have used namespace System.Web.Script.Services namespace, which 
is part of the core ASP.NET AJAX framework.

Note that the two new attributes, [ScriptService],   [ScriptMethod]. The attribute [ScriptService] is the attribute of the class myservice and [ScriptMethod] is the attribute of the web method GetData(). These attributes are parsed by the ASP.NET AJAX framework and is used to determine what portions of the service are exposed in the JavaScript proxies.

Next we add a new web form called client-centricexample.aspx. the first step is to include ScriptManager control. Next, we declare a service reference to the local web service myService.asmx.  In the web form, we use two regular Html elements two textbox controls and one button. Whenever user clicks on the button in the page, the GetResult() javascript function is called. In this function we call the web service to display the text enetered by the user in another textbox control. In the statement, myService.GetData(document.form1.Text1.value,onComplete); 

The first  parameter is the data entered in the first textbox control and the second parameter is the name

of the callback function onComplete that is  called when the method returns succesfully. When the call return is completed, the changes to be made in the user interface is mentioned here.

In the statement document.form1.Text2.value = result; 

the control text2 is assigned the result of the web service. So, whenever user click the button, the textbox control is updated dynamically.

WebService/WebMethod code:

<%@ WebService Language="C#" Class="myService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myService : System.Web.Services.WebService
{

    [ScriptMethod]
    [WebMethod]

public string GetData(string myString)
    {
        return myString;
    }
}

HTML code:

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="myService.asmx" />
    </Services>
    </asp:ScriptManager>

<input type=text id=Text1 name=Text1 /> 
<input type=text id=Text2 name=Text2 />    
<input type=button id="btnGet" value="Getdata" onclick="GetResult();" />

JavaScript code:

<script type="text/javascript">

function GetResult()
{
      myService.GetData(document.form1.Text1.value,onComplete);
}

function onComplete(result)
{
    document.form1.Text2.value = result;
}

</script>
</form>

February 20, 2008

Free software from Microsoft !

Back in 1995-97 i was indirectly involved with a product which was a successor to Clipper. During a freewheeling discussion session, i suggested that the product competing with VB and Delphi, be given free of cost to all universities. The idea was not accepted. Today i feel somewhat vindicated. When you cannot sell something to someone, you simply give it away, provided the manufacturing (here copying) costs are negligible.

Microsoft today announced, Free software tools to Universities and schools in an effort to kick start innovation based on its windows platform and to promote more usage. All universities are pitching in for Linux and IBM's eclipse as they are open source and free. This move is seen as a strategy to keep open source at bay.

This offer will include Visual Studio the suite - which includes VB, ASP, C# and C++. With this students of colleges and Universities can learn all the tools at college level and be better prepared when they step out for entering the Job market.

Microsoft has sought to plug one easy entry point for free open source software. While, this offer does not include - open source it includes only free tools.

Twitter Updates

    follow me on Twitter
    AddThis Social Bookmark Button
    Blog powered by TypePad
    My Photo