Отправить сообщение в Event Hub UWP
Моя проблема
Мне нужно отправить данные телеметрии в EventHub, который я создал в своей учетной записи Azure, используя UWP.
Я создал веб-приложение (в котором я подробно рассказал о соединениях EventHub и ключах области хранения) - это приложение, которое получает данные из EventHub и строит график в реальном времени с помощью WebSocket.
Что я пробовал
У меня есть консольное приложение, которое использует ServiceBus dll для отправки данных в EventHub. Когда я попытался сделать UWP, DLL-библиотека ServiceBus не поддерживается в Core .Net Framework
Можете ли вы показать мне несколько указателей или фрагмент кода, который будет отправлять данные в EventHub.
1 ответ
В Universal Apps вы должны использовать новый пакет NuGet для Microsoft.Azure.EventHubs.
Цитирование из этой статьи: 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)));