Click here to Skip to main content
16,016,024 members
Articles / Web Development / ASP.NET

ASP.NET Page Automatically Notifies When MSMQ Message Arrives

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Jan 2011CPOL2 min read 13.3K   4   1
This blog will discuss how ASP.NET page automatically notifies when MSMQ message arrives

Recently, I came across one forum query. The query was like: There is one source from which message was sent to MSMQ and a web interface aka an ASP.NET page would display the newly added message automatically without any user intervention. In order to replicate the situation, I created two .NET projects; one is simple console application and another one is an web application. Console application would compose the message and send it to the MSMQ continuously using an infinite loop. Web application connects to MSMQ and displays the message in a gridview using ajaxupdatepanel which asynchronous trigger fired by an Ajax timer control.

Time to start with a console application. I assume that you have MSMQ feature installed on your server and you are using VS 2010.

In console application, I created a very simple method to create a queue; composing and sending the message to the queue using the following code snippet:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Threading;
namespace MSMQSample
{
class Program
{
static void Main(string[] args)
{
//Infinite loop executed in the 5 seconds interval
while (true)
{
SendMessage();
Thread.Sleep(5000);
}
}
// Method to create queue, compose message and sendingmessage to queue
private static void SendMessage()
{
try
{
const stringMSG_QUEUE = @".\private$\TestQueue";
MessageQueue _msgQueue = null;
if (MessageQueue.Exists(MSG_QUEUE))
{
_msgQueue = new MessageQueue(MSG_QUEUE);
}
else
{
MessageQueue.Create(MSG_QUEUE);
}
string _msgText = String.Format("Messagesent at {0}", DateTime.Now.ToString());
Message _msg = new Message();
_msg.Body = _msgText;
_msg.Label = new Guid().ToString();
_msgQueue.Send(_msg);
}
catch (Exceptionexc)
{
Console.WriteLine(exc);
}
}
}
}

Running this console application would create the message and send the message to MSMQ.

Now you need to create one web application with one aspx page. The aspx page contains one Ajax timer, Ajax updatepanel and gridview control. I use timer control to invoke the method on each tick event (interval of 5 seconds) of it and update the gridview control using partial update (because I put the gridview within updatepanel).

I also have one custom class MSMQMessage to store the message label and body. You can add/remove properties from it according to your requirement. Basically, I am binding list of MSMQMessage with the gridview control.

The aspx code looks like:

ASP.NET
<%@ Page
Language="C#"AutoEventWireup="true"
CodeBehind="Default.aspx.cs"Inherits="MSMQSample.Web.Default"%>
<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head> 
<body> 
<form id="form1″ runat="server">
<asp:ScriptManager ID="ScriptManager1″runat="server">
asp:ScriptManager>
<div>
<asp:Timer ID="UpdateTimer"runat="server"
Interval="5000″OnTick="UpdateTimer_Tick">asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1″runat="server">
<Triggers>
<asp:AsyncPostBackTriggerControlID="UpdateTimer"EventName="Tick"/>
Triggers>
<ContentTemplate>
<asp:GridView ID="grdMessage"runat="server"> 
asp:GridView>
ContentTemplate>
asp:UpdatePanel> 
div>
form>
body> 
html>

The MSMQMessage classcode is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MSMQSample.Web
{
public class MSMQMessage
{
public string Label {get;set;}
public string Body{get;set;}
}
}

In codebehind, I write a method to read the message from queue, bind the gridview with list of message and call this method on tick event of timer. This is achieved using the following code:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Messaging;
using System.Threading;
namespace MSMQSample.Web
{
public partial class Default :System.Web.UI.Page
{
const stringMSG_QUEUE = @".\private$\TestQueue"; 
protected voidPage_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
UpdateGUI();
}
}
protected voidUpdateTimer_Tick(object sender, EventArgs e)
{
UpdateGUI();
}
private voidUpdateGUI()
{
try
{
MessageQueue _msgQueue = null;
IList<MSMQMessage>_msgList = new List<MSMQMessage>();
if (MessageQueue.Exists(MSG_QUEUE))
{
_msgQueue = new MessageQueue(MSG_QUEUE);
}
else
{
throw newException("MessageQueue does not exist");
}
foreach (Message_message in _msgQueue.GetAllMessages())
{
MSMQMessage _msmqmessage = new MSMQMessage(); 
_msmqmessage.Label = _message.Label;
_message.Formatter = new XmlMessageFormatter(newString[] { "System.String,mscorlib"});
_msmqmessage.Body = _message.Body.ToString();
_msgList.Add(_msmqmessage);
}
grdMessage.DataSource = _msgList;
grdMessage.DataBind();
}
catch
{
throw;
}
}
}
}

It is obvious that the update GUI method would be called by the Timer’s tick event in the interval of 5 seconds and it will bind the list of message with the gridview.

How to test the application. First run the aspx page. Initially, it will not display anything because you don’t have any message in the queue.

Right click on console application from solution explorer and click on Debug -> Start New Instance.

That’s it! Now you will show the aspx page that automatically refreshes the gridview and shows you the latest messages.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
A community lover and consultant working with Microsoft suite of products. Since 2005, he has been working in application development and maintenance using different Microsoft products. During his leisure time, he prefers to serve different Microsoft communities and learning new technologies. You can reach him at his blog DotNet Artisan

Comments and Discussions

 
GeneralVisual Studio Solution Pin
Juwi_uk27-May-11 8:07
Juwi_uk27-May-11 8:07 
Hi,

This looks greate but I'm having trouble piecing all of the code snippets together in this sample.

Are you able to post the example as a Visual Studio project for us to download?

Regards

Julian

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.