拾荒时代------技术,艺术!

.NET/Ajax/C#/Web2.0精品技术文章网摘。

导航

How to Show Messenger-Like Popups Using AJAX

Introduction

You have already been using MSN Messenger to chat with friends, relatives, businesses, and much more. When someone signs in, a small popup window shows up on the right-bottom side of the screen, informing you that your friend X has just signed in. It is a nice way for MSN messenger to notify you about changes in the contacts online.

What about using the same technique on an ASP.NET page? In other words, suppose that you are monitoring a database table, where users place their orders online and you would like to be notified whenever a new request comes in to the database table.

In this article we will show you how to implement a messenger-like popup window whenever a new record is added to a database table. The popup will show on the bottom-right side of the screen on top of an ASP.NET page notifying you that a new record has been added. We will use ASP.NET 2.0 AJAX 1.0 Extensions and mainly the client library accompanies by the AJAX extensions.

Database Sample

In this article we will use a database table called MyInbox simulating your inbox on a mail server. This table contains EmailFrom, Body, and Date columns. These columns shall resemble an email that you have received in your inbox as an example.

Constructing the JavaScript

We will create a new AJAX enabled website, then open the Default.aspx page in the HTML source, and start adding our JavaScript that will handle showing and hiding the popup and querying the database to see if there are any new emails inserted.

First of all, we define a global variable.

Listing 1

var numberOfEmails_original= 0;

The numberOfEmails_original variable shall hold the number of emails present in the database table when the page first loads. We will see later on when and how this variable is used. Then, we attach an event handler for the Application’s Init method.

Listing 2

var app = Sys.Application; app.add_init(applicationInitHandler); function applicationInitHandler(sender, args)  {   InboxService.GetLatestNumberOfEmails(OnCurrentNumberOfEmailsReady); }

What we are doing at the initialization of the Application is do a script service call to execute the GetLatestNumberOFEmails method located at the AJAX Service that we will discuss later on in the article. We are specifying the success callback function to run when a response is sent back from the server.

The idea in here is that, the first time the page loads, we get the current number of emails from the server and store it in the numberOfEmails_original as shown in the OnCurrentNumberOfEmailReady callback function below.

Listing 3

function OnCurrentNumberOfEmailsReady(result, userContext, methodName)  {   numberOfEmails_original= result;   // Start Checking   StartChecking(); }

As you can see, we set the result returned by the AJAX Service to the local variable numberOfEmails_original and then call a method named StartChecking().

Now that the original number of emails currently stored in the database is known, we can start checking from now on to any new email that is added to the database table.

The StartChecking method is as follows:

Listing 4

function StartChecking()  {   InboxService.GetLatestNumberOfEmails(OnLastestNumberOfEmailsReady); }

The StartChecking function does nothing but a call to the same AJAX service method, InboxService.GetLastestNumberOfEmails. However, this time, we are passing in another success callback function which is the OnLatestNumberOfEmailsReady. The success callback function is shown below.

Listing 5

function OnLastestNumberOfEmailsReady(result, userContext, methodName) {   var numberOfEmails_new = result;   if (numberOfEmails_new > numberOfEmails_original)   {     ShowPopup();     $get("modalBody").innerHTML = numberOfEmails_new - numberOfEmails_original;     // Update the count here     numberOfEmails_original = numberOfEmails_new;   }   // Start checking again   window.setTimeout(StartChecking, 10000); }

The method starts by placing the result from the AJAX service into a local variable called numberOfEmails_new. This variable now holds the latest number of emails located in the database table.

Then the code checks if the number of emails currently stored in the database is greater than the number of emails originally the page has requested from the database. This means that new emails we have were inserted into the database since the last time the code queried the database.

If this is true, then a call to ShowPopup() function is done that is responsible for showing a popup the MSN Messenger way. Then the number of new emails is filled in the body of the popup window informing the user on the number of new emails received, and finally, the code sets the current number of emails in the database table to the numberOfEmails_original variable. This way the numberOfEmails_original variable is synchronized with the emails’ number in the database. Refreshing the value of this variable is very important for later checking on the client side.

The last statement in this method is a call for the StartChecking method encapsulated in a window.setTimeout function call. As you can see here, the same logic will run according to the milliseconds placed in the setTimeout function. So as long as the page is running, the checking will continue and every time a new email is added to the database table, a pop up window is shown on the screen to notify the user about the new emails that have been added.

The figure below shows the page when it first loads.

Figure 1: Page when first loaded

When a new record is inserted into the database while the above page is opened, you will notice a small messenger like pop up window is shown on the bottom-right side of the page as in Figure 2.


Figure 2

You can clearly see a popup window in the figure above that shows when the page checks the database table on the server and finds that the number of emails currently on the database is greater than the number of emails stored on the client side.

The last two functions to discuss are the ShowPopup and HidePopup functions that are used as utility methods to show and hide the popup window on the page.


Building the AJAX Service

In this final section of the article we will show you the simple AJAX Service that we have created that the client code will use to access the database and retrieve information about the number of records stored in the database.

Listing 6

[ScriptService] public class InboxService: System.Web.Services.WebService {   [WebMethod]   public int GetLatestNumberOfEmails()   {     int numberOfEmails = 0;       using(SqlConnection conn = new SqlConnection       (WebConfigurationManager.ConnectionStrings[0].ConnectionString))     {       using(SqlCommand cmd = new SqlCommand("GetLatestNumberOfEmails", conn))       {         cmd.CommandType = CommandType.StoredProcedure;           conn.Open();         numberOfEmails = (int)cmd.ExecuteScalar();       }     }       return numberOfEmails;   } }

The first thing to notice is the ScriptService attribute located at top of the service name. This is very important if you want your Web service to be a script callable service. The above web service includes one Web method which is GetLatestNumberOfEmails that accesses the database and retrieves the total number of emails or records in the database.

Downloads

[Download Sample]

Conclusion

In this article we demonstrated how to build MSN Messenger-like popup windows to show up on the page when a new record is added to the database table. You can use the same technique in your Web application for any other goal. But the idea is the same, which is popping up windows on an ASP.NET Page due to an event that happened somewhere on the server.

Happy Ajaxified Dot Netting!!


 

Article Feedback

Title: *
Name: *
Url: ( Optional )
Comment: *
Please add 2 and 3 and type the answer here:

User Comments

Title: GOOG   
Name: Mr. Duc
Date: 7/25/2007 1:38:18 AM
Comment:
good, I love it, and I use example in my project. Thank you very much
Title: Re: Hiren   
Name: Bilal Haidar [MVP]
Date: 6/25/2007 1:50:19 AM
Comment:
Hiren,
You can visit my site here: http://bhaidar.net/cs/archive/2007/04/18/telerik-c-vb-net-converter.aspx

You can convert the code from C# to VB easily!

Hope this helps,
regards
Title: Very Nice Example   
Name: Hiren Jatakia
Date: 6/25/2007 1:41:04 AM
Comment:
Hello Bilal,
This is exactly i want, Nice article, but can i have VB version of this example, cause i require this in VB.net format not in c#, if u can send it to me, it would be very helpful for me......
Title: Nice codes   
Name: PAwan Kumar
Date: 6/24/2007 4:59:04 AM
Comment:
Nice tutorial ....keep it up
Title: database   
Name: somuvas
Date: 6/20/2007 1:55:22 AM
Comment:
this is db connections
Title: One Question Though   
Name: AzamSharp
Date: 6/14/2007 12:44:52 PM
Comment:
Hi Bilal,

Great article as usual. I have one question though. Is there any special reason that you used the UpdateProgress control?

Thanks,
Azam
Title: Very Very Nice Work   
Name: AzamSharp
Date: 6/13/2007 5:57:37 PM
Comment:
Hi Bilal,

Very very nice work. :)

Thanks,
Title: SW engineer   
Name: Vinh
Date: 6/13/2007 10:36:29 AM
Comment:
It is good article. Simple and easy to follow.
Title: Re:   
Name: Bilal Haidar [MVP]
Date: 6/13/2007 9:28:10 AM
Comment:
I never publish anything that it doesn't work!

Plus, there is a technical editing for this article! So I am sure it works!! Are you facing any problem?

Regards
Title: R u sure!   
Name: Vijay KArla
Date: 6/13/2007 4:28:25 AM
Comment:
Bilal, R u sure that it works?
Title: Great work   
Name: Sandeep Acharya
Date: 6/13/2007 3:56:32 AM
Comment:
Hi,

I have already gone thru some of your prev articles and this one also carries the excellence with no exception.

Keep providing us such nice stuffs.

Thanks

Sandeep Acharya
Title: Good Article   
Name: Joydip Kanjilal
Date: 6/13/2007 1:58:54 AM
Comment:
Hi Bilal,

This is a nice article. Keep this good work going.

Best,

Joydip
Title: It's Good   
Name: Anjali Kataria
Date: 6/12/2007 10:12:05 PM
Comment:
Feature that u explain with an examples Its good. Good Work keep Up GOOD LUCK
Title: Very Good Article   
Name: Haissam Abdul Malak
Date: 6/12/2007 1:22:24 AM
Comment:
Bilal, it was nice to see such an implementation. keep up the good work

Regards,


posted on 2007-07-25 15:34  拾荒时代  阅读(600)  评论(0)    收藏  举报