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

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