Build An SMS Queueing System Using Azure And Twilio

Before we work on this we need to make sure we have a paid Azure account. Azure free account does not provide some services which we need to run, like Azure message services and also creating a free account on Twilio for sent messages.

 I will discuss the following topics in this article.
  1. Create mobile app.
  2. Create API for sent messages.
  3. Create table for inserting information of sent messages.
  4. Queue messages.
  5. Create web jobs, which will run your method continuously.

Now, I will discuss the above defined points for sending a message with the help of Azure API, Web jobs and Twilio.

  1. Create Mobile App

    We’ll start building our notification system by logging into Azure and creating a new Storage mobile app. The Queue capability of the Storage mobile app provides a basic first-in-first-out (FIFO) queue and serves as the backbone of our system.

    After logging into Azure click “+” sign at top of left corner.



    When you click on “+” sign the following window will open.



    Now go in recent and click on mobile app, when you will click mobile app then a new window will open. From here you can create a new mobile app.



    Give the app name, create or select the resource group and click on create button after clicking on create button a new mobile app will be created.

  2. Create API for send messages

    After creating a mobile app successfully we will create an API which will use to send messages. Go to your created app, a new window opens with the overview of your created app.



    Scroll down the middle window. In the mobile section there are two link buttons for creating an API and table.



    Click on “Easy APIs” link button for creating an API. After clicking on the “Easy APIs” link a new section will open for creating an API. In this new section there are add buttons; click on this add button.

    When you click on this add button a new section “Add API will open”.



    From here you can create an API and can give the permission of your API. I create APIs with the permission of “Allow anonymous access”.

    After creating an API you need to create a table for storing message information.

  3. Create table for inserting information of sent messages

    Click on “Easy tables” link button, after clicking on this button a new section will open. Click on add button of this new section at top. A new section will open, “Add table”. Here you can create your table and can give the permission.



    After table is created click on created table, table section will open. In table section click on “Manage Schema” button at top.

    A schema section will open here you can add columns of your table. Add the   following columns in your table for managing information of sent messages, such as message, phone number, status, message id, version. Following columns are automatically created by Azure id, version, updateAt, deleted, createdAt.



    Now your table is created which we will use for storing message information.

  4. Queue Messages

    In this section we will read how we can queue messages. For queuing messages go on your created app, click on “Easy APIs” link button in mobile, click on your added API and “API details” section in this section click on “Edit Script” button.



    When you click on edit script button it will redirect to a new url.

    It will open “App Service Editor;” here you can write script for queuing your message in node JS. I give a small description about “Active Service Editor”.



    In “WORKING FILES” section open your JS file and write the following code.
    1. // Initiate the “azure-storage” module, if you do not find “azure-storage” module then open //console and run following command npm install azure  
    2. var azure = require("azure-storage");  
    3.   
    4. module.exports = {  
    5.     //Get  
    6.     "get"function(req, res, next) {  
    7.         res.send('test');  
    8.     },  
    9.     //Post  
    10.     "post"function(req, res, next) {  
    11.         var accountName = [Your Account Name];  
    12.         var accountKey = [Your Account Key];  
    13.         var host = accountName + '.queue.core.windows.net';  
    14.         // Create queue service  
    15.         var queueSvc = azure.createQueueService(accountName, accountKey, host);  
    16.         // it will create queue if not exist  
    17.         queueSvc.createQueueIfNotExists('[Your App Name]'function(error, result, resp) {  
    18.             if (!error) {  
    19.                 // Create Base64 Object  
    20.                 var buff = new Buffer(JSON.stringify(req.body)).toString("base64");  
    21.                 queueSvc.createMessage('[Your App Name]', buff, function(error, result, resp) {  
    22.                     if (!error) {  
    23.                         //if message successfully queued the show message  
    24.                         res.send('notifications queued');  
    25.                     } else {  
    26.                         res.send(error);  
    27.                     }  
    28.                 });  
    29.             } else {  
    30.                 res.send(error);  
    31.             }  
    32.         });  
    33.     }  
    34. }  
    After saving it you can test your API in fiddler or POSTMAN. For test get call.



    For post message defined Content-Type: application/json and in body pass the json object like.



    After clicking on send you can see your notification now queued.

    Now we need to define web and code for running the web jobs.

  5. Create web jobs which will run your method continuously for sent messages.

    First create a new console project in your visual studio.

    Install the following NuGet Packages.
    • Microsoft Azure WebJobs
    • Windows Azure Mobile Services
    • Twilio
After successfully installing these packages add the following code in your main method.
  1. publicstaticvoid Main(string[] args) {  
  2.     //config for web jobs  
  3.     var config = new Microsoft.Azure.WebJobs.JobHostConfiguration();  
  4.     //set polling interval  
  5.     config.Queues.MaxPollingInterval = TimeSpan.FromMinutes(3);  
  6.     //initiate job host  
  7.     JobHost host = newJobHost(config);  
  8.     //run job host  
  9.     host.RunAndBlock();  
  10.   
  11. }  
And add a method for sending notification.
  1. publicstaticasyncTaskSendNotifications([QueueTrigger("Your App name")] List < Notification > notifications) {  
  2.     try {  
  3.         //if notification is found  
  4.         if (!object.Equals(notifications, null)) {  
  5.             Console.WriteLine("Processing Notifications");  
  6.             //set mobile app url  
  7.             var mobileServiceAppUrl = ConfigurationManager.AppSettings["MOBILESERVICEAPPURL"];  
  8.             //intialize twilio client  
  9.             var twilioClient = newTwilioRestClient(ConfigurationManager.AppSettings["ACCOUNTSID"], ConfigurationManager.AppSettings["AUTHTOKEN"]);  
  10.             //initialize mobile service client  
  11.             var amsClient = newMobileServiceClient(mobileServiceAppUrl, ConfigurationManager.AppSettings["MOBILESERVICEAPPKEY"]);  
  12.             //get table where we put the all notification information in azure  
  13.             IMobileServiceTable < Notification > notificationsTable = amsClient.GetTable < Notification > ();  
  14.             foreach(var notification in notifications) {  
  15.                 // call back url  
  16.                 string notificationCallbackUrl = string.Format("{0}api/notificationCallback", mobileServiceAppUrl);  
  17.                 //insert data in notification table  
  18.                 await notificationsTable.InsertAsync(notification);  
  19.   
  20.                 Console.WriteLine("Sending to {0}", notification.phonenumber);  
  21.  
  22.                 #  
  23.                 region Twilio code  
  24.                 for sent message  
  25.                 //send message to user by twilio  
  26.                 var result = twilioClient.SendMessage(  
  27.                     ConfigurationManager.AppSettings["FROM"],  
  28.                     notification.phonenumber.Trim(),  
  29.                     notification.message,  
  30.                     notificationCallbackUrl);  
  31.   
  32.                 notification.Status = result.Status;  
  33.                 notification.MessageSid = result.Sid;#  
  34.                 endregion  
  35.   
  36.                 //update notification status when message sent or failed  
  37.                 await notificationsTable.UpdateAsync(notification);  
  38.             }  
  39.         } else {  
  40.             Console.WriteLine("No notification found.");  
  41.         }  
  42.     } catch (Exception ex) {  
  43.         Console.WriteLine("An error occured");  
  44.     }  
  45. }  
Add following connection string and key value in your web.config.
  1. <connectionStrings>  
  2.     <addname="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=Your Account Name ;AccountKey=Your Account Key" />  
  3. </connectionStrings>  
  4. In app settings add  
  5. <addkey="ACCOUNTSID" value="Your twilio account SID" />  
  6. <addkey="AUTHTOKEN" value="Twilio Token" />  
  7. <addkey="FROM" value="Your twilio phone number" />  
  8.   
  9. <addkey="MOBILESERVICEAPPURL" value="http://yourappname.azurewebsites.net/" />  
  10. <addkey="MOBILESERVICEAPPKEY" value="Your app key" />  
This method is used for sending messages by Twilio.

Now we need to create web jobs. For creating a job go to your solution explorer. Right click on your project and click on “Publish as Azure WebJobs”.

When you click on “Publish as Azure WebJob” following window will open. 

In profile click on “Microsoft Azure WebSites”. A new window will open.

If you are not logging in with “Microsoft Azure WebSites” then first login, then form “Existing WebSites” select your app and click Ok.

After clicking ok you will reach this window.

Click on publish, after clicking on publish your web jobs will be created.

Run your console application, after running your console application you can see your job host is started.

Now run post call of your Azure API from fiddler or postman. When your notification in queued successfully, your web jobs will run and you can see the result in your console application.

If an error occurs at the time of inserting value in table like, “An invalid API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of 2.0.0. in azure” then go to your “Azure web site” and go your mobile app and in settings click “Application Settings”and in “App Setting” add following key and value.

Key - MS_SkipVersionCheckvalue - true
Now you can check your table data.