Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

.NET Core QueueMessage JSON to Typed Object. Using Azure.Storage.Queues

$
0
0

The documentation around .NET QueueMessage is a little fuzzy so depending on the version of your NuGet libraries might differ in properties. This article uses the Azure.Storage.Queues, Version=12.7.0.0.

If you, like me, have systems writing JSON messages to the queue, you also struggle with converting these queue messages back to an object when reading from the queue.

But with a little help from NewtonSoft, it does not have to be that difficult.

Imagine that you wish to get this simple message from the queue:

A simple JSON message added to the queue via Visual Studio

This message can be mapped to this class:

using Newtonsoft.Json;

namespace MyCode
{
  public class HelloWorld
  {
    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }
  }
}

CHALLENGE #1: IS THE CONTENT ENCODED?

Now, when you read the message from the queue, you might get a surprise, as the original message is nowhere to be seen:

The message in the MessageText property?

Yes, when adding messages from Visual Studio, the contents is base 64 encoded. So first the message needs to be decoded, and then converted into an object.

THE EXTENSION METHOD:

This extension method will do the heavy lifting for you:

using Azure.Storage.Queues.Models;
using Newtonsoft.Json;
using System;
using System.Text;

namespace MyCode
{
  public static class QueueMessageExtensions
  {
    public static string AsString(this QueueMessage message)
    {
      byte[] data = Convert.FromBase64String(message.MessageText);
      return Encoding.UTF8.GetString(data);
    }

    public static T As<T>(this QueueMessage message) where T : class
    {
      byte[] data = Convert.FromBase64String(message.MessageText);
      string json = Encoding.UTF8.GetString(data);
      return Deserialize<T>(json, true);
    }

    private static T Deserialize<T>(string json, bool ignoreMissingMembersInObject) where T : class
    {
      T deserializedObject;
      MissingMemberHandling missingMemberHandling = MissingMemberHandling.Error;
      if (ignoreMissingMembersInObject)
        missingMemberHandling = MissingMemberHandling.Ignore;
      deserializedObject = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings { MissingMemberHandling = missingMemberHandling, });
      return deserializedObject;
    }

  }
}

USAGE:

// This is an arbitrary class that returns a list of messages from 
// an Azure Queue. You have your own class here
IEnumerable<QueueMessage> messages = await _queueRepository.Get();

foreach (var message in messages)
{
  // Use the extension method to convert the message to the
  // HelloWorld type:
  var obj = message.As<HelloWorld>();
  // You can now access the properties:
  _logger.LogInformation($"{obj.Title}, {obj.Text}");
}

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles