Thursday 8 June 2023

Publish events to Azure Event Grid Topic using c# console app

In this aticle I explained how to publish events to Azure Event Grid Topic using C# console app.

 Steps to publish Events to Event Grid Topic

· Create a azure function using Azure Event Grid Trigger template.

· If you haven't previously used Event Grid in your Azure subscription, you may need to register the Event Grid resource provider.

· Create an event grid topic provides a user-defined endpoint that you post your events to.

· You subscribe to an event grid topic to tell Event Grid which events you want to track, and where (azure function) to send the events.

· Publish an event to Event Grid Topic using URL and KEY of the custom topic created (using postman or event publisher client console app).

 

Publish Events to EventGrid Topic

  • First if all install Azure and EventGrid packages and include the below ref.

        using Azure;

        using Azure.Messaging.EventGrid;

 

  • Declare and Event Grid Topic’s end point and public key:

        private const string topicEndpoint = "copy and paste here Topic end points";

        private const string topicKey = "Copay and paste here public key

 

  • Create Event Grid Publisher Client using credentials

        static Uri endpoint = new Uri(topicEndpoint);

        static AzureKeyCredential credential = new AzureKeyCredential(topicKey);

        static EventGridPublisherClient client = new EventGridPublisherClient(endpoint, credential);

 

  • Now create EventPublisher method to post events to Event Grid Topic

        private static async Task<string> EventPublisher()

        {

            List<EventGridEvent> eventsList = new List<EventGridEvent>

            {

                new EventGridEvent(

                subject: $"New Employee: Alba Sutton",

                eventType: "Employees.Registration.New",

                dataVersion: "1.0",

                 data: new{

                  Id = "108",

                   Description = "456 College Street, Bow, WA 98107",

                   isDone="true"}),

                new EventGridEvent(

                subject: $"New Employee: Alexandre Doyon",

                eventType: "Employees.Registration.New",

                dataVersion: "1.0",

                data: new{

                    Id = "109",

                   Description = "456 College Street, Bow, WA 98107",

                   isDone="true"})

            };

              await client.SendEventsAsync(eventsList);

              Console.WriteLine("All events have been published to the EventGrid Topic");

              return "All events have been published to the EventGrid Topic";

        }

 

  • Finally, call EventPublisher method from Manin method:

 

        static async Task Main()

            {

                try

                {

                await EventPublisher();

                Console.WriteLine("Press any key to exit");

                Console.ReadLine();

                }

               catch (Exception ex)

                {

                Console.WriteLine($"Exception: {ex.Message}");

                }

           }

 

  • The complete code example is here:

    using System;

    using Azure;

    using System.Threading.Tasks;

    using Azure.Messaging.EventGrid;

    namespace AzEventbasedSolution

    {

    internal class Program

    {

        private const string topicEndpoint = "copy and paste here Topic end points";

         private const string topicKey = "Copay and paste here public key

        static Uri endpoint = new Uri(topicEndpoint);

        static AzureKeyCredential credential = new AzureKeyCredential(topicKey);

        static EventGridPublisherClient client = new EventGridPublisherClient(endpoint, credential);

        static async Task Main()

        {

            try

            {

                await EventPublisher();

                Console.WriteLine("Press any key to exit");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Exception: {ex.Message}");

            }

        }


        private static async Task<string> EventPublisher()

         {

            List<EventGridEvent> eventsList = new List<EventGridEvent>

            {

                new EventGridEvent(

                subject: $"New Employee: Alba Sutton",

                eventType: "Employees.Registration.New",

                dataVersion: "1.0",

                 data: new{

                  Id = "108",

                   Description = "456 College Street, Bow, WA 98107",

                   isDone="true"}),

                new EventGridEvent(

                subject: $"New Employee: Alexandre Doyon",

                eventType: "Employees.Registration.New",

                dataVersion: "1.0",

                data: new{

                    Id = "109",

                   Description = "456 College Street, Bow, WA 98107",

                   isDone="true"} )

            };

              await client.SendEventsAsync(eventsList);

              Console.WriteLine("All events have been published to the EventGrid Topic");

              return "All events have been published to the EventGrid Topic";

        }

      }

    }




Tuesday 6 June 2023

Publish messages to Azure Service Bus using c# console app.

In this article, I will explain and provide the working code to pusblish message to Azure service bus using C# console app.


First of all install the Server Bus package and include below ref

    using Azure.Messaging.ServiceBus;

Define service bus connection string and queue name

        private const string serviceBusConnectionString = "Copy and paste service bus connection string";

        private const string queueName = "demo-servicebusqueue";

Define variables to use

         private const int numOfMessages = 200;

        static ServiceBusClient client = default!;

        static ServiceBusSender sender = default!;

        static ServiceBusProcessor processor = default!;

Below is the main method calls Message publisher method which generates message and push to service bus

 public static async Task Main(string[] args)

        {

            try

             {

                await MessagePublisher();

             }

            catch (Exception ex)

             {

                Console.WriteLine($"Exception: {ex.Message}");

             }

          }


Define publisher method, in this case, which generates message

        private static async Task<string> MessagePublisher()

        {

            // create service bus client

            client = new ServiceBusClient(serviceBusConnectionString);

            // Create message sender

            sender = client.CreateSender(queueName);

            // create service message batch

            using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

            var msg = "";

            for (int i =1; i <= numOfMessages; i++)

            {

                msg= $"{{\"id\": {i},\"createdOn\": \"2023-04-05T13:04:57\",\"description\": \"This is very good product with 1 year wanranty\",\"isDone\": false}}";

                // add message to batch

                if (!messageBatch.TryAddMessage(new ServiceBusMessage(msg)))

                {

                    throw new Exception($"An exception has been thrown");

                }

            }

            try

            {

                // finally send message to azure service bus

                await sender.SendMessagesAsync(messageBatch);

                Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");

            }

            finally

            {

                await sender.DisposeAsync();

                await client.DisposeAsync();

            }

            return "All messages have been published to the queue";

        } 


Complete code 

using System;

using System.Diagnostics;

using System.Threading.Tasks;

using Azure.Messaging.ServiceBus;

using Microsoft.Azure.Amqp.Framing;

namespace AzServiceBus

{

    public class Program

    {

        private const string serviceBusConnectionString = "Copy and paste service bus connection string";

        private const string queueName = "demo-servicebusqueue";

        private const int numOfMessages = 200;

        static ServiceBusClient client = default!;

        static ServiceBusSender sender = default!;

        static ServiceBusProcessor processor = default!;

        public static async Task Main(string[] args)

        {

            try

            {

                await MessagePublisher();

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Exception: {ex.Message}");

            }

        }

        private static async Task<string> MessagePublisher()

        {

            client = new ServiceBusClient(serviceBusConnectionString);

            sender = client.CreateSender(queueName);

            using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

            var msg = "";

            for (int i =1; i <= numOfMessages; i++)

            {

                msg= $"{{\"id\": {i},\"createdOn\": \"2023-04-05T13:04:57\",\"description\": \"This is very good product with 1 year wanranty\",\"isDone\": false}}";

                if (!messageBatch.TryAddMessage(new ServiceBusMessage(msg)))

                {

                    throw new Exception($"An exception has been thrown");

                }

            }

            try

            {

                await sender.SendMessagesAsync(messageBatch);

                Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");

            }

            finally

            {

                await sender.DisposeAsync();

                await client.DisposeAsync();

            }

            return "All messages have been published to the queue";

        }

    }

}