jeudi 7 mai 2015

Connect to Event-Hub

This post explain how to create and connect to a Microsoft Event Hub in order to implement a Real-Time Business Intelligence Solution.

Create an Event-Hub on Microsoft Azure.



You will need an Azure account with a subscription, on azure portal hit the plus button on the left-bottom of the screen. Then APP SERVICES -> SERVICE BUS->EVENT HUB


Then click on Custom-create.

You will have to create a unique name for the event-hub and for the namespace of the service bus if don't already have one.


Once the creation is finish go to the the tab Service bus then click on the arrow after the name of your new service bus.


Now it's important that you go inside the hub and not configure the security inside the service-namespace.


Now go on the configure tab and create a new Policy with Send and Listen permission.


Then hit save.
Under Share access key generator select your policy from the drop-down list. And copy the Primary key.We will need it later.


Create a c# application to send data to an Event hub.


Now we will create a c# application that send data to an Event Hub.

Create a new c# console application in Visual-studio.

Use NuGet ton install Active Directory Authentification Library and Microsoft Azure Service Bus and NewtonSoft.Json.

This line of code will help you to initialize your connection to the service-bus

    string eventHubName = "demohub";
            string eventHubNamespace = "demohub-namespace";
            string sharedAccessPolicyName = "DemoPolicy";
            string sharedAccessPolicyKey = "YourKey"
            var settings = new MessagingFactorySettings()
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sharedAccessPolicyName, sharedAccessPolicyKey),
                TransportType = TransportType.Amqp
            };

            var factory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", eventHubNamespace, ""), settings);
            EventHubClient client = factory.CreateEventHubClient(eventHubName);



Then to send data you will need to serialize a json object then send it.

// e is the object you want to send
String eventdata = JsonConvert.SerializeObject(e);

// You will need to partition the data you send with a key
                EventData data = new EventData(Encoding.UTF8.GetBytes(eventdata))
                {
                    PartitionKey = e.card_uid
                };

Then you can send you data with a Synchrnous method

client.Send(data);

Or Asynchronous

tasks.Add(client.SendAsync(data));


Aucun commentaire:

Enregistrer un commentaire