Skip to main content

Windows Azure Service Bus - Adding properties to the BrokeredMessage automatic

Some days ago I started to look over a big system and trying to identify places where Windows Azure can be used. Trying to imagine a PoC I realized that I need a mechanism that is able to add properties to a BrokeredMessage automatically.
For example we can have a serializable item that is added to the BrokeredMessage. This message can have one, two or n properties that we want to add them to the BrokeredMessage. These properties will be used by the topics and subscription to filter and redirect each message.
This target can be accomplished in different ways:
  1. Our object can contain a method that returns the list of properties as KeyValuePair. This can be used to populate the Properties of the BrokeredMesssage.
  2. Another option is to create a separate class that store the list of properties for each class and to call an external method that will populate our BrokeredMessage with our custom properties.
  3. Create a custom attribute that will be used to mark properties that will be added to the BrokeredMessage. After adding our object to the BrokeredMessage, we will need to call another method that will processed our object and add the marked properties to the BrokeredMessage.
Each solution has good parts and bad parts. Also, based on the developer preference and the project characteristics, each team can prefer a different solution.
Using the first option has the downside that we create a coupling between our class and Windows Azure. Even if is not directly, the method will be relevant only for Windows Azure. If we want to reuse these classes, maybe we don’t want to load the class with a lot of methods.
The second option creates a clear decoupling between the item that is sent using BrokeredMessage and the system. The downside of is on the configuration part. We need to manage a separate configuration for items that will be added on the BrokeredMessage. Also we will need to create a mechanism that will read the configuration and extract from each item the properties that need to be exposed in the BrokeredMessage.
The last option creates a small coupling between our item and the mechanism that sends the message on the wire. In comparison with the first and the second option, this option in somehow in the middle. It will not add to much complexity to our project. The only problem that I see here is the reflection mechanism that needs to be used to retrieve the properties that need to be exposed in the BrokeredMessage.
I will take the last option that I will try to cover. To be able to develop a mechanism that automatically add the properties of BrokeredMessage the properties of an items that are marked with a custom properties we will need to create two things
  1. A custom attribute that will be used to mark the properties of our item
  2. Decorate our item properties with our custom attribute.
  3. A function that will extract the properties that are marked with our custom attribute and add them to the properties list of the BrokeredMessage
We need to create our attribute. This attribute will be used only on the properties that need to be exposed in the BrokeredMessage. Using the AttributeUsage attribute we will limit the places where our attribute can be used – only on properties.
[AttributeUsage(AttributeTargets.Property)]
public class ExposedProperty : System.Attribute
{
    private string name;

    public ExposedProperty(string name)
    {
        this.name = name;
    }
}
In this moment we have our attribute that can be used on the properties of our item that we want to expose.
public class Item
{
        [ExposedProperty( “name”, PropertyDirection.ReadAndWrite))]
        public string Name { get; set; }

        public int Age { get; set; }

        [ExposedProperty( “job” , PropertyDirection.ReadAndWrite))]
        public string Job { get; set; }

        public double Salary { get; set; }

}
As you can see we can have different properties names (one in our Item class and another one that is used in the BrokeredMessage). This can be very useful when we exposed different object that are coming from different sources. The PropertyDirection specify the direction of data. This is not mandatory, but can be useful and also tell us the direction of data.
The last step that we need to do is to write a method that will extract all the properties that are decorated with our custom attribute and add them to our BrokeredMessage.
public void AddCustomProperties(BrokeredMessage message, object item)
{
    Type exposedPropertyType = typeof(ExposedProperty);
    PropertyInfo[] itemProperties = serializableObject.GetType().GetProperties();
    foreach (PropertyInfo property in itemProperties)       
    {
        foreach (ExposedProperty exposedProperty in property.GetCustomAttributes(exposedPropertyType, true))
        {
            var propertyValue = property.GetValue(item, null);
            message.Properties.Add(exposedProperty.Name, propertyValue);
        }
    }
}
In this moment we have all that we need to add our item and all the custom properties to the BrokeredMessage. In the following example we are adding the item to the BrokeredMessage.
Item item = new Item();
...

SubscriptionClient subscriptionClient = SubscriptionClient.CreateFromConnectionString(
    CloudConfigurationManager.GetSetting("ServiceBusConnectionString"),
    "myFooTopic",
    "Property1Equal10");
BrokeredMessage message = subscriptionClient.Receive();
Sending the message to our subscribers:
BrokeredMessage message = new BrokeredMessage(item);
AddCustomProperties(message,item);
topicClient.Send(message);
In this way we will be able to define filters over the subscription using our custom properties. The downside of this solution is the way we het the list of properties that are decorated with our custom attribute – using reflection. Reflection is a very expensive mechanism. Because our machines and servers are very fast, based on the case, this may or not may be a problem.

Comments

Popular posts from this blog

Why Database Modernization Matters for AI

  When companies transition to the cloud, they typically begin with applications and virtual machines, which is often the easier part of the process. The actual complexity arises later when databases are moved. To save time and effort, cloud adoption is more of a cloud migration in an IaaS manner, fulfilling current, but not future needs. Even organisations that are already in the cloud find that their databases, although “migrated,” are not genuinely modernised. This disparity becomes particularly evident when they begin to explore AI technologies. Understanding Modernisation Beyond Migration Database modernisation is distinct from merely relocating an outdated database to Azure. It's about making your data layer ready for future needs, like automation, real-time analytics, and AI capabilities. AI needs high throughput, which can be achieved using native DB cloud capabilities. When your database runs in a traditional setup (even hosted in the cloud), in that case, you will enc...

Cloud Myths: Migrating to the cloud is quick and easy (Pill 2 of 5 / Cloud Pills)

The idea that migration to the cloud is simple, straightforward and rapid is a wrong assumption. It’s a common misconception of business stakeholders that generates delays, budget overruns and technical dept. A migration requires laborious planning, technical expertise and a rigorous process.  Migrations, especially cloud migrations, are not one-size-fits-all journeys. One of the most critical steps is under evaluation, under budget and under consideration. The evaluation phase, where existing infrastructure, applications, database, network and the end-to-end estate are evaluated and mapped to a cloud strategy, is crucial to ensure the success of cloud migration. Additional factors such as security, compliance, and system dependencies increase the complexity of cloud migration.  A misconception regarding lift-and-shits is that they are fast and cheap. Moving applications to the cloud without changes does not provide the capability to optimise costs and performance, leading to ...

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...