Skip to main content

Service Bus Topics - How to use it (part 1)

In the last post we saw find out what is a Service Bus Topics. Next step that we should to do is to see how we can use it. From a lot of perspective, it is similar to Service Bus Queues.
The first thing that we need here is a Service Namespace. This is a unique named used to identify or service. The same namespace can be used for Service Bus Topics and Service Bus Queue without any kind of problems. To create a new namespace from the Azure portal, we should go Service Bus section. From there we have the possibility to create a new namespace. After the namespace is created we should be able to access it and see in the properties list the “Default Issuer” and “Default Key”. This information is needed to be able to consume and access a Service Bus Topics.
After we have the namespace created we need to configure the application to be able to access these services. In an application, this information can be stored in different locations, depending on our needs and preferences. The simplest one is to hardcode this value in our application, but is not the best one. If we create a website we can use configuration file of our web application to store this information.
<configuration>
    <appSettings>
        <add
                key="ServiceBusConnectionString"
value="Endpoint=sb://myFooNamespace.servicebus.windows.net/;SharedSecretIssuer=myFooIssuerName;SharedSecretValue=myFooDefaultKey" />
    </appSettings>
</configuration>
In the case you are working with a web-role or with a worker role, a good idea is to save this information in the service definition file (*.csdef and *.cscfg).
<WebRole name="FooWebRole" vmsize="Medium">
        <ConfigurationSettings>
            <Setting name="ServiceBusConnectionString" />
        </ConfigurationSettings>
</WebRole>

<Role name="FooWebRole"
        <ConfigurationSettings>
            <Setting name="ServiceBusConnectionString"
                     value=="Endpoint=sb://myFooNamespace.servicebus.windows.net/;SharedSecretIssuer=myFooIssuerName;SharedSecretValue=myFooDefaultKey"  />
        </ConfigurationSettings>
</Role>
Another possible solution is to store this information in a separately file, that can be consume by our application. In this case when we will create the instance of Service Bus Topics we will need to be able to specify this data. Basically, this information can be stored in any location from our application. We can even hardcoded this in our code – but please, don’t do this.
Remarks: If you read the posts about Service Bus Queues, you will notify that this configuration is the same. This happens because the entry point for Topics and Queues in Windows Azure are represented by the same “service”.
For creating a topic we have two options. We can create one from portal. We need to go to the portal, select our namespace from Service Bus and we will see that we have a new button there that permits us to create a new topic (or queue). It is not very insetting in this way. The other option is to create it from code.
From code, first of all we need to create a new instance of NamespaceManager. Yes, the same NamespaceManager that we used for Service Bus Queues. After this, we can create the Topic directly or check if it exists.
var namespaceManager =
    NamespaceManager
        .CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));

if (!namespaceManager.TopicExists("myFooTopic"))
{
    namespaceManager.CreateTopic("myFooTopic");
}
We should check if the topic already exists. Otherwise, a MessagingEntityAlreadyExistsException exception will be throwed by the service. Also, the name of the topic should respect the following rules:
  • Character that are accepted are: ‘a’-‘z’, ’A’-‘Z’, ‘-‘, ‘.’, ‘0’-‘9’
  • It should start with a character
If we want to specify some custom property to the topic, for example the TTL of the messages or the size of the topic, this can be done in the moment when we create the topic using TopicDescription.
TopicDescription topicDescription = new TopicDescription("myFooTopic")
{
    DefaultMessageTimeToLive = new TimeSpan(0, 1, 0)
};
...
namespaceManager.CreateTopic(topicDescription);
Creating a topic is quite simple. Creating a message for a topic is simple as well. We need to create a BrokeredMessage and send to the topic (yes, the same BrokeredMessage class that is used in Service Bus Queues – pretty cool). To handle a topic, we need to create a new instance of TopicClient.
TopicClient topicClient = TopicClient.CreateFromConnectionString(
    CloudConfigurationManager.GetSetting("ServiceBusConnectionString"),
    "myFooTopic");
BrokeredMessage message = new BrokeredMessage();
message.Properties["myCustomProperty"] = 1234;
topicClient.Send(message);
Receiving messages from Topics, is also simple, but before this we should talk about subscriptions and filters. This will be done tomorrow in more details.
In conclusion we saw how we can create namespace, Service Bus Topics and how we can send messages to these topics. Keep in mind that a message that is added to a topic is simple a BrokeredMessage.
Part 2

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...