Responding To Inbound SMS Messages

In our last article, we created the basis of a messaging system, allowing us to receive inbound messages using keywords and shortcodes. We’ve also previously seen how we can send SMS messages. It’s time to bring everything together and create a simple messaging system that can process inbound SMS messages and send back responses to those messages.

The Current System

Our inbound messaging system (see the Receiving SMS Messages via Shortcodes & Keywords article) currently consists of:

  • A simple SQL Server database
  • A “listener” ASP.NET Web page
  • An Inbound SMS Message class

As it stands, the system can receive inbound SMS messages and delivery receipts. The key part we are missing is the ability to send a response message back to the person who sent in the inbound response. That’s what we’re going to add here. This will cause the code to change quite a bit, so we won’t show the previous code here; please refer to the other articles if you want to see this.

Why Do We Need To Respond?

You might ask yourself why bother sending a response? Well, courtesy first of all. If you’ve advertised a keyword mechanism and one of your customers (or potential customers) has made the effort to use it, the least you can do is acknowledge their message. Secondly, perception; most people expect to receive a reply of some sort when they send in a SMS message to a keyword/shortcode. Imagine you entered a competition via SMS. You would expect to receive a message back confirming your entry, wouldn’t you?
It’s always best to respond to user queries. This lets the user know the system is working and can also be used to direct them to a Web site, which can possibly be used to entice them to use more of your services or products. Don’t leave the user sitting around wondering whether their SMS message arrived!

Planning Our System

We need to change both parts of the system to improve our functionality. We must:

  • Change the database structure
  • Change the ASP.NET listener and classes

What You Need

This example is developed using a SQL Server database (any version from 2000 onwards) and a simple C# ASP.NET Web site. So you’ll need a version of SQL Server (the free SQL Server Express Edition will do the trick) and a tool which allows you to create an ASP.NET Web site (Visual Studio Express could be used here, this is also free).
If you want to test the system in anger, you’ll need an account with an aggregator or SMS provider (see here for more information on this), and at least one keyword with that aggregator. We’re using iTagg in this example, but there are lots more aggregators and SMS providers – Mdev, Oxygen8, and Tanla are just a couple of examples.

The Database

We’ll start off by creating the database. In our previous articles, this consisted of one table, which we used to store messages. It also contained a couple of stored procedures, which inserted messages into the table and updated messages with delivery receipt information.

To be able to support a proper inbound/outbound SMS mechanism, we need to add:

  • The ability to send back a response message to inbound messages
  • The ability to identify the keyword to which the inbound message was received, and then send back a response specifically for that keyword

Assume we had two keywords – mobiforge and deviceatlas. If our system only supported one response, the message sent back would always be the same. If the response was set up as follows:
Thanks for contacting mobiForge! To see great articles discussing all aspects of mobile development, visit http://mobiforge.com now!

Then we would be confusing users who have texted in to the deviceatlas keyword. It’s natural to assume they would expect to receive a response along these lines:
DeviceAtlas is the premier mobile device detection database. To find out more, visit us at http://deviceatlas.com today.

To support this functionality, we’ll need to amend the database as follows:

  • Add a KeywordResponses table, which will store keyword details and details of the response message to send
  • Modify the Messages table, so it is linked to the KeywordResponses table
  • Modify the usp_InsertMessage stored procedure, so it can identify the keyword to which the message has been sent, and returns the response to send
  • Add a stored procedure to return keyword details when an inbound message is received

Here’s an updated script, with all of those changes:

Run this script in SQL Server Management Studio to create the database. In the screenshot below, I’ve inserted two records into the KeywordResponses table to support the mobiforge and deviceatlas keywords I was discussing earlier.


Figure 1 – Configuring keywords in the database

You can see that each record stores the name of the keyword, along with the shortcode on which the keyword is located. There’s a SendResponse flag, which denotes whether a response should be sent or not; and finally there’s a ResponseOriginator and a ResponseMessageBody. These two values determine what message is sent, and who it appears to be sent from.
We now have support for multiple keywords in our database. Hurrah! Now we just need to update the ASP.NET side of things.

ASP.NET Changes

