Sunday, 12 November 2017

configuration based queue or topic or subscription name for web job processing

In this post we are going to see how to make a configured based queue or topic or subscription name for webjob processing. for this we have to create a class which implements INameResolver interface.


using Microsoft.Azure.WebJobs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceConsole
{
    class WebJobNameResolver : INameResolver
    {
        public string Resolve(string name)
        {
            var resolvedName = ConfigurationManager.AppSettings[name];
            if (string.IsNullOrWhiteSpace(resolvedName))
            {
                throw new InvalidOperationException("Cannot resolve " + name);
            }
            return resolvedName;
        }
    }
}


Create a two keys in app.config file,specify this keyname in the ServicebusTrigger with covered by %%symbol

<add key="topicname" value="testTopic" />

<add key="subscriptionname" value="rajSubscription"/>

Then we have to change the queue name or topic name or subscription name with covered by %%
symbol.

[ServiceBusTrigger("%topicname%", "%subscriptionname%", AccessRights.Listen)]


using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceConsole
{
    public class SampleCreate
    {
        public SampleCreate()
        {

        }

        public async Task Process([ServiceBusTrigger("%topicname%", "%subscriptionname%", AccessRights.Listen)]BrokeredMessage message )
        {
            var data = message.GetBody<Model>();
            var username = message.Properties["Mac"];
            Console.WriteLine("read the message");           
        }
    }
}


Then we have to configure the webjob for resolve these names from our resolver which is created few minutes back. example : NameResolver = new WebJobNameResolver()


var config = new JobHostConfiguration {
                JobActivator = new UnityJobActivator(container),
                NameResolver = new WebJobNameResolver()
            };


config.UseServiceBus(new Microsoft.Azure.WebJobs.ServiceBus.ServiceBusConfiguration {
ConnectionString = ConfigurationManager.ConnectionStrings["ServiceBus"].ConnectionString
            });
         
           

            /* Run the webjob to listen for messages*/
            JobHost host = new JobHost(config);

            host.RunAndBlock();





From this post you can learn how to make a configuration based queue or topic or subscription name for webjob processing.