2

I am trying to get into dotnet and Azure and so I build small solution that triggers a azure function by http with a count that then requests the given amount of cat facts from a public api, stores them in a cosmos db and, if the fact is not in my database, dispatches an Event Grid event.

My trouble is about serializing the data for the event and then deserializing it in my event handler.

The data model

public class CatFactDatabaseModel
{
    [JsonProperty("id")]
    public string? Id;

    [JsonProperty("category")]
    public string? Category;

    [JsonProperty("value")]
    public string? Value;

    [JsonProperty("valueHash")]
    public string? ValueHash;
}

The way I pass data to the event

foreach (var item in dbUpdateItems)
{
    var i = JsonConvert.SerializeObject(item);
    log.LogInformation($"SERIALIZED ITEM: {i}");
    var e = new EventGridEvent("add-catFact", "add-catFact", "1.0", i);
    await collector.AddAsync(e);
}

where dbUpdateItems is a list of CatFactDatabaseModel.

The code to deserialize the Event

public static void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
{
    var any = JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
    var data = JsonConvert.DeserializeObject<CatFactDatabaseModel>(any.ToString());
    log.LogInformation($"Added message was {data.Value}");
}

The Question is:

Why do I need to deserialize the EventGridEvent twice?

I tried to skip the serializing in the event creating, but then I just get empty data in the event. If I deserialize only once into CatFactDatabaseModel, I get errors. If I deserialize without a type, it becomes an escaped string.

I tried to read the data as JObject instead of EventGridEvent, but that turns out the be the same with extra steps.

I tried to deserialize with

var data = eventGridEvent.Data.ToObjectFromJson<CatFactDatabaseModel>();

but it's not working either This is the only way it turned out as an actual, non empty object of type CatFactDatabaseModel, but I don't think this is how it is supposed to be.

I think the actual error is on the event creation part, but I could not find a solution with the documentation or googling stuff.

What am I doing wrong?

xtp
  • 119
  • 1
  • 11
  • [Not the answer] Thank you for your question. I was struggling a lot with it. Thx for telling that Eventgrid serialize twice and one needs to be de-serialized twice. I was doing this earlier with my custom event and sending via HTTP client. Httpclient way was working fine. I started using event grid SDK, as I want to go away with secret, and it is only supported using EventGrid SDK, and landed these issues. It sounds like the event grid SDK needs some improvement. Share Edit Undelete Flag – Vikrant Aug 05 '23 at 02:00

0 Answers0