In this section, you'll write a Windows console app that sends events to your Event Hub.
-
In Visual Studio, create a new Visual C# Desktop App project using the Console Application project template. Name the project Sender.
-
In Solution Explorer, right-click the solution, and then click Manage NuGet Packages for Solution.
-
Click the Browse tab, then search for
Microsoft Azure Service Bus
. Ensure that the project name (Sender) is specified in the Version(s) box. Click Install, and accept the terms of use.Visual Studio downloads, installs, and adds a reference to the Azure Service Bus library NuGet package.
-
Add the following
using
statements at the top of the Program.cs file:using System.Threading; using Microsoft.ServiceBus.Messaging;
-
Add the following fields to the Program class, substituting the placeholder values with the name of the Event Hub you created in the previous section, and the namespace-level connection string you saved previously.
static string eventHubName = "{Event Hub name}"; static string connectionString = "{send connection string}";
-
Add the following method to the Program class:
static void SendingRandomMessages() { var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName); while (true) { try { var message = Guid.NewGuid().ToString(); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, message); eventHubClient.Send(new EventData(Encoding.UTF8.GetBytes(message))); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message); Console.ResetColor(); } Thread.Sleep(200); } }
This method continuously sends events to your Event Hub with a 200-ms delay.
-
Finally, add the following lines to the Main method:
Console.WriteLine("Press Ctrl-C to stop the sender process"); Console.WriteLine("Press Enter to start now"); Console.ReadLine(); SendingRandomMessages();