On the ASP.NET side of things, we’d previously created a site that had:

  • An ASPX page that acts as a listener, waiting for messages to be received from the aggregator (the intermediary company we use to send and receive SMS messages through – see here for more information)
  • A simple iTaggDeliveryReceipt class, to handle delivery receipts
  • A simple InboundSmsMessage class, to handle inbound SMS messages

We’ll change the site so it has the following:

  • An ASPX page that acts as a listener. This will handle both the inbound messages and the delivery receipt notifications
  • A simple iTaggDeliveryReceipt class
  • A KeywordResponse class, to represent the keywords and their associated response
  • A SmsMessage class, which represents both inbound and outbound SMS messages

We’ll assume we’re starting from scratch, and no previous project exists.

Creating the ASP.NET Web Site

Open up Visual Studio. From the File menu, choose New, then Web Site. Call the Web site MobiforgeDemo and click OK. You’ll have a variety of options depending upon the version of Visual Studio used; ensure you create an ASP.NET Empty Web Application.


Figure 2 –Creating an empty ASP.NET Web Site

Once the project is created, your Solution Explorer (this is usually displayed on the right-hand side of the screen) will look something like this (if you’re using Visual Studio 2010):


Figure 3 – Solution Explorer after Web Site creation

Let’s add in the classes first. Right-click on MobiforgeDemo and choose Add -> New Item from the pop-up menu. Choose Class, and set the file name as iTaggDeliveryReceipt.cs. Then click Add to create the class.


Figure 4 – Adding a class

Repeat the process two more times, setting the file name as:

  • KeywordResponse.cs
  • SmsMessage.cs

Finally, we need to add the listener Web page. Select the Add -> New Item option from the pop-up menu again, but this time choose Web Form. Name the form listener.aspx and click Add.

Solution Explorer will now look like this:


Figure 5 –The final Solution Explorer

We now have all the building blocks in place, and we can start adding code.

iTaggDeliveryReceipt Class

Let’s add the code for the iTaggDeliveryReceipt class first. This processes delivery receipt XML sent to our system from iTagg and updates the database accordingly. Double-click on iTaggDeliveryReceipt.cs in Solution Explorer, and replace the code there with the following:

The code is pretty simple. We start off by defining a bunch of private properties and public accessors. Once this is done we define a constructor to accept and process the XML sent to us by iTagg. This constructor calls a private method that returns a value for the specified XPATH query.

SmsMessage Class

We need a mechanism that allows us to represent SMS messages in the database. This mechanism should allow us to:

  • Represent the properties of an SMS message
  • Store messages in the database, whether they are inbound or outbound

We’ll create the SmsMessage class for this very purpose. Open SmsMessage.cs and enter this code.

The first part of the code listing defines the properties – message body, originator, recipient etc. Then we have two constructors. The first constructs a message from an Input Stream. This is used to create inbound message objects, as iTagg will deliver an input stream to our listener page when they receive an inbound SMS message on our behalf. The second is used to construct outbound messages and accepts a defined set of parameters that we can use to create the SmsMessage object.
The last method in the listing is WriteMessageToDatabase. This calls the usp_InsertMessage stored procedure to insert the message into the database. When instantiating the connection, ensure you replace DBSERVER with the name of your SQL Server.

KeywordResponse Class

The last class we’ll create is KeywordResponse. This is another simple class that will:

  • Define a set of properties to define a keyword response
  • Create a keyword response from an inbound message, by reading details from the database
  • Have the ability to send the response SMS message

Open up the KeywordResponse.cs file, and add in the code below:

We begin by defining four properties:

  • Keyword ID – The internal keyword identifier; we use this to easily identify keywords within the database.
  • Send Response – A Boolean value, which determines whether we send a response back when an inbound message is received. If this is true, we send the response.
  • Response Originator – Response Message Body

These are the values sent back to the person who sent the inbound SMS message. The Response Originator determines who the message was sent from; the Response Message Body represents the content of the message.

Next up we define our constructor. This accepts an Input Stream, which in this case is the HTTP POST string passed to us by iTagg. We then pull out the parts of this Input Stream that allow us to identify the keyword to which the message was sent.

Our next method is _readKeywordFromDatabase. This is called by the constructor to pull out the keyword response details from the database we created earlier. This is a private method and cannot be called outside of the class.

