devxlogo

SMS Messaging Using the .NET Compact Framework

SMS Messaging Using the .NET Compact Framework

MS messaging is one of the many ways in which your Windows Mobile application[s] connect to the outside world. The key advantage to SMS is that as long as the device has a valid SIM card, it is able to send and receive SMS messages. Unlike using web services (which uses a request and response communication model), SMS messaging is asynchronous in nature?messages are sent and received as and when needed. Also unlike sockets programming, SMS messaging does not require building a client and server in order to send and receive data?all relaying is taken care of by the cellular network. There are downsides, however: Using SMS messaging can be costly and delivery is non-guaranteed. That said, SMS messaging is still a viable solution for many enterprise applications in use today.

This article will show you how to use SMS messaging in a real-world application. The sample application is used in a hospital where nurses are equipped with Windows Mobile devices. When a patient is admitted to the hospital, SMS messages are sent to the nurses in charge to notify them of the various events happening, such as patients’ admission, patients’ discharging, etc. The sample project uses the .NET Compact Framework to integrate SMS messaging into the application.

Sending SMS Message
Using Visual Studio 2008, create a new Windows Mobile 6 Professional application using C#. Name the project SMSMessaging.

To use SMS messaging in a Windows Mobile application, you need to add a reference to the following DLLs:

  • Microsoft.WindowsMobile.dll
  • Microsoft.WindowsMobile.PocketOutlook.dll

Populate the default Form1 with the controls shown in Figure 1.

Figure 1. Form1: Populating the default Form1 with the various controls.

For simplicity’s sake, hardcode the lblEmployeeID control with a fixed employee ID. Also, add a few items into the cbbLocation control: Ward 1, Ward 2, Ward 3, and so on.

Switch to the code-behind of Form1 and import the following namespace:

using Microsoft.WindowsMobile.PocketOutlook;

Within the Form1 class, define the constant representing the phone number of the HQ where you can send acknowledgement messages to:

    public partial class Form1 : Form    {        const string HQPhoneNo = "651234567";

In the first part of this project, you’ll be enabling a nurse to send his/her location to a central server through SMS. Code the Send Location via SMS button as follows:

        private void btnSendSMS_Click(object sender, EventArgs e)        {            try            {                SmsMessage sms = new SmsMessage()                {                    Body = lblEmployeeID.Text + "|" + cbbLocation.Text                };                sms.To.Add(new Recipient(HQPhoneNo));                sms.Send();                MessageBox.Show("Message sent!");                                        }            catch (Exception ex)            {                MessageBox.Show(ex.Message);                        }        }

The SmsMessage class (located in the Microsoft.WindowsMobile.PocketOutlook namespace) allows you to send a SMS message to one or more recipients. In the code above, if a nurse is current in Ward 5, the application will send a SMS message with the following content (in the format |):

745402|Ward 5

Intercepting SMS Messages
When a new event occurs (such as patient admissions/discharges), this information can be transmitted instantly to the nurse using SMS messages.

Add the controls shown in Figure 2 to Form1.

SMS messages sent to the nurses will be in the following format:

TSK_REQ|||

The following list shows sample SMS messages:

  • TSK_REQ|123|6|Prepare patient for discharge
  • TSK_REQ|456|5|Prepare patient for admission
  • TSK_REQ|009|2|Prepare patient for surgery

Each message will begin with the TSK_REQ identifier, followed by the patient ID, ward number, and the description of the task.


Figure 2. Task Information: Adding the controls to Form1 to display task information.
 
Figure 3. Task Messages: Receiving SMS task messages and displaying the individual task.

In the code-behind of Form1, import the following namespace:

using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;

Declare a variable of type MessageInterceptor:

    public partial class Form1 : Form    {        const string HQPhoneNo = "651234567";        MessageInterceptor msgInterceptor;

The MessageInterceptor class allows you to intercept an incoming SMS message and raise an event.

In the Form1_Load event handler, create a new instance of the MessageInterceptor class and wire up the MessageReceived event with an event handler:

        private void Form1_Load(object sender, EventArgs e)        {            msgInterceptor = new MessageInterceptor(                InterceptionAction.NotifyAndDelete, true);            msgInterceptor.MessageReceived += new                 MessageInterceptorEventHandler(                msgInterceptor_MessageReceived);        }

The MessageReceived event is fired whenever an incoming SMS message is received. In this event, you will first typecast the message received (via the SmsMessage object. This is necessary so that you can retrieve the body of the SMS message received. You then add the content of the message into the ListBox control (shown in Listing 1).

In this event, you also send an acknowledgement back to the sender by using another instance of the SmsMessage class. When a nurse clicks on the ListBox control, you will display the details of the tasks in the various label controls (see also Figure 3):

        private void listBox1_SelectedIndexChanged(        object sender, EventArgs e)        {            string task = listBox1.SelectedItem.ToString();            string[] field = task.Split('|');            if (field.Length == 4)            {                lblPatientID.Text = field[1];                lblWardNo.Text = field[2];                lblDescription.Text = field[3];            }        }

Filtering SMS Messages
So far the application intercepts all incoming messages, including those not sent by the system. However, from time to time a nurse might receive private messages from friends or family, that the application should not intercept.

You can set a message filter using the MessageCondition class. Modify the Form1_Load event to use the MessageCondition class to set up a filtering rule:

Figure 4. Private Messages: Messages not intercepted are received by the device.

        private void Form1_Load(object sender, EventArgs e)        {            msgInterceptor = new MessageInterceptor(                InterceptionAction.NotifyAndDelete, true);            //---set the filter for the message---            msgInterceptor.MessageCondition =                new MessageCondition(                   MessageProperty.Body,                   MessagePropertyComparisonType.StartsWith,                   "TSK_REQ", true);            msgInterceptor.MessageReceived += new                MessageInterceptorEventHandler(                msgInterceptor_MessageReceived);        }

From now on, only messages that start with the word “TSK_REQ” will be intercepted by the application; all other messages will be ignored and received by the device (see Figure 4).

Also, the application may not be in the foreground all the time. For example, a nurse may make a phone call and thus switch the application to the background. When a new task message arrives, you should bring the application to the foreground programmatically.

First, import the following namespace:

using System.Reflection;

In the event handler for the MessageReceived event, append the following lines of code to bring the application to the foreground, shown in Listing 2.

Basically, you first use reflection to find the path of the current application. You then use the Process.Start() method to run the application again. As Windows Mobile applications are single-instance, using the Start() method on an already running application simply brings it to the foreground.

Registering the Application with the Device
Now that the application is capable of intercepting all relevant messages, there is one more thing left to do. The application itself may not be always running. For example, the device may be reset for some reason, and when it is rebooted the application would not be loaded unless the nurse launches it specifically. The device will not intercept incoming task messages unless the application is running.

A better method is to register the application with the device’s registry so that whenever an incoming message is received (that satisfies the filtering rule), it automatically invokes the application (even when it has not yet been loaded).

To do this, declare an object of type Guid and assigns it a guid value:

    public partial class Form1 : Form    {        const string HQPhoneNo = "651234567";        MessageInterceptor msgInterceptor;        Guid appID = new Guid("{283D3327-ADB8-41a0-B9DD-28E2845B5FF3}");

Author’s Note: You can create a GUID for development use in Visual Studio 2008 by going to Tools?Create Guid.

In the Form1_Load event handler, use the static method IsApplicationLauncherEnabled() and check to see whether the application (identified using the appID object) is registered. If it is registered, load the existing MessageInterceptor class using the appID object. If it is not, proceed as normal and register the application using the EnableApplicationLauncher() method, shown in Listing 3.

Figure 5. Unregister: Adding a menu item control to unregister the application.

Because the application is automatically registered when it is loaded, it would be good to provide a means to unregister the application. To do so, add a menu item control to the Form (see Figure 5).

To unregister the application, use the DisableApplicationLauncher() method and remove the event handler for the MessageReceived event (as shown in Listing 4).

That’s it! From now on, when the application is loaded for the first time, it is automatically registered with the device. Even if the application is unloaded from memory, it will automatically be invoked when an incoming message satisfying the filtering rule is received.

Increasingly Useful
This article has shown you how to send and receive SMS messages using the .NET Compact Framework. Using SMS messaging as a communication medium is gaining popularity as the cellular network gains in coverage and reliability. If you have ideas for using SMS messaging in your Windows Mobile applications, don’t hesitate to share your ideas.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist