private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName) { EventHubClient eventHubClient = null; EventHubReceiver eventHubReceiver = null; try { eventHubClient = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events"); eventHubTextBox.Text = String.Format("Receiving events...\r\n"); eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount; string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceIDsComboBoxForEvent.SelectedItem.ToString(), eventHubPartitionsCount); eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime); while (true) { ct.ThrowIfCancellationRequested(); EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)); if (eventData != null) { string data = Encoding.UTF8.GetString(eventData.GetBytes()); DateTime enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime(); eventHubTextBox.Text += String.Format("{0}> Data:[{1}]", enqueuedTime, data); if (eventData.Properties.Count > 0) { eventHubTextBox.Text += "Properties:\r\n"; foreach (var property in eventData.Properties) { eventHubTextBox.Text += String.Format("'{0}': '{1}'\r\n", property.Key, property.Value); } } eventHubTextBox.Text += "\r\n"; } } } catch (Exception ex) { if (ct.IsCancellationRequested) { eventHubTextBox.Text += String.Format("Stopped Monitoring events. {0}\r\n", ex.Message); } else { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); eventHubTextBox.Text += String.Format("Stopped Monitoring events. {0}\r\n", ex.Message); } if (eventHubReceiver != null) { eventHubReceiver.Close(); } if (eventHubClient != null) { eventHubClient.Close(); } dataMonitorButton.Enabled = true; deviceIDsComboBoxForEvent.Enabled = true; cancelMonitoringButton.Enabled = false; } }
public async Task ReceiveDataFromCloud() { startingDateTimeUtc = DateTime.UtcNow - TimeSpan.FromHours(24); factory = MessagingFactory.CreateFromConnectionString(ConnectionString); client = factory.CreateEventHubClient(eventHubEntity); group = client.GetDefaultConsumerGroup(); receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc); try { while (true) { EventData data = receiver.Receive(); if (data != null) { var receiveddata = Encoding.UTF8.GetString(data.GetBytes()); Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), receiveddata); } } } catch (Exception ex) { Debug.WriteLine("Exception {0}", ex); } receiver.Close(); client.Close(); factory.Close(); }
//code adapted from tutorial https://paolopatierno.wordpress.com/2015/11/02/azure-iot-hub-get-telemetry-data-using-amqp-stack-and-azure-sb-lite/ public static string GetMessage(string partitionId) { string result = null; ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString); builder.TransportType = TransportType.Amqp; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConnectionString); EventHubClient client = factory.CreateEventHubClient(eventHubEntity); EventHubConsumerGroup group = client.GetDefaultConsumerGroup(); var startingDateTimeUtc = DateTime.Now; EventHubReceiver receiver = group.CreateReceiver(partitionId, startingDateTimeUtc); EventData data = receiver.Receive(); receiver.Close(); client.Close(); factory.Close(); if (data != null) { result = Encoding.UTF8.GetString(data.GetBytes()); return(result); } else { return(null); } }
private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName) { EventHubClient eventHubClient = null; EventHubReceiver eventHubReceiver = null; try { eventHubClient = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events"); int eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount; string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceID, eventHubPartitionsCount); eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime); //receive the events from startTime until current time in a single call and process them var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(20)); foreach (var eventData in events) { byte[] rxbuff = eventData.GetBytes(); makeCommDataForLogData("Rx", rxbuff); } //having already received past events, monitor current events in a loop while (true) { ct.ThrowIfCancellationRequested(); var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(0.5)); if (eventData != null) { byte[] rxbuff = eventData.GetBytes(); makeCommDataForLogData("Rx", rxbuff); } } } catch (Exception ex) { if (ct.IsCancellationRequested) { //Stopped Monitoring events by user action. } else { //Something happen. } if (eventHubReceiver != null) { eventHubReceiver.Close(); } if (eventHubClient != null) { eventHubClient.Close(); } } }
public void Scenario8_EventHubReceiveFromPartitionDateTimeOffset(string eventHubEntity, string partitionId, DateTime dateTimeOffset) { ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString); builder.TransportType = TransportType.Amqp; MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString); EventHubClient client = factory.CreateEventHubClient(eventHubEntity); EventHubConsumerGroup group = client.GetDefaultConsumerGroup(); EventHubReceiver receiver = group.CreateReceiver(partitionId, dateTimeOffset); while (true) { EventData data = receiver.Receive(); } receiver.Close(); client.Close(); factory.Close(); }
static void SendReceive(MessagingFactorySettings messagingFactorySettings) { MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{EventHubNamespace}/", messagingFactorySettings); EventHubClient ehClient = messagingFactory.CreateEventHubClient(EventHubName); EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup(); var receiveTask = Task.Factory.StartNew(() => { string[] partitionIds = { "0", "1" }; Parallel.ForEach(partitionIds, partitionId => { EventHubReceiver receiver = consumerGroup.CreateReceiver(partitionId, EventHubConsumerGroup.StartOfStream); while (true) { EventData data = receiver.Receive(TimeSpan.FromSeconds(10)); if (data == null) { break; } Console.WriteLine($"Received from partition {partitionId} : " + Encoding.UTF8.GetString(data.GetBytes())); } receiver.Close(); }); }); System.Threading.Thread.Sleep(5000); ehClient.Send(new EventData(Encoding.UTF8.GetBytes($"{DateTime.UtcNow}"))); Task.WaitAll(receiveTask); ehClient.Close(); messagingFactory.Close(); Console.WriteLine("Send / Receive complete. Press enter to exit."); Console.ReadLine(); }
protected void btnReceive_Click(object sender, EventArgs e) { MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings { TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience), TransportType = TransportType.Amqp }; messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false; MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/", messagingFactorySettings); EventHubClient ehClient = messagingFactory.CreateEventHubClient(txtEventHub.Text); EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup(); int partitions = int.Parse(txtPartitions.Text); string[] Offsets = new string[partitions]; if (!string.IsNullOrEmpty(hiddenStartingOffset.Value)) { Offsets = hiddenStartingOffset.Value.Split(','); } System.Threading.Tasks.Parallel.ForEach(Enumerable.Range(0, int.Parse(txtPartitions.Text)), partitionId => { EventHubReceiver receiver = consumerGroup.CreateReceiver($"{partitionId}", Offsets[partitionId] == null ? "-1" : Offsets[partitionId]); EventData data = receiver.Receive(TimeSpan.FromSeconds(1)); if (data != null) { Offsets[partitionId] = data.Offset; txtReceivedData.Text += $"PartitionId: {partitionId} Seq#:{data.SequenceNumber} data:{Encoding.UTF8.GetString(data.GetBytes())}{Environment.NewLine}"; } receiver.Close(); }); hiddenStartingOffset.Value = string.Join(",", Offsets); ehClient.Close(); messagingFactory.Close(); }
private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName) { EventHubClient eventHubClient = null; EventHubReceiver eventHubReceiver = null; try { string selectedDevice = deviceIDsComboBoxForEvent.SelectedItem.ToString(); eventHubClient = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events"); eventHubTextBox.Text = "Receiving events...\r\n"; eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount; string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount); eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime); //receive the events from startTime until current time in a single call and process them var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(20)); foreach (var eventData in events) { var data = Encoding.UTF8.GetString(eventData.GetBytes()); var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime(); var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString(); if (string.CompareOrdinal(selectedDevice.ToUpper(), connectionDeviceId.ToUpper()) == 0) { eventHubTextBox.Text += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]"; if (eventData.Properties.Count > 0) { eventHubTextBox.Text += "Properties:\r\n"; foreach (var property in eventData.Properties) { eventHubTextBox.Text += $"'{property.Key}': '{property.Value}'\r\n"; } } if (enableSystemProperties.Checked) { if (eventData.Properties.Count == 0) { eventHubTextBox.Text += "\r\n"; } foreach (var item in eventData.SystemProperties) { eventHubTextBox.Text += $"SYSTEM>{item.Key}={item.Value}\r\n"; } } eventHubTextBox.Text += "\r\n"; // scroll text box to last line by moving caret to the end of the text eventHubTextBox.SelectionStart = eventHubTextBox.Text.Length - 1; eventHubTextBox.SelectionLength = 0; eventHubTextBox.ScrollToCaret(); } } //having already received past events, monitor current events in a loop while (true) { ct.ThrowIfCancellationRequested(); var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)); if (eventData != null) { var data = Encoding.UTF8.GetString(eventData.GetBytes()); var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime(); // Display only data from the selected device; otherwise, skip. var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString(); if (string.CompareOrdinal(selectedDevice, connectionDeviceId) == 0) { eventHubTextBox.Text += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]"; if (eventData.Properties.Count > 0) { eventHubTextBox.Text += "Properties:\r\n"; foreach (var property in eventData.Properties) { eventHubTextBox.Text += $"'{property.Key}': '{property.Value}'\r\n"; } } if (enableSystemProperties.Checked) { if (eventData.Properties.Count == 0) { eventHubTextBox.Text += "\r\n"; } foreach (var item in eventData.SystemProperties) { eventHubTextBox.Text += $"SYSTEM>{item.Key}={item.Value}\r\n"; } } eventHubTextBox.Text += "\r\n"; } // scroll text box to last line by moving caret to the end of the text eventHubTextBox.SelectionStart = eventHubTextBox.Text.Length - 1; eventHubTextBox.SelectionLength = 0; eventHubTextBox.ScrollToCaret(); } } } catch (Exception ex) { if (ct.IsCancellationRequested) { eventHubTextBox.Text += $"Stopped Monitoring events. {ex.Message}\r\n"; } else { using (new CenterDialog(this)) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } eventHubTextBox.Text += $"Stopped Monitoring events. {ex.Message}\r\n"; } if (eventHubReceiver != null) { eventHubReceiver.Close(); } if (eventHubClient != null) { eventHubClient.Close(); } dataMonitorButton.Enabled = true; deviceIDsComboBoxForEvent.Enabled = true; cancelMonitoringButton.Enabled = false; } }
private async Task MonitorEventHubAsync(CancellationToken ct) { EventHubClient eventHubClient = null; EventHubReceiver eventHubReceiver = null; var consumerGroupName = "$Default"; var startTime = DateTime.Now; try { string selectedDevice = cboDevices2.SelectedItem.ToString(); eventHubClient = EventHubClient.CreateFromConnectionString(txtConnectionString.Text, "messages/events"); var eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount; string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount); eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime); //receive the events from startTime until current time in a single call and process them var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(20)); foreach (var eventData in events) { var data = Encoding.UTF8.GetString(eventData.GetBytes()); var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime(); var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString(); if (string.CompareOrdinal(selectedDevice.ToUpper(), connectionDeviceId.ToUpper()) == 0) { txtMessages.Text += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]"; UpdatePanel1.Update(); if (eventData.Properties.Count > 0) { txtMessages.Text += "Properties:\r\n"; UpdatePanel1.Update(); foreach (var property in eventData.Properties) { txtMessages.Text += $"'{property.Key}': '{property.Value}'\r\n"; UpdatePanel1.Update(); } } txtMessages.Text += "\r\n"; UpdatePanel1.Update(); } } //having already received past events, monitor current events in a loop while (true) { ct.ThrowIfCancellationRequested(); var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)); if (eventData != null) { var data = Encoding.UTF8.GetString(eventData.GetBytes()); var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime(); // Display only data from the selected device; otherwise, skip. var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString(); if (string.CompareOrdinal(selectedDevice, connectionDeviceId) == 0) { txtMessages.Text += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]"; UpdatePanel1.Update(); if (eventData.Properties.Count > 0) { txtMessages.Text += "Properties:\r\n"; UpdatePanel1.Update(); foreach (var property in eventData.Properties) { txtMessages.Text += $"'{property.Key}': '{property.Value}'\r\n"; UpdatePanel1.Update(); } } txtMessages.Text += "\r\n"; UpdatePanel1.Update(); } } } } catch (Exception ex) { if (ct.IsCancellationRequested) { txtMessages.Text += $"Stopped Monitoring events. {ex.Message}\r\n"; UpdatePanel1.Update(); } else { txtMessages.Text += $"Stopped Monitoring events. {ex.Message}\r\n"; UpdatePanel1.Update(); } if (eventHubReceiver != null) { eventHubReceiver.Close(); } if (eventHubClient != null) { eventHubClient.Close(); } cmdStart.Enabled = true; cboDevices2.Enabled = true; cmdStop.Enabled = false; UpdatePanel1.Update(); } }
//For demo purpose we have taken two devices/rooms and //updating the collection based on the data received public async Task ReceiveDataFromCloud() { startingDateTimeUtc = DateTime.UtcNow; ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString); builder.TransportType = ppatierno.AzureSBLite.Messaging.TransportType.Amqp; factory = MessagingFactory.CreateFromConnectionString(ConnectionString); client = factory.CreateEventHubClient(eventHubEntity); group = client.GetDefaultConsumerGroup(); receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);//startingDateTimeUtc while (true) { EventData data = receiver.Receive(); if (data != null) { var receiveddata = Encoding.UTF8.GetString(data.GetBytes()); var messageString = JsonConvert.DeserializeObject <ConferenceRoomDataPoint>(receiveddata); if (messageString.DeviceId == "device1") { conferenceRoomDataPointList[0].DeviceId = messageString.DeviceId; conferenceRoomDataPointList[0].RoomTemp = messageString.RoomTemp; conferenceRoomDataPointList[0].RoomStatus = messageString.RoomStatus; conferenceRoomDataPointList[0].Color = messageString.Color; conferenceRoomDataPointList[0].LightStatus = messageString.LightStatus; DateTime localDateTime = DateTime.Parse(messageString.Time); DateTime utcDateTime = localDateTime.ToLocalTime(); conferenceRoomDataPointList[0].Time = utcDateTime.ToString(); conferenceRoomDataPointList[0].RoomPressure = messageString.RoomPressure; conferenceRoomDataPointList[0].RoomAlt = messageString.RoomAlt; } if (messageString.DeviceId == "device2") { conferenceRoomDataPointList[1].DeviceId = messageString.DeviceId; conferenceRoomDataPointList[1].RoomTemp = messageString.RoomTemp; conferenceRoomDataPointList[1].RoomStatus = messageString.RoomStatus; conferenceRoomDataPointList[1].Color = messageString.Color; conferenceRoomDataPointList[1].LightStatus = messageString.LightStatus; DateTime localDateTime = DateTime.Parse(messageString.Time); DateTime utcDateTime = localDateTime.ToLocalTime(); conferenceRoomDataPointList[1].Time = utcDateTime.ToString(); conferenceRoomDataPointList[1].RoomPressure = messageString.RoomPressure; conferenceRoomDataPointList[1].RoomAlt = messageString.RoomAlt; } //var message = new ConferenceRooms(Encoding.ASCII.GetBytes(receiveddata)); Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), Encoding.UTF8.GetString(data.GetBytes())); } else { break; } await Task.Delay(2000); } receiver.Close(); client.Close(); factory.Close(); }
private static async Task ReadFromIOTHub(string activeIoTHubConnectionString, string selectedDevice, DateTime startTime, CancellationToken ct, string consumerGroupName) { EventHubClient eventHubClient = null; EventHubReceiver eventHubReceiver = null; EventHubReceiver eventHubHistoryReceiver = null; string output = "Receiving events...\r\n"; try { eventHubClient = EventHubClient.CreateFromConnectionString(activeIoTHubConnectionString, "messages/events"); eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount; string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount); //If inside Firewall, use this below line... ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http; bool IsHistoryNeeded = Convert.ToBoolean(ConfigurationManager.AppSettings["IsHistoryNeeded"]); if (IsHistoryNeeded) { //receive the events from startTime until current time in a single call and process them eventHubHistoryReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition); var events = await eventHubHistoryReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(20)); foreach (var eventData in events) { ProcessEvent(eventData); } } //having already received past events, monitor current events in a loop eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime); while (true) { ct.ThrowIfCancellationRequested(); var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)); if (eventData != null) { ProcessEvent(eventData); } } } catch (Exception ex) { if (ct.IsCancellationRequested) { //output += $"Stopped Monitoring events. {ex.Message}\r\n"; } else { //Do something } if (eventHubReceiver != null) { eventHubReceiver.Close(); } if (eventHubClient != null) { eventHubClient.Close(); } } }