Last up we have SendSmsMessage. This is a public method and is used to send the response SMS message back to the original sender via iTagg. You’ll note at the end of this method we create a SmsMessage object and write it to the database – this creates a record of the message we’ve just sent in the database.
When instantiating the connection in readKeywordFromDatabase, ensure you replace DBSERVER with the name of your SQL Server. Also, ensure you set the correct user name and password for your iTagg account in the SendSmsMessage method.

Listener.aspx

The last piece of the puzzle is the listener page. This page will be called when an inbound message or delivery receipt arrives, and will contain code to process the inbound message/delivery receipt. This page will perform the following processing:

  • Determine whether the data being passed by iTagg is a delivery receipt or an inbound message
  • If the data represents a delivery receipt, the database is updated
  • If the data represents an inbound message, we obtain the keyword details, write the message to the database, and then send back a response SMS message (if the keyword is configured to do so)

There are four key methods defined here to do our work:

  • Page_Load – This is the standard ASP.NET page load event. This is the first event called. It calls DeliveryReceiptReceived to determine what type of message has been received, and then calls the appropriate processing method.
  • DeliveryReceiptReceived – Returns true if a delivery receipt has been received. If an inbound SMS message was received, it returns false.
  • ProcessDeliveryReceipt – Processes a delivery receipt. The message ID is identified and the appropriate message in the database is updated.
  • ProcessInboundSmsMessage – Processes an inbound SMS message. The sending of the outbound response SMS message is performed here.

Here’s the code, type or paste it into listener.aspx.cs:

Compile the application – it should build without any issues (make sure you change DBSERVER to the name of your SQL Server). Deploy it to IIS as you would any other application. We’re almost ready to roll!

Configuring iTagg

Assuming you have set up a keyword with iTagg, you now need to tell iTagg to direct any messages sent to this keyword to your new Web site. Let’s assume the Web site URL is:
http://mobiforge.com/mobiforgedemo/listener.aspx
You need to log on to the ITagg control panel, and set up the keyword URL. We also need to set up the delivery receipt URL.
To set these URLs up, point your browser at www.itagg.com. Log on to the control panel. After doing this, a screen should appear listing your keywords.


Figure 6 – The iTagg control panel

Click on the keyword and set the URL. This should be set to the URL you have published the Web site to. Make sure you add the listener.aspx part. Click OK to save.


Figure 7 – iTagg URL configuration

Nearly ready – we just need to set up delivery receipts. In the menu on the left, click on the Delivery Receipts option. When the screen appears, set the URL to the same as that you’ve just specified for the keyword.


Figure 8 – Setting the iTagg Delivery Receipt URL

Click Update to save. You’re done!

Testing The System

All that is left to do now is test the system. So grab your phone and type in your keyword! If your keyword is mobiforge, send mobiforge to 60300. Please don’t try this – it isn’t a live example! If you’d like to try out a real company that’s using iTagg, try texting thebestof to 60300.


Figure 9 – Sending an SMS message

Once you’ve sent your message, wait for a few seconds and you should receive a response back:


Figure 10 – Receiving an SMS message

Let’s check out the database. We should have two messages in there; the inbound message we’ve just sent, and the outbound message the system has just sent.


Figure 11 – The database after message sending and receiving

Note the Delivered column in the table; the outbound message is showing true in the column, which tells us our delivery receipt processing is working too (the inbound messages will always display false). Hurrah!

Summary

So there we are – a complete messaging system in a few easy steps! Remember that you don’t have to use iTagg – you are free to use any messaging provider you wish. The system we’ve just built isn’t robust – it needs more error handling, for example – but it gives you the basis to go on and create a fully automated, inbound and outbound SMS messaging system. Have fun sending – and receiving!

Exclusive tips, how-tos, news and comment

Receive monthly updates on the world of mobile dev.

Other Products

Market leading device intelligence for the web, app and MNO ecosystems
DeviceAtlas - Device Intelligence

Real-time identification of fraudulent and misrepresented traffic
DeviceAssure - Device Verification

A free tool for developers, designers and marketers to test website performance
mobiReady - Evaluate your websites’ mobile readiness

© 2024 DeviceAtlas Limited. All rights reserved.

This is a website of DeviceAtlas Limited, a private company limited by shares, incorporated and registered in the Republic of Ireland with registered number 398040 and registered office at 6th Floor, 2 Grand Canal Square, Dublin 2, Ireland