Auto Refreshing Pages-Server side vs AJAX and AJAX server Side vs Client Side

Posted: April 18, 2007 in Uncategorized
Auto Refresh:-Server Side:-With Reposting:-Whenever you are going to display a stock reporting kind of solution with real data changes in a web application. You might face with 2 primitive issues those are whether to go with a PULL model or to go for a PUSH model. Further to that you also need to consider if any Hybrid approach are possible. The same apply to any real-time collaborative systems and with the stateless HTTP coming into the picture the complexity increases .With a Desktop application you might consider Callback and Pub-Sub patterns together with some sort of Auto-notification [like a sql dependency] to provide similar experience. [Although the Sql dependency is less scalable if used improperly and I ll discuss that in another post].
In this post we ll consider simple PULL model without the SereverFarm Scenario and its not for a real time production scenario for high traffic where you need to consider little more to provide some set of braodcasting or multicasting to  a set of server but this is not a quick solution which can work in production if your traffic and polling interval  managed properly.
Now coming to the simple process of how the activities carry in current applications without Ajax is as follows:-
            1. You post to a hidden frame, Remotescript or script call to get the data asynchronously
            2. You hook Ajax frameworks to get the data
            3. You simply use the serevrside approach with page refresh.
            Coming to the server side approach what you can do is Autopostback the page every few seconds.
Here is a demo script I used to populate the data and the autorefresh:-
DB script to populate a table and generate few random col:-
select Employeeid,lastname,firstname,birthdate,address,city into emp from northwind.dbo.employees
altertable emp add  sal int
CREATEFUNCTION dbo.ISOdd (@id int)
declare @result bit
set @result=1
                                    set @result=0
return @result
select dbo.isodd(5)
update emp set sal=case(dbo.isodd(employeeid))
                                    when  0 then employeeid*1000
                                    when 1 then  employeeid*2000
update Emp set sal=sal-50 where employeeid=1
droptable emp
Now you can do something like:-
protectedvoid Page_Load(object sender, EventArgs e)
       privatevoid getdata()
            SqlConnection con = newSqlConnection(“connstr here”);
            SqlDataAdapter ad = newSqlDataAdapter(“SELECT [employeeid],[firstname],[sal] FROM [emp]”, con);
            DataSet ds = newDataSet();
            GridView1.DataSource = ds.Tables[0].DefaultView;
And something like the following in the Aspx:-
      <bodystyle=”font-size: 12pt”>
            function reload() {
            window.setTimeout( “reload()”, 2000 );
You can also do something like
URL:- is ur page url
Here by I am refreshing the page every 2 seconds which might cause a network congestion and you need to set a appropriate interval for your production application.In fact there is a lot you need to consider while providing a real time webbased solution.I ll try to go one afetr other issues and this is first of the post to start with .So now that we saw how we can provide a serevr side solution Next we ll see how we cna hook up a AJAX based solution with Async postback and Updatepanel with timer as well as Client Side frx of ajax. 

Atlas Update Panel and Timer Server Side:-

Here I am loading the data in pageload() infact thru a Webservice Call .I will also discuss how you can expose this webservice from Client script as well as what does the Atlas Webservice offers .If you wants the Websrevice needed to supprot the JSON format you need to provide the Extension to the Web.config for the AJAX hookup as well as you need to decorate it with the ScriptService attaributes and Scrpitmethod when necessary for example returning the XML reponse format.

 Do remember that these extra complexities are necessary only when you are going for a true client side approach to avind the Update panel approach.For the Update panel approach all these are not required and you can hookup a normal Asmx.  

Update Panel Approach:-

protectedvoid Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
        privatevoid getdata()
            proxy.Service1 proxy = newService1();
            proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            DataSet ds= (DataSet)proxy.GetEmployeedata();
            GridView1.DataSource = ds.Tables[0].DefaultView;
        protectedvoid Timer1_Tick(object sender, EventArgs e)


    <form id=”form1″ runat=”server”>
   <asp:ScriptManager ID=”ScriptManager1″ runat=”server” >
    <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional” >
    <asp:GridView ID=”GridView1″ ……..




  using System.Web.Script.Services;

  namespace GetEmp
[WebService(Namespace = ““)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service1 : System.Web.Services.WebService


        public DataSet  GetEmployeedata()
SqlConnection con = new SqlConnection(“conn str here”);
SqlDataAdapter ad = new SqlDataAdapter(“SELECT [employeeid], [lastname], [firstname], [birthdate], [address], [sal], [city] FROM [emp]”, con);
DataSet ds = new DataSet();
return ds;

  if you see the above code I have set the upadetpanel mode to conditional and I am jeust resetting the DataSource of the gridview and rebidning it in the timer_click.There are other mode also but i am preferring the programmatical mode for this post and ill cover those in anotehr post if needed.

  As I told before if you want to expose your webservice to JSON format that you can see while you apend a /js to ur asmx path you need to provide the Ajax extension to the Web.config if you are hosting the webservice outside your app.Further to that you need to import the Script.Services and decorate the service with ScriptService.Also you cann’t have the Dataset returns directly you can return datatable and also return XML from the Webmthod call using the ScriptMethod attaribute an dpassing the responseformat as XML.

  Here is the Client Mode Operation:-

  Here we ll call the websrvice to  get the data and display in Div all from Client script:-

The webservice remains the same with the addition of the scriptservice and script method attribute[uncomment the script svc call etc].

  Now that you have the webService ready.[Donot forget to add the extensions to the web.config to make it JSON aware].To make that the simpler approach would be see the web,config for a Asp.NEt Ajax appliucation and copy the WebExtension,Script extension realtaded configuratiosn and Http handlers to the ASMX if you are enabling an existing Asmx Json Aware.That is if you browse the Asmxpath/js you ll get the JSON call format.

  Here is the aspx to call the webservice and display the data all from client side:-

<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” >
<asp:ScriptReference Path=”CallWebServiceMethods.js” />
<asp:ServiceReference Path=”WebService.asmx” />[note i ve in same app u can provide ur url]
<input id=”Button1″ type=”button” value=”button”  onclick=”ClientGetEmployee()” />
<div id=”div1″  >

  Here is the .JS:-

function ClientGetEmployee()
function SucceededCallback(result, eventArgs)
// Page element to display feedback.
var RsltElem = document.getElementById(“div1”);
RsltElem.innerHTML = result.xml;

function FailedCallback(error)
// Display the error.
var RsltElem =
RsltElem.innerHTML =
“Service Error: ” + error.get_message();


 If you see rather then hooking of  arealtime collaboration here I am mere providing how to call webservice from client script an display the XML data in  a DIV.Since you ll not  get the Gridview datasource set to the result automagically.
That is in Succceedcallback:-
var RsltElem = document.getElementById(“gridview1”);
RsltElem.innerHTML = result.;
throws you error.You can hook up your own list and display the result from client side itself but that needed little more Javascript programming to parse the Dom and create your output.

  One last tip:-if you want to debug the java script  then enable script debugging in IE and from tools-customize from the debug commnad add the script explore and add the break point to the java script to step thru it.

This is enough for one post and I ll cover lot of the topics in next posts


  1. says:

    Your space is very nice. Congratulations !Best wishes from Salvador.

  2. ujval says:

    vista guide

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s