How To Create Service Bus Triggered WebJob In .Net Core

Introduction 

In this article, we will learn about how to create a Web Job using .Net Core with Service bus triggered.

Prerequisite 

  • Microsoft Azure account.
  • .Net Core 3.1
  • Visual Studio 2019 will be preferable.

What is Web Job

Web Job is something like a scheduler. We can set functionality to run in a specific interval of time or we can trigger a Web job when a new message came in Message Queue. We can trigger a web job in three different ways. Web Jobs can be triggered on Queue, Service Bus, Blob, etc. Here I giving some detail to create ServiceBus Trigger.

We can split code based on the following,

  • Web job creation 
  • Sending a message to Queue to trigger Web job
  • Debugging and check 

Web Job creation 

Step 1

Create Azure ServiceBus namespace from Azure Portal (www.Portal.azure.com).

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

After creating Service Bus Namespace, 

Step 2

Create a .Net Core - C# Console application. The framework you can select is .Net Core 3.1.

Step 3

Add "Javascript JSON Configuration File". Specify the file name as "appsettings.json". Right-click and select the Properties of "appsettings.json" and Select "Copy To Output Directory" = "Copy If Never".

For taking ServiceBus ConnectionString, Navigate to Service Bus > Shared access policiesRootManageSharedAccessKeyPrimary Connection String > click on the copy button on the right side of the text box.

How To Create Service Bus Triggered WebJob in dotNet Core

{
  "AzureWebJobsServiceBus": "<Place Your Service Bus Primary Connection String Here>"
}

Step 4

Open Program.cs and add the following namespace.

using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

You can use the following command to install the package on NuGet Package Manager Console ( First package is for -> HostBuilder() | 2nd is for -> AddServiceBus() ).

PM> Install-Package Microsoft.Azure.WebJobs.Extensions -version 4.0.1
PM> Install-Package Microsoft.Azure.WebJobs.Extensions.ServiceBus -IncludePrerelease

 Add the following code for creating a Host,

class Program {
    static async Task Main() {
        var hostBuilder = new HostBuilder();
        hostBuilder.ConfigureWebJobs((context, builder) => {
            builder.AddServiceBus(options => options.MaxConcurrentCalls = 1);
        });
        var host = hostBuilder.Build();
        using(host) {
            await host.RunAsync();
        }
    }
}

Step 5

Add a Class file named Functions.cs. Add the following namespaces.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

Install the package using the following commands. The following command is for installing Logging methods. Microsoft.Azure.WebJobs, is already a part of the previously installed package.

PM> Install-Package Microsoft.Extensions.Logging.Console -version 5.0.0

Use the following code for triggering a function, when any message is in the service bus message queue.

public class Functions {
    public static void processservicebus([ServiceBusTrigger("webjob1", Connection = "AzureWebJobsServiceBus")] string myQueueItem, ILogger log) {
        log.LogInformation(myQueueItem);
    }
}

You have to remember the Queue name (Queue name you can use any string), whatever you are giving here same needs to give in the Client-side method also.

Sending a message to Queue to trigger Web job

Now we can go ahead and create code to send messages.

Step 1

Create another Net Core - C# Console application. The framework you can select is .Net Core 3.1.

Step 2

Open Program.cs and add the following namespace.

using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using System.Text.Json;

And use the following code to send messages.

public class Program {
    static string connectionString = "<Place your ServiceBus Connection String Here>";
    private static ServiceBusClient _client;
    private static ServiceBusSender _clientSender;
    private
    const string QUEUE_NAME = "webjob1"; // It should be as same as queue name given in the Host creation time
    static async Task Main() {
        _client = new ServiceBusClient(connectionString);
        _clientSender = _client.CreateSender(QUEUE_NAME);
        Messages objMessage = new Messages() {
            MessageId = 1, Subject = "First Message"
        };
        string messagePayload = JsonSerializer.Serialize(objMessage);
        ServiceBusMessage message = new ServiceBusMessage(messagePayload);
        await _clientSender.SendMessageAsync(message).ConfigureAwait(false);
    }
    public class Messages {
        public int MessageId {
            get;
            set;
        }
        public string Subject {
            get;
            set;
        }
    }
}

All codes are done for the creation of Host and sending messages to Message Queue. Once any new message came in the Message Queue, then the following function will trigger automatically.

public static void processservicebus([ServiceBusTrigger("webjob1", Connection = "AzureWebJobsServiceBus")] string myQueueItem,ILogger log)

You can use the same implementation in your project to achieve something like, when a new file user uploads into your application, then you need to insert records from that file into the system with some validation. So that you can do, Once any new file came into the application then you can send those file detail as a Message and Process that file. You can call the file processing method inside the above method.

Debugging and check 

Step 1

Right-click on your Host Project and select Debug > Start New Instance.

How To Create Service Bus Triggered WebJob in dotNet Core

Then the following console is to be loaded. By this step, we can assume that our Webjob is up.

How To Create Service Bus Triggered WebJob in dotNet Core

Put a breakpoint in the following method,

public static void processservicebus([ServiceBusTrigger("webjob1", Connection = "AzureWebJobsServiceBus")] string myQueueItem,ILogger log)

Step 2

Now the same way you can start a Message sending console application also. Once that is up (message is sent), then you will get a call in the above method.

Publishing Web Job

You can publish your Web job from the Visual studio itself. Please follow the following steps. We are publishing Web Job into App Service.  If we are going with the below step, then there is an option to create App Service (in the 3rd screenshot).

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

If you are choosing Azure Portal to create and Publish a Web Job then follow the following steps.

Add App Service

How To Create Service Bus Triggered WebJob in dotNet Core

Click on the App Service you created. And select Web Job from the Left side menu.

How To Create Service Bus Triggered WebJob in dotNet Core

Click on "+ Add". Give Web Job Name. In the File Upload section, you can select the Exe file from the Release folder of the Host Project. And you can give Type Triggered and Triggers = Manual.

How To Create Service Bus Triggered WebJob in dotNet Core

This will create a Web job for you.

Go to Advanced Tool > Go.

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

How To Create Service Bus Triggered WebJob in dotNet Core

Click on Site > wwwroot > AppData > jobs > triggered > Open the folder <same name as Web Job>.

How To Create Service Bus Triggered WebJob in dotNet Core

Now you can drag and drop all DLL into that folder.

Conclusion

In this article, we learned the basic steps of how to create a Web Job that is triggered by Service Bus and how we can publish code to Azure.


Similar Articles