How-To: Write data to Event Hubs

In this How-To we will work with Event-Hubs. You can find more information on the following place.

First we go to the Azure Portal

Then we click on the “New” button.

Then we click on “Data + Analytics”and then on the “Event Hub” section.

We will be forwarded to the old portal, but to the right section.

You will see the following.
Now you can choose a name for your Event Hub. We have already a servicebus namespace. So we can select that one.

Then we see our Event Hub.

When we open our “ordershub”, we configure our permissions under the “Configure” tab.
We created the “sendToOrdershub” permission so we can send it to our Event Hub.

Now we will create our application to send our order information to the Event Hub.
Start Visual Studio and create a new C# Console Application.
Then add the the “Windows.Azure.Service” NuGet package.

Also add the “Json.NET” NuGet package.

Then we create a new “Order” class

public class Order 
{
	public int Id { get; set; }
	public string Name { get; set; }
	public int Quantity { get; set; }
	public double Price { get; set; }
}

Then we create our Main program.
First we create our “EventHubClient”. After that we create our “Order” object. Then we serialize it to json and send it to our EventHub.

public class Program
{
    public static void Main(string[] args)
    {
        EventHubClient ehc = EventHubClient.CreateFromConnectionString(
            "Endpoint=sb://orderexample.servicebus.windows.net/;SharedAccessKeyName=sendToOrdershub;SharedAccessKey=YOURSHAREDKEY",
            "ordershub");

        Console.WriteLine("Start");

        for (int i = 0; i < 100; i++)
        {
            Order order = new Order()
            {
                Id = i,
                Name = "Order_" + i,
                Quantity = new Random().Next(1,100),
                Price = new Random().NextDouble()
            };

            string svJson = JsonConvert.SerializeObject(order);
            Byte[] svBytes = Encoding.UTF8.GetBytes(svJson);
            ehc.Send(new EventData(svBytes));
        }

        Console.WriteLine("End");
        Console.ReadLine();
    }
}

You can also find the source code on my Github Repo

Now your “Orders” are available on your “EventHub”.

Have fun… If you have a problem. Ping me on twitter or send a comment on this post.