Click here to Skip to main content
15,884,537 members
Articles / Hosted Services / Azure

Using CodeProject API in Azure Mobile Scheduled Jobs

Rate me:
Please Sign up or sign in to vote.
4.85/5 (5 votes)
3 Mar 2016CPOL7 min read 28.3K   140   7   1
Let us try to understand how to make use of CodeProject API within the Scheduled jobs in Windows Azure Mobile Services.

This article is an entry in our Microsoft Azure IoT Contest. Articles in this section are not required to be full articles so care should be taken when voting.

Introduction

Note - The Article code doesn't have any references to Nuget based libaries. I happend to delete those for one good reason that is, I really got shocked about the overall zipped size of the project. Yes, it's tremendous. What you have to do is, download and compile the source so that the Nuget references are downloaded and the project gets compiled.

In this article, I will walk you through the basics about Azure Mobile Scheduled jobs; how to create one and run tests to have a feel about it.

First let us have some basic understanding about scheduled jobs in Azure mobile and then we can move on to implement the same by making use of CodeProject API.

I will be discussing the below topics

Scheduled jobs basics

Scheduled jobs are tasks that run on background. These jobs run based on the how you define them as a part of the scheduling process. There are times you may need to perform background operations in Azure mobile services; here comes the Scheduler which comes in handy for running these background tasks as jobs that can be scheduled to run.

You may run a specific task at a regular interval of time (minute, hour, days, and month) or on demand. If you ask what kind of jobs that can be scheduled, you can run jobs starting with the simplest ones to complex recurring jobs.

One can run the scheduled jobs either inside or outside of the Azure. A very good example of a job that can run inside Azure is, say you wish to synch your Twitter updates or you wish to periodically data from a feed and update the same on your Azure storage.

Here are some of the use cases were you can use Scheduled jobs

  1. Periodically gather data and update the same in Azure.
  2. Cleaning up of logs.
  3. Run jobs for routine backups or archival of data.
  4. Run some application maintenance tasks.

Background

It's highly recommended to read through and understand the below mentioned article for CodeProject API Wrapper as this project makes use of the Wrapper.

http://www.codeproject.com/Articles/878994/Csharp-CodeProject-API-Wrapper

Create Azure Mobile Service

Create an Azure mobile project and deploy the same and test.

1) Log on to Windows Azure portal and click on "New" and navigate to Mobile services -> Create

CreateAzureMobile1

2) Key in the URL and then select or create a database, although we don’t use SQL Azure database for this project. Select the backend as .NET and proceed further to create an Azure mobile service.

CreateAzureMobile2

3) You should see a screen something like below. You can select the HTML/JavaScript option and download the code by clicking on "Create a new HTML App" link.

CreateAzureMobile3

Once you download and open up the solution, you should see a basic skeleton of a mobile service. We are interested in coding the Scheduled jobs. You can copy all the files that I have provided in the sample project download. Copy the source files for scheduled jobs and then copy the open the web.config of the sample project and copy paste the appsettings to your project. 

Note – The App settings has all the client Id and secret keys (CodeProject Test keys) so you can get started in testing the same.

Creating a Scheduled Jobs

Let us create a simple job which makes a HTTP Request to CodeProject API for gathering the articles and notification based on My API and do a service logging for time being. 

public class CodeProjectMyArticlesJob : ScheduledJob
{
        // The server base address
        private const string baseUrl = "https://api.codeproject.com/";

        // this will hold the Access Token returned from the server.
        static string _accessToken;

        /// <summary>
        /// Just Log the articles that we are reading through.
        /// </summary>
        /// <returns></returns>
        public async override Task ExecuteAsync()
        {
            try
            {
                _accessToken = ConfigurationManager.AppSettings["MyAPIAccessToken"];

                var codeProjectApiWrapper = new CodeProjectApiWrapper(baseUrl, _accessToken);
                var articles = await codeProjectApiWrapper.GetMyArticles();

                // My Articles
                foreach (var article in articles)
                {
                    Services.Log.Info(string.Format("Title: {0}", article.title));
                    foreach (var author in article.authors)
                    {

                        Services.Log.Info(string.Format("Authors: {0}", author.name));
                    }
                }
            }
            catch (Exception ex)
            {
                Services.Log.Info(ex.ToString());
            }
        }
}

Here’s the snapshot of how the Logs look like in Azure Mobile Services.

Logs

Below is the code snippet which will make a HTTP GET Request to CodeProject API and gets all the notifications for the specified Account Access Token which is based on your CodeProject Account.

public class CodeProjectMyNotificationJob: ScheduledJob
{
        // The server base address
        private const string baseUrl = "https://api.codeproject.com/";

        // this will hold the Access Token returned from the server.
        static string _accessToken;

        /// <summary>
        /// Just Log in if there’s any new Notifications.
        /// </summary>
        /// <returns></returns>
        public async override Task ExecuteAsync()
        {
            try
            {
                _accessToken = ConfigurationManager.AppSettings["MyAPIAccessToken"];

                var codeProjectApiWrapper = new CodeProjectApiWrapper(baseUrl, _accessToken);

                // My Notifications
                Services.Log.Info("Reading all my Notifications");
                var notificationRoot = await codeProjectApiWrapper.GetMyNotifications();
                var notifications = notificationRoot.notifications;

                if (notifications.Count == 0)
                    Services.Log.Info("There are no new Notifications");
                else
                {
                    foreach (var notification in notifications)
                    {
                        Services.Log.Info(string.Format("Subject: {0}", notification.subject));
                        Services.Log.Info(string.Format("Notification Date: {0}", notification.notificationDate));
                    }
                }
            }
            catch (Exception ex)
            {
                Services.Log.Info(ex.ToString());
            }
        }
}

Here’s the snapshot of the CodeProject Notification shown in the main website and the same is being show in the Azure Mobile service log.
CodeProjectNotification

NotificationJob

CodeProject Notification via SMS

Now let us slightly modify our previous code for notification to send SMS with the subject line for each of the notifications.

In order to send SMS rightly within the scheduler, we will be making use of Twilio SMS library. Please have a look into my previous article on about VOIP and SMS/MMS solution for IOT devices for more understanding about Twilio.

http://www.codeproject.com/Articles/877833/VOIP-and-SMS-MMS-solution-for-IOT-devices

Let us build a small Scheduler which can read through the CodeProject notification and can trigger an SMS. Notice below, we are using almost the same logic as we did previously. All we are trying to accomplish is to send SMS than just doing a service log.

Below are the steps for sending SMS.

  1. Install Twilio C# client library. You can search for "Twilio" in nugget package manager and install the same.
  2. Update the configuration file to have Twilio account SID, token etc. For sending SMS with Twilio, you will have to setup a dedicated Twilio number or can port your number. So we have an application configuration key for "TwilioNumber". Then you need to one more key for sending SMS number.
  3. Create an instance of TwilioRestClient with the Account SID and Account Key.
  4. Sending SMS is done in one line of code by making a call to SendMessage of TwilioRestClient instance by passing in from number, to number and a message to send that we code as Notification date and Notification subject line.
public class CodeProjectMyNotificationWithTwilioSmsJob: ScheduledJob
{
        // The server base address
        private const string BaseUrl = "https://api.codeproject.com/";

        // this will hold the Access Token returned from the server.
        static string _accessToken;

        /// <summary>
        /// Just Log in if there’s any new Notifications.
        /// </summary>
        /// <returns></returns>
        public async override Task ExecuteAsync()
        {
            try
            {
                _accessToken = ConfigurationManager.AppSettings["MyAPIAccessToken"];

                // set our AccountSid and AuthToken
                string accountSid = ConfigurationManager.AppSettings["AccountSid"];
                string authToken = ConfigurationManager.AppSettings["AuthToken"];
                string smsToSendNumber = ConfigurationManager.AppSettings["SmsToSendNumber"];
                string twilioNumber = ConfigurationManager.AppSettings["TwilioNumber"];

                // instantiate a new Twilio Rest Client with the Account SID and Token
                var twilioClient = new TwilioRestClient(accountSid, authToken);

                var codeProjectApiWrapper = new CodeProjectApiWrapper(BaseUrl, _accessToken);

                // My Notifications
                Services.Log.Info("Reading all my Notifications");
                var notificationRoot = await codeProjectApiWrapper.GetMyNotifications();
                var notifications = notificationRoot.notifications;

                if (notifications.Count == 0)
                    Services.Log.Info("There are no new Notifications");
                else
                {
                    foreach (var notification in notifications)
                    {
                        var message = string.Format("{0} - {1}", notification.notificationDate,
                            notification.subject);

                        twilioClient.SendMessage(
                            twilioNumber,    // From number, must be an SMS-enabled Twilio number
                            smsToSendNumber, // To number is the phone which you wish the SMS.
                            message);        // message content
                    }
                }
            }
            catch (Exception ex)
            {
                Services.Log.Info(ex.ToString());
            }
        }
}

Publish Azure Mobile Service

You can compile the project and once everything is building, it’s the time to see how we can deploy the Azure mobile service.

  1. Right click on Project and select "Publish" option, which will open up a window like below. A very easy approach in selecting the publish target is the first option.

PublishToAzureMobile1

2) When you select the first option for publish target, it lets you to log in to Windows Azure so that you can select the exisitng mobile service that you have created. 

PublishToAzureMobile2

3) When you click OK button in step 2, you will see the below screen, shows all the information the server and credentials for publishing. You can click on validate connection just to check if everything is fine and ready for publishing. 

PublishToAzureMobile3

4) Clicking on next button, will show the below window. You don’t have to do anything, just leave the default selections. 

PublishToAzureMobile4

5) Clicking next, will show the final window where you can preview the things which gets published and then hit the publish button, which will publish your Azure mobile service. 

PublishToAzureMobile5

Create Scheduled Job

Now that we have published the Azure mobile service, it’s time to create scheduled jobs and run the same and see the results.

1)  Select the "Scheduler" option within your Azure mobile service. 

CreateJobs1

2) Specify job name. The job name is nothing but the scheduled job class name that you had created which ends with "Job". For example, we have created a class named "CodeProjectMyArticlesJob" then the job should be named as "CodeProjectMyArticles".

Select "On demand" option so that we can manually run and see the results in no time.

CreateJobs2

3) You should see something like below with the status set to "Disabled" for on demand jobs. 

CreateJobs3

Run Scheduled Job

Now that we have created a scheduled job, it’s the time to run. Just hit the "Run Once" button as show below, it will trigger the scheduler to run the job.

RunJob

Verify Scheduled Job Response

Now it’s the time to verify the service log to see the output of the above scheduled job for fetching the CodeProject My API articles. You should see something like below.

The service log currently shows all the articles that I had published in CodeProject.

Logs

Points of Interest

I was very much excited about the new Scheduler. Now that we have so many options to do background jobs. Ofcourse a lot of things I am daily playing and leaning with Azure. 

I just wondered the simplicity and the easiness of creating a powerful scheduled jobs. Well, I don't have any words to say. I am much impressed with the new Azure functionalities. 

History

Versions 1.0 - Published the initail version of the article explaining what is a scheduled job, how to created one in Azure mobile service, deploy and run the same on Azure. - 02/23/2015

License

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


Written By
Web Developer
United States United States
Profile

Around 10 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.

In Brief

Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.

Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF

Software Development

Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI

Healthcare Domain Experience

CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability

Education

B.E (Computer Science)

CodeProject Contest So Far:

1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro

2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics

3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin

4. Intel App Innovation Contest 2013 - eHealthCare

5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Contest 2014

6. Grand Prize Winner of CodeProject Android Article Contest 2014

7. Grand Prize Winner of IOT on Azure Contest 2015

Comments and Discussions

 
Questionroadmap Pin
kiquenet.com24-May-16 1:47
professionalkiquenet.com24-May-16 1:47 

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.