How to write to Azure Event Grid Topic in Azure Function

I noticed that, all of the sudden, Topics are no longer available as part of Service Bus. Is it possible to write a message to an Event Grid Topic within an Azure Function?

1 answer

  • answered 2018-09-16 00:02 Roman Kiss

    The following code snippet is an example of the using an azure function for pushing a telemetry stream to the eventing model:

    enter image description here

    #r "Microsoft.ServiceBus"
    #r "Newtonsoft.Json"
    using System.Configuration;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.ServiceBus.Messaging;
    using Newtonsoft.Json;
    // reusable client proxy
    static HttpClient client = HttpClientHelper.Client(ConfigurationManager.AppSettings["TopicEndpointEventGrid"], ConfigurationManager.AppSettings["aeg-sas-key"]);
    // AF
    public static async Task Run(EventData ed, TraceWriter log)
        log.Info($"C# Event Hub trigger function processed a message:{ed.SequenceNumber}"); 
        //foreach(var prop in ed.SystemProperties)
        //   log.Info($"{prop.Key} = {prop.Value}");
        // fire EventGrid Custom Topic
        var egevent = new 
            Id = ed.SequenceNumber.ToString(),
            Subject = $"/iothub/events/{ed.SystemProperties["iothub-message-source"] ?? "?"}/{ed.SystemProperties["iothub-connection-device-id"] ?? "?"}",
            EventType = "telemetryDataInserted",
            EventTime = ed.EnqueuedTimeUtc,
            Data = new
                sysproperties = ed.SystemProperties,
                properties = ed.Properties,
                body = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(ed.GetBytes()))
        await client.PostAsJsonAsync("", new[] { egevent });  
    // helper
    class HttpClientHelper
        public static HttpClient Client(string address, string key)
            var client = new HttpClient() { BaseAddress = new Uri(address) };
            client.DefaultRequestHeaders.Add("aeg-sas-key", key);
            return client;      

    the function.json:

          "bindings": [
             "type": "eventHubTrigger",
             "name": "ed",
             "direction": "in",
             "path": "myIoTHubName",
             "connection": "connectionstringIOTHUB",
             "consumerGroup": "eventing",
             "cardinality": "many"
          "disabled": false

    Note, that the payload for the AEG Custom Topic is depended from its inputSchema property. Basically, current AEG version (included also preview) allows to declare an input schema from the following selection:

    • EventGridSchema (default schema)
    • CloudEventV01Schema
    • CustomEventSchema (still in the preview)

    more details can be found: