Setting up MSMQ on your Mobile and Writing MSMQ Application with .NET Compact Framework 3.5

Exclusive offer: get 50% off this eBook here
.NET Compact Framework 3.5 Data Driven Applications

.NET Compact Framework 3.5 Data Driven Applications — Save 50%

Build robust and feature-rich mobile data-driven applications with the help of real-world examples

$29.99    $15.00
by Edmund Tan | April 2010 | .NET

In this article by Edmund Tan, author of .NET Compact Framework 3.5 Data Driven Applications, we will discuss about the following:

  • Setting up Microsoft Messaging QueueService(MSMQ) on your mobile device
  • Writing your first MSMQ application
  • Setting up MSMQ on your server

Let's get started.

Setting up Microsoft Messaging Queue Service (MSMQ) on your mobile device

MSMQ is not installed by default on the Windows Mobile platform. This section will guide you on how to install MSMQ on your mobile device or device emulator. You will first need to download the Redistributable Server Components for Windows Mobile 5.0 package (which can also be used for Windows Mobile 6.0) from this location:

href="http://www.microsoft.com/downloads/details.aspx?FamilyID=cdfd2bb2-fa13-4062-b8d1-4406ccddb5fd&displaylang=en

After downloading and unzipping this file, you will have access to the MSMQ.arm.cab file in the following folder: \Optional Windows Mobile 5.0 Server Components\msmq

Copy this file via ActiveSync to your mobile device and run it on the device. This package contains two applications (and a bunch of other DLL components) that you will be using frequently on the device:

  • msmqadm.exe:This is the command line tool that allows you to start and stop the MSMQ service on the mobile device and also configure MSMQ settings. It can also be invoked programmatically from code.
  • visadm.exe: This tool does the same thing as above, but provides a visual interface.

These two files will be unpacked into the \Windows folder of your mobile device. The following DLL files will also be unpacked into the \Windows folder:

  • msmqd.dll
  • msmqrt.dll

Verify that these files exist. The next thing you need to do is to change the name of your device (if you haven't done so earlier). In most cases, you are probably using the Windows Mobile Emulator, which comes with an unassigned device name by default. To change your device name, navigate to Settings | System | About on your mobile device. You can change the device name in the Device ID tab. At this point, you have the files for MSMQ unpacked, but it isn't exactly installed yet. To do this, you must invoke either msmqadm.exe or visadm.exe. Launch the following application:

\Windows\visadm.exe

A pop-up window will appear. This window contains a text box and a Run button that allows you to type in the desired command and to execute it. The first command you need to issue is the register install command. Type in the command and click the Run button. No message will be displayed in the window. This command will install MSMQ (as a device driver) on your device.

Run the following commands in the given order next (one after the other):

MSMQ Command Name

Purpose

register

You will need to run the register command one more time (without the install keyword) to create the MSMQ configuration keys in the registry.

enable binary

This command enables the proprietary MSMQ binary protocol to send messages to remote queues.

enable srmp

This command enables SRMP (SOAP Reliable Messaging Protocol), for sending messages to remote queues over HTTP.

start

This command starts the MSMQ service

 

Verify that the MSMQ service has been installed successfully by clicking on the Shortcuts button and then clicking the Verify button in the ensuing pop-up window. You will be presented with a pop-up dialog as shown in the following screenshot:

MSMQ log information

If you scroll down in this same window above, you will find the Base Dir path, which contains the MSMQ auto-generated log file. This log file, named MQLOGFILE by default, contains useful MSMQ related information and error messages.

After you've done the preceding steps, you will need to do a soft-reset of your device. The MSMQ service will automatically start upon boot up.

.NET Compact Framework 3.5 Data Driven Applications Build robust and feature-rich mobile data-driven applications with the help of real-world examples
Published: April 2010
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Writing your first MSMQ application

Your first MSMQ application will do something really simple—create a local queue (on the device), send a message to the queue, and then read it back from the queue immediately after.

Create a new Smart Device Application project named SupportCase, and add a new form to your project. Add a reference to the System.Messaging library in your project. This library contains the MSMQ routines.

Create a new class named Generic.cs. This class will contain the initialization routines for MSMQ. Write the following code:

using System;
using System.Windows.Forms;
using System.Messaging;
using System.Runtime.InteropServices;
namespace SupportCase
{
public class Generic
{

//Import the following API functions in CoreDLL.dll
[DllImport("CoreDll.dll")]private static extern int
CloseHandle(IntPtr hProcess);
[DllImport("CoreDll.dll")]private static extern IntPtr
ActivateDevice(string lpszDevKey, int dwClientInfo);

//This function will initialize MSMQ and ensure that the
//service is running. It will ultimately return true if
//MSMQ is running
public static bool InitializeMSMQ()
{
bool returnValue;
returnValue = RunMSMQCommand("status");
if (returnValue == false)
{
//MSMQ service is not started yet, so we will
//attempt to recreate the registry keys and start
//the service
RunMSMQCommand("register cleanup");
RunMSMQCommand("register install");
RunMSMQCommand("register");
RunMSMQCommand("enable binary");
RunMSMQCommand("enable srmp");
returnValue = RunMSMQCommand("start");
if (returnValue == false)
{
//You have to perform ActivateDevice
//(specifically for Pocket PC devices)
//to load the MSMQ device drivers.
RunActivateDevice();
//Check the status of the MSMQ service again
returnValue = RunMSMQCommand("status");
}
}
return returnValue;
}
//This function loads the MSMQ device drivers
public static void RunActivateDevice()
{
try
{
IntPtr handle =
ActivateDevice("Drivers\\BuiltIn\\MSMQD", 0);
CloseHandle(handle);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//This function allows you to run an msmqadm command
//programmatically. It is functionally similar to
//executing statements in visadm.exe
public static bool RunMSMQCommand(string Command)
{
try
{
Process _process = new Process();
_process.StartInfo.FileName =
"\\windows\\msmqadm.exe";
_process.StartInfo.Arguments = Command;
_process.StartInfo.UseShellExecute = true;
_process.Start();
_process.WaitForExit();
return (_process.ExitCode == 1 ? false : true);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return false;
}
}
}

Now let's take a look at the code required to send a message to a queue. The first thing you need to do is to create the queue. You can create a queue programmatically using the following code:

string _queueName = ".\\private$\\mylocalqueue";
if (! MessageQueue.Exists(_queueName))
{
MessageQueue.Create(_queueName);
}

The queue name usually takes on the following format. The private$ keyword indicates that this queue is a private queue (that is not published on the network).

.\\private$\\queueName

You must now create the message object. The Message class allows you to create one in the following manner:

Message _m = new Message();
_m.Label = "My first message";
_m.Body = "Hello, this is my first message";

The Body property of the message takes in an object, which can be a string, or an entire business object. Take note that serialization of business objects is done automatically by the queue. Now that you have the message object, you need to send it to a queue. You must first create a MessageQueue object in your code and pass in the name of the queue you want it to represent. This object contains a Send method that you can use to send the Message object to the queue. This can be done via the following code:

MessageQueue _mq = new MessageQueue(_queueName);
_mq.Send(_m);
_mq.Close();

To read from a queue, you must first inform MSMQ which data type you're using in the Body property of the message. You can do this by setting the MessageQueue.Formatter property to an appropriate formatter. In the following code, you are specifying a String data type for the formatter:

_mq.Formatter = new XmlMessageFormatter(new Type[]{typeof(string)})
;

The next step would be to do the actual read. You can do this by calling the MessageQueue.Receive method, which will then return a Message object. The following code shows how you can retrieve and display the Body of a received message:

Message _receivedMsg = _mq.Receive();
MessageBox.Show(_receivedMsg.Body.ToString());

Now, let's put it all together. Add a button to the form you've created earlier. In the click event of the button, write the following code to send a message to a queue and to read it back from the same queue right after:

public void btnSendLocalMessage_Click(System.Object sender, 
System.EventArgs e)
{
//First we initialize MSMQ
if (Generic.InitializeMSMQ() == false)
{
MessageBox.Show("Could not initialize MSMQ");
return;
}

string _queueName = ".\\private$\\mylocalqueue";
try
{
//Create the queue if it does not exist
if (! MessageQueue.Exists(_queueName))
{
MessageQueue.Create(_queueName);
}
//Send the message to the queue
MessageQueue _mq = new MessageQueue(_queueName);
Message _m = new Message();
_m.Label = "My first message";
_m.Body = "Hello, this is my first message";
_mq.Send(_m);
public void btnSendLocalMessage_Click(System.Object sender,
System.EventArgs e)
{
//First we initialize MSMQ
if (Generic.InitializeMSMQ() == false)
{
MessageBox.Show("Could not initialize MSMQ");
return;
}

string _queueName = ".\\private$\\mylocalqueue";
try
{
//Create the queue if it does not exist
if (! MessageQueue.Exists(_queueName))
{
MessageQueue.Create(_queueName);
}
//Send the message to the queue
MessageQueue _mq = new MessageQueue(_queueName);
Message _m = new Message();
_m.Label = "My first message";
_m.Body = "Hello, this is my first message";
_mq.Send(_m);

If you run this sample, you will see that the message is first sent to the local queue, and then is displayed.

.NET Compact Framework 3.5 Data Driven Applications Build robust and feature-rich mobile data-driven applications with the help of real-world examples
Published: April 2010
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Setting up MSMQ on your server

To send messages remotely from a mobile device to a server, your server must also have queues (and, therefore, MSMQ) set up. Not all PCs or servers come with MSMQ installed by default. To install MSMQ on your PC, you simply have to follow these steps:

  1. Navigate to the Control Panel of your operating system, and launch Add/Remove Programs (in Windows XP) or Programs and Features (in Windows Vista).
  2. On the left pane, you will be able to see the Add/Remove Windows Components shortcut (in Windows XP) or Turn Windows Features on or off shortcut (in Windows Vista). Click on the shortcut.
  3. In the ensuing pop-up window, ensure that all the Microsoft Message Queue (MSMQ) Server options are checked. (The naming of the various subcomponents might also differ between Windows XP and Vista.)
  4. Click OK to begin installation. You might be prompted for the Windows setup CD in the process.
  5. After a successful installation, you will have access to the various message queuing features in the Control Panel | Administrative Tools | Computer Management tool. You will see a Message Queuing node under the Services and Applications node. Through this area, you can manually create/remove a queue and also browse through messages sitting in these queues.

Creating a queue on the server manually using the computer management panel

You will now create a local private queue in your server by right-clicking the Private Queues node and then choosing New | Private Queue from the context menu. Specify private$\jobqueue as the name for this queue. Do not check the Transactional checkbox.

You will now see your queue added to the Private Queues section. Right-click on the queue and navigate to its properties window. Under the Security tab, ensure that you have granted the ANONYMOUS_LOGON, IUSR_MachineName, and IWAM_MachineName accounts at least the Receive Message and Peek Message rights.

Summary

In this article, we discussed about the following:

  • Setting up MSMQ on your mobile device
  • Writing your first MSMQ application
  • Setting up MSMQ on your server

About the Author :


Edmund Tan

Edmund Tan is the CTO and co-founder of a leading e-forms and workflows solution vendor based in Singapore. He holds more than 8 years of experience building performance-critical .NET e-forms and workflows solutions for smart devices on top of Oracle and Microsoft SQL Server databases for large companies and governmental institutions located in Singapore.

Edmund is also a regular public speaker in various conferences held in Singapore and Malaysia on the topic of on-the-go BPM (Business Process Management) hosted on smart device technologies.

Books From Packt

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide
Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

Microsoft Silverlight 4 Data and Services Cookbook
Microsoft Silverlight 4 Data and Services Cookbook

ASP.NET MVC 1.0 Quickly
ASP.NET MVC 1.0 Quickly

Programming Microsoft Dynamics NAV 2009
Programming Microsoft Dynamics NAV 2009

VSTO 3.0 for Office 2007 Programming
VSTO 3.0 for Office 2007 Programming

Microsoft Dynamics AX 2009 Programming: Getting Started
Microsoft Dynamics AX 2009 Programming: Getting Started

Least Privilege Security for Windows 7, Vista, and XP
Least Privilege Security for Windows 7, Vista, and XP

Learning SQL Server 2008 Reporting Services
Learning SQL Server 2008 Reporting Services

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
4
7
d
d
L
n
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software