Skip to main content

Creating and Deploying Microsoft Azure WebJobs

Azure WebJobs enables you to run programs or scripts in your website as background processes. It runs and scales as part of Azure Web Sites.
This article focuses on the basics of WebJobs before demonstrating an example where it can be used.

This article is also available on the Mirosoft TechNet Wiki.
This article was highlighted in the The Microsoft TechNet Guru Awards! (October 2014).


What is Microsoft Azure WebJobs?
Azure WebJobs enables 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 is 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)
In this article, the use of c# command line app shall be demonstrated.

Creating and Deploying WebJobs using VS 2013 Update 3

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.

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

class Program
    static void Main()
        Console.WriteLine("Hello TN Wiki!");

Deploying WebJobs

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

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

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

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

Once signed in, you may select in which WebSite the Job Shall runs.


Click on OK, then select Publish.

Now, if you go the the Microsoft Azure portal, and navigate to your WebSite, you shall see a 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!".

class Program
    static void Main()
        Console.WriteLine("Hello TN Wiki!");

Deploying WebJobs

The following steps needs to be performed to deploy the WebJob:
1. Build the application
2. Go the the Bin/Debug path of the Application and Add all the contents in a .zip file.

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

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

5. Wait for the Job to be uploaded and created

Running a Job and Viewing the result in WebJob Dashboard

Running a job

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

When the run completes, The result shall be displayed on the 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.

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

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

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 below

Saving a file in Azure Blob storage

Below are the steps to save a string to a blob using C# code
1. Build the connection string using the keys retrieved above
string ConStr = "DefaultEndpointsProtocol=https;AccountName= xxx ;AccountKey=xxx ";

2. Create an instance of CloudStorageAccount. This Represents a Windows Azure Storage account.
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.
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 .  

CloudBlobContainer container = blobClient.GetContainerReference("blobcontainer");

5. Gets a reference to a block blob in the container and Upload a string text to it.
CloudBlockBlob blob = container.GetBlockBlobReference("BlobFile.txt");

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

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

Example: Daily Sales

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


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 below

Retrieving Daily Sales from the Database

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

public string GetDailySales(string date)
    string SalesDetails = "";
        string StrCommand = @"select region, sum(amount) AMOUNT
                            FROM SALES
                            WHERE TRANDATE= '" + date + "' group by region";
        using (SqlCommand command = new SqlCommand(StrCommand, con))
        using (SqlDataReader reader = command.ExecuteReader())
            while (reader.Read())
                SalesDetails = SalesDetails + reader.GetString(0) + "\t" + reader.GetInt32(1) + "</br>";
    catch (Exception e)
        Console.WriteLine("Could not retrieve Information " + e.Message);
    Console.WriteLine("Information Retrieved Successfully");
    return SalesDetails;

E-Mail result

The next step is to send the results by mail. This is done by the function below
public void SendEmail(string msg)
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(emailFrom);
        mail.Subject = subject;
        mail.Body = msg;
        mail.IsBodyHtml = true;
        using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            smtp.Credentials = new NetworkCredential(emailFrom, password);
            smtp.EnableSsl = enableSSL;
            Console.WriteLine("Email sent to " +emailTo +" at " + DateTime.Now);
    catch (Exception e)
        Console.WriteLine("Email failed "+ e.Message);

Saving the result in Blob Storage

The function below creates a container if it does not exist and save the result in a blob
public static void WriteToBlob(string salesreport)
        string acs = "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx";
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(acs);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("salesinfo");
        CloudBlockBlob blob = container.GetBlockBlobReference("DailyReport" + DateTime.Now + ".txt");
        Console.WriteLine("File saved successfully"); ;
    catch (Exception e)
        Console.WriteLine("Saving to blob failed "+ e.Message);

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 below

E-Mail received successfully

Sales Info container created and sales report save to blob.



Popular posts from this blog

Creating and Querying Microsoft Azure DocumentDB

DocumentDB is the latest storage option added to Microsoft Azure.
It is a no-sql storage service that stores JSON documents natively and provides indexing capabilities along with other interesting features.

This article is available available on theMicrosoft Technet Wiki. This article was highlighted in theTop Contributor awardson the 12th of October 2014. This article was highlighted in the TNWiki Article Spotlight. This article was highlighted in the The Microsoft TechNet Guru Awards! (October 2014).

DocumentDB is the latest storage option added to Microsoft Azure.
It is a no-sql storage service that stores JSON documents natively and provides indexing capabilities along with other interesting features.
This wiki shall introduce you to this new service.

Setting up a Microsoft Azure DocumentDBGo to the new Microsoft Azure Portal. 

 Click on New > DocumentDB

Enter A Database ID and hit Create!

Query Unstructured Data From SQL Server Using PolyBase

Scope The following article demonstrates how unstructured data and relational data can be queried, joined and processed in a single query using PolyBase, a new feature in SQL Server 2016. Pre-RequisitesIntroduction to Big Data Analytics Using Microsoft Azure Big Data Analytics Using Hive on Microsoft Azure Analyze Twitter Data With Hive in Azure HDInsight Running Hadoop on Linux using Azure HDInsight  Introduction Traditionally, Big Data is processed using Apache Hadoop which is totally fine. But what if the result of this needs to be linked to the traditional Relation Database? For example, assume that from the analysis of tons of application logs, marketing needs to contact some customs that faced problems in an application following a failure in the application.
This problem is solved with PolyBase. PolyBase allows you to use Transact-SQL (T-SQL) statements to access data stored in Hadoop or Azure Blob Storage and query it in an ad-hoc fashion. It also lets you query semi-structure…