Developing WebJobs using WebJobs SDK and .NET Framework 4.5

In the previous section, we saw how easily we can deploy any .NET Core console application as WebJobs on Azure. However, there is a limitation of WebJobs SDK, that is, it cannot run with .NET Core, hence, we have to stick with .NET framework 4.5.

WebJobs SDK provides built-in features that simplify complex plumbing and make it easy for developers to use and build them in less time. For example, to enable WebJobs SDK to listen to a queue or a service bus for the creation of any new items, we can just add any method in the functions class and specify the trigger attributes on a parameter that passes the object as JSON or XML (as configured) being inserted in the Azure queue.

To start with, install the Azure SDK, which installs some templates specific to Azure, and provides a new Azure WebJobs template to create the basic WebJob on the fly:

On selecting the Azure WebJob project template, it creates a Function class and initializes a JobHost to run the WebJob:

    var host = new JobHost(); 
host.RunAndBlock();

JobHost is the entry point of Azure WebJobs SDK and its primary purpose is to perform indexing, monitoring, and scheduling the functions defined using the WebJobs artifacts.

In the Function class, we can define static methods and define the storage, WebHook, and other trigger attributes that run whenever any change is made.

The following is an example that triggers this method whenever any queue item is added in the MessageQueue, where MessageQueue is the name of the queue created on Azure. We can achieve the complete event-based trigger by just adding the QueueTrigger attribute on the message parameter:

    public static void ProcessQueueMessage([QueueTrigger(
"testqueue")] String message, TextWriter log)
{
log.WriteLine(message);
}

Moreover, WebJobs are also smart in serializing the JSON response to the object if specified as a parameter. In the preceding code snippet, we have used the String parameter. However, this can be changed to an object if we needed some object to be serialized based on the JSON response. So, for example, if the JSON text receiving has an ID and Name, then we can define a POCO class in .NET, which can contain properties like ID and Name, and the signature will be as follows:

    public static void ProcessQueueMessage([QueueTrigger(
"testqueue")] Message message, TextWriter log)
{
log.WriteLine(message.Name);
}

There are many other triggers, such as FileTriggerAttribute, ErrorTrigger, and others, which you can check out in the WebJobs SDK documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.162.51