Creating And Deploying Microsoft Azure WebJobs

Introduction

What is Microsoft Azure WebJobs?

Azure WebJobs enable you to run programs or scripts in your website as background processes. It runs and scales as part of Azure Web Sites.

What Scheduling Options are supported by Microsoft Azure WebJobs?

Azure WebJobs can run continuously, on demand or on a schedule.

In what language/scripts are WebJobs written?

Azure WebJobs can be created using the following scripts:

  1. .cmd, .bat, .exe (using windows cmd)
  2. .ps1 (using powershell)
  3. .sh (using bash)
  4. .php (using php)
  5. .py (using python)
  6. .js (using node)

This article demonstrates the use of c# command line app.

Creating and Deploying WebJobs using Visual Studio

Creating WebJobs

In Visual Studio 2013 Update 3, WebJobs can be created and deployed directly from Visual Studio itself.

To get started, just create a new project, Under C#, select Microsoft Azure WebJobs. In this example, a "HelloTNWiki" project is created.

Microsoft azure website

A normal console application is created and the entry point to the program is Main(). This example shall just display "Hello TN Wiki!".

  1. class Program  
  2. {  
  3.    static void Main()  
  4.    {  
  5.       Console.WriteLine("Hello TN Wiki!");  
  6.    }  
  7. }  
Deploying WebJobs

To deploy the WebJob, right-click on the project and select Publish as Azure WebJob.

Publish as Azure WebJob

Select when the WebJob shall run and click OK. In this example, the job will be run on demand.

WebJob shall run

Select a publish target, in this example the target will be an Azure WebSite.

Azure WebSite


You shall be required to sign-in and enter your Microsoft Azure credentials

sign in

Once signed in, you may select in which WebSite the Job is to run.

WebSite the Job

Click on OK, then select Publish.

Publish web

Now, if you go the the Microsoft Azure portal, and navigate to your WebSite, you shall see a new WebJob created and deployed.

new WebJob created and deployed

Using previous versions of Visual Studio

Creating WebJobs

In Visual Studio, create a Console Application.

The entry point of the application is still Main(). This example shall just display "Hello TN Wiki!".

Console application
  1. class Program  
  2. {  
  3.    static void Main()  
  4.    {  
  5.       Console.WriteLine("Hello TN Wiki!");  
  6.    }  
  7. }  
Deploying WebJobs

The following steps need to be performed to deploy the WebJob:

 

  1. Build the application.

  2. Go to the Bin/Debug path of the Application and add all the contents in a .zip file.

    webjob folder

  3. Go to the Azure portal, select your WebSite, then go to WebJobs and select ADD a job.

    ADD a job

  4. Enter a Job name, select the .zip file, select when the job shall run and click ok.

    Enter a Job name

  5. Wait for the Job to be uploaded and created,

    uploaded and created

Running a Job and Viewing the result in WebJob Dashboard

Running a job

To run an on-demand WebJob as explained above, select the job and click on Save at the bottom of the page.
click on Save

When the run completes the result shall be displayed on the Last Run Result tab.

Last Run Result tab

WebJob Dashboard

The WebJobs dashboard in the Azure management portal provides powerful management capabilities that give you full control over the execution of WebJobs, including the ability to invoke individual functions within WebJobs.

The dashboard also displays function runtimes and output logs.

To access the dashboard page, click on the link under the Log Column.

access the dashboard page

This opens the dashboard page which contains details and statistics about the WebJob.

contains details

By selecting a specific run, statistics about the job together with the Job Log can be obtained.

As per the result of the example above, "Hello TN Wiki!" is displayed in the Job Log

toggle output

WebJobs SDK

The WebJobs SDK makes it easier to use Azure Storage.

The WebJobs SDK has a binding and trigger system which works with Microsoft Azure Storage Blobs, Queues and Tables as well as Service Bus Queues.

Installing the WebJob SDK

To use the WebJob SDK in Visual Studio, the following NuGet Package needs to be installed.

Using the SDK to create and save a file in an Azure Storage Account

Creating a Storage Account on Microsoft Azure

From the Azure Portal go to Data Services, Storage, Quick-Create and fill in the required information.

Once the storage account is provision, the next thing to do is to get the keys. Click on the Manage Keys button like the following:

Storage

Saving a file in Azure Blob storage

The following are the steps to save a string to a blob using C# code:

  1. Build the connection string using the keys retrieved above:
    1. string ConStr = "DefaultEndpointsProtocol=https;AccountName= xxx ;AccountKey=xxx ";  
  2. Create an instance of CloudStorageAccount. This represents a Windows Azure Storage account.
    1. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConStr);  
  3. Create an instance of CreateCloudBlobClient.

    Provides a client-side logical representation of the Windows Azure Blob service. This client is used to configure and execute requests against the Blob service.
    1. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
  4. Get a container in the Windows Azure Blob service. Create the container if it does not exist.

    This should be in lower case.
    1. CloudBlobContainer container = blobClient.GetContainerReference("blobcontainer");  
    2. container.CreateIfNotExists();  
  5. Gets a reference to a block blob in the container and upload a string text to it.
    1. CloudBlockBlob blob = container.GetBlockBlobReference("BlobFile.txt");  
    2. blob.UploadText("HelloTNWiki");  
  6. Run the WebJob.

    You may now view the created container in your Storage Account > Containers in the Azure Portal.

    chervinstorage

    By clicking on the container, you will be able to see the newly created Blob and its contents.

    blobcontainer

Example: Daily Sales

Having gone into the basics of Azure WebJobs, the following is an example where all the concepts can be used and applied.

Scenario

Consider a scenario where a sales WebApp is being deployed into Azure. The App stores sales information from several branches of a store.

The requirement is everyday at a specific time in the morning, compile the total sales per region, save the report on aBlob storage and email the report to the directors.

Assume the Database schema of the Application is like the following:

table

Retrieving Daily Sales from the Database

The code block below connects to an Azure Database, select and aggregates the sales information as required.

  1. public string GetDailySales(string date)  
  2. {  
  3.     dbconnect();  
  4.    
  5.     string SalesDetails = "";  
  6.    
  7.     try  
  8.     {  
  9.         string StrCommand = @"select region, sum(amount) AMOUNT  
  10.                             FROM SALES  
  11.                             WHERE TRANDATE= '" + date + "' group by region";  
  12.    
  13.         using (SqlCommand command = new SqlCommand(StrCommand, con))  
  14.         using (SqlDataReader reader = command.ExecuteReader())  
  15.         {  
  16.             while (reader.Read())  
  17.             {  
  18.                 SalesDetails = SalesDetails + reader.GetString(0) + "\t" + reader.GetInt32(1) + "</br>";  
  19.             }  
  20.         }  
  21.    
  22.    
  23.         con.Close();  
  24.     }  
  25.     catch (Exception e)  
  26.     {  
  27.         Console.WriteLine("Could not retrieve Information " + e.Message);  
  28.            
  29.         throw;  
  30.     }  
  31.    
  32.     Console.WriteLine("Information Retrieved Successfully");  
  33.    
  34.     return SalesDetails;  
  35. }  
E-Mail result

The next step is to send the results by mail. This is done by the following function:
  1. public void SendEmail(string msg)  
  2. {  
  3.     try  
  4.     {  
  5.         MailMessage mail = new MailMessage();  
  6.    
  7.         mail.From = new MailAddress(emailFrom);  
  8.         mail.To.Add(emailTo);  
  9.         mail.Subject = subject;  
  10.         mail.Body = msg;  
  11.         mail.IsBodyHtml = true;  
  12.    
  13.         using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))  
  14.         {  
  15.             smtp.Credentials = new NetworkCredential(emailFrom, password);  
  16.             smtp.EnableSsl = enableSSL;  
  17.             smtp.Send(mail);  
  18.             Console.WriteLine("Email sent to " +emailTo +" at " + DateTime.Now);  
  19.    
  20.         }  
  21.     }  
  22.     catch (Exception e)  
  23.     {  
  24.         Console.WriteLine("Email failed "+ e.Message);  
  25.         throw;  
  26.     }  
  27. }  
Saving the result in Blob Storage

The function below creates a container if it does not exist and save the result in a blob.
  1. public static void WriteToBlob(string salesreport)  
  2. {  
  3.     try  
  4.     {  
  5.         string acs = "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx";  
  6.    
  7.         CloudStorageAccount storageAccount = CloudStorageAccount.Parse(acs);  
  8.         CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
  9.         CloudBlobContainer container = blobClient.GetContainerReference("salesinfo");  
  10.         container.CreateIfNotExists();  
  11.         CloudBlockBlob blob = container.GetBlockBlobReference("DailyReport" + DateTime.Now + ".txt");  
  12.         blob.UploadText(salesreport);  
  13.    
  14.         Console.WriteLine("File saved successfully"); ;  
  15.    
  16.     }  
  17.     catch (Exception e)  
  18.     {  
  19.         Console.WriteLine("Saving to blob failed "+ e.Message);  
  20.            
  21.         throw;  
  22.     }  
  23. }  
View Result

Notice the use of Console.WriteLine() in each function. This shall help to trace the execution process and log errors in case of problems.

Thus the job log will be like the following:

web job run detail

E-Mail received successfully

daily sales report

Sales Info container created and sales report saved to blob.

Salesinfo

References

 

Recommended Free Ebook
Next Recommended Readings