Get started sending messages to Azure Event Hubs in .NET Standard

Note

This sample is available on GitHub.

This tutorial shows how to write a .NET Core console application that sends a set of messages to an event hub. You can run the GitHub solution as-is, replacing the EhConnectionString and EhEntityPath strings with your event hub values. Or you can follow the steps in this tutorial to create your own.

Prerequisites

To send messages to an event hub, we will use Visual Studio to write a C# console application.

Create an Event Hubs namespace and an event hub

The first step is to use the Azure portal to create a namespace for the event hub type, and obtain the management credentials that your application needs to communicate with the event hub. To create a namespace and an event hub, follow the procedure in this article, and then proceed with the following steps.

Create a console application

Start Visual Studio. From the File menu, click New, and then click Project. Create a .NET Core console application.

New project

Add the Event Hubs NuGet package

Add the Microsoft.Azure.EventHubs .NET Standard library NuGet package to your project by following these steps:

  1. Right-click the newly created project and select Manage NuGet Packages.
  2. Click the Browse tab, then search for "Microsoft.Azure.EventHubs" and select the Microsoft.Azure.EventHubs package. Click Install to complete the installation, then close this dialog box.

Write some code to send messages to the event hub

  1. Add the following using statements to the top of the Program.cs file.

    using Microsoft.Azure.EventHubs;
    using System.Text;
    using System.Threading.Tasks;
    
  2. Add constants to the Program class for the Event Hubs connection string and entity path (individual event hub name). Replace the placeholders in brackets with the proper values that were obtained when creating the event hub. Make sure that the {Event Hubs connection string} is the namespace-level connection string, and not the event hub string.

    private static EventHubClient eventHubClient;
    private const string EhConnectionString = "{Event Hubs connection string}";
    private const string EhEntityPath = "{Event Hub path/name}";
    
  3. Add a new method named MainAsync to the Program class, as follows:

    private static async Task MainAsync(string[] args)
    {
        // Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
        // Typically, the connection string should have the entity path in it, but for the sake of this simple scenario
        // we are using the connection string from the namespace.
        var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
        {
            EntityPath = EhEntityPath
        };
    
        eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
    
        await SendMessagesToEventHub(100);
    
        await eventHubClient.CloseAsync();
    
        Console.WriteLine("Press ENTER to exit.");
        Console.ReadLine();
    }
    
  4. Add a new method named SendMessagesToEventHub to the Program class, as follows:

    // Creates an event hub client and sends 100 messages to the event hub.
    private static async Task SendMessagesToEventHub(int numMessagesToSend)
    {
        for (var i = 0; i < numMessagesToSend; i++)
        {
            try
            {
                var message = $"Message {i}";
                Console.WriteLine($"Sending message: {message}");
                await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
            }
    
            await Task.Delay(10);
        }
    
        Console.WriteLine($"{numMessagesToSend} messages sent.");
    }
    
  5. Add the following code to the Main method in the Program class.

    MainAsync(args).GetAwaiter().GetResult();
    

    Here is what your Program.cs should look like.

    namespace SampleSender
    {
        using System;
        using System.Text;
        using System.Threading.Tasks;
        using Microsoft.Azure.EventHubs;
    
        public class Program
        {
            private static EventHubClient eventHubClient;
            private const string EhConnectionString = "{Event Hubs connection string}";
            private const string EhEntityPath = "{Event Hub path/name}";
    
            public static void Main(string[] args)
            {
                MainAsync(args).GetAwaiter().GetResult();
            }
    
            private static async Task MainAsync(string[] args)
            {
                // Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
                // Typically, the connection string should have the entity path in it, but for the sake of this simple scenario
                // we are using the connection string from the namespace.
                var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
                {
                    EntityPath = EhEntityPath
                };
    
                eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
    
                await SendMessagesToEventHub(100);
    
                await eventHubClient.CloseAsync();
    
                Console.WriteLine("Press ENTER to exit.");
                Console.ReadLine();
            }
    
            // Creates an event hub client and sends 100 messages to the event hub.
            private static async Task SendMessagesToEventHub(int numMessagesToSend)
            {
                for (var i = 0; i < numMessagesToSend; i++)
                {
                    try
                    {
                        var message = $"Message {i}";
                        Console.WriteLine($"Sending message: {message}");
                        await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
                    }
    
                    await Task.Delay(10);
                }
    
                Console.WriteLine($"{numMessagesToSend} messages sent.");
            }
        }
    }
    
  6. Run the program, and ensure that there are no errors.

Congratulations! You have now sent messages to an event hub.

Next steps

You can learn more about Event Hubs by visiting the following links: