发送消息到Event Hub UWP

时间:2017-02-08 06:17:21

标签: c# azure uwp azure-eventhub

我的问题

我需要将遥测数据发送到我使用UWP在Azure帐户中创建的EventHub。

我创建了一个Web应用程序(我已经提供了有关EventHub连接和存储区域键的详细信息) - 从EventHub获取数据并使用WebSocket绘制实时图形。

我尝试了什么

我有一个控制台应用程序,它使用ServiceBus dll将数据发送到EventHub。 当我尝试创建UWP时,Core .Net Framework

不支持ServiceBus dll

你能告诉我一些将数据发送到EventHub的指针或代码片段。

1 个答案:

答案 0 :(得分:1)

在Universal Apps中,您必须使用新的 Microsoft.Azure.EventHubs NuGet包。

引用本文:https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-dotnet-standard-getstarted-send

 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 a 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 any key 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.");
         }
     }
 }

所以你安装NuGet包,从连接字符串创建一个EventHubClient,然后用它来发送消息:

await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));