Ejemplo n.º 1
0
        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;
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            EventHubClient client = null;

            try
            {
                if (File.Exists(_fileName))
                {
                    string auditData     = File.ReadAllText(_fileName);
                    JArray auditDataJson = JArray.Parse(auditData);
                    client = EventHubClient.CreateFromConnectionString(_connectionString, _eventHubName);

                    foreach (JObject auditEvent in auditDataJson)
                    {
                        client.Send(new EventData(Encoding.UTF8.GetBytes(auditEvent.ToString())));
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("Input file {0} not found.", _fileName));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Upload of Azure AD Audit Data to Event Hub failed with the following error: {0}", ex.Message));
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
        }
Ejemplo n.º 3
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Proton-DotNet.exe connection_string");
                return(2);
            }

            try
            {
                EventHubClient   ehc      = EventHubClient.CreateFromConnectionString(args[0]);
                EventHubReceiver receiver = ehc.GetDefaultConsumerGroup().CreateReceiver("0");
                while (true)
                {
                    EventData data = receiver.Receive();
                    if (data == null)
                    {
                        break;
                    }

                    string text = Encoding.UTF8.GetString(data.GetBytes());
                    Console.WriteLine(data.SequenceNumber + ":" + text);
                }

                ehc.Close();

                return(0);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }

            return(1);
        }
Ejemplo n.º 4
0
 public void Dispose()
 {
     if (_eventHubClient != null)
     {
         _eventHubClient.Close();
     }
 }
        public async Task ClientCannotRetrieveMetadataWhenClosed(bool sync)
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                {
                    var partition = (await client.GetPartitionIdsAsync()).First();

                    Assert.That(async() => await client.GetPropertiesAsync(), Throws.Nothing);
                    Assert.That(async() => await client.GetPartitionPropertiesAsync(partition), Throws.Nothing);

                    if (sync)
                    {
                        client.Close();
                    }
                    else
                    {
                        await client.CloseAsync();
                    }

                    await Task.Delay(TimeSpan.FromSeconds(5));

                    Assert.That(async() => await client.GetPartitionIdsAsync(), Throws.TypeOf <ObjectDisposedException>());
                    Assert.That(async() => await client.GetPropertiesAsync(), Throws.TypeOf <ObjectDisposedException>());
                    Assert.That(async() => await client.GetPartitionPropertiesAsync(partition), Throws.TypeOf <ObjectDisposedException>());
                }
            }
        }
Ejemplo n.º 6
0
        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();
        }
 public void Dispose()
 {
     if (_closeOnDispose)
     {
         _eventHubClient.Close();
     }
 }
Ejemplo n.º 8
0
        //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);
            }
        }
Ejemplo n.º 9
0
        public void Scenario4_EventHubSendToPublisherWithToken(string sbnamespace, string eventHubEntity, string publisher, string sharedAccessKeyName, string sharedAccessKey)
        {
            string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                sharedAccessKeyName,
                sharedAccessKey,
                new TimeSpan(0, 20, 0));

            string connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                token);

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);

            EventHubClient client = factory.CreateEventHubClient(eventHubEntity);

            EventHubSender sender = client.CreateSender(publisher);

            EventData data = new EventData(Encoding.UTF8.GetBytes("Body"));

            data.Properties["time"] = DateTime.UtcNow;

            sender.Send(data);

            sender.Close();
            client.Close();
            factory.Close();
        }
        /// <summary>
        /// Method to run Health Check for Azure Event hub
        /// </summary>
        /// <param name="serviceKey"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override LightHealth.HealthCheck HealthCheck(string serviceKey, string value)
        {
            try
            {
                if (config == null)
                {
                    this.GetConnection(string.Empty);
                }

                foreach (var item in _eventCache)
                {
                    if (!string.IsNullOrEmpty(item.Value.HubName))
                    {
                        var connectionStringBuilder = new EventHubsConnectionStringBuilder(config.ConnectionString)
                        {
                            EntityPath = item.Value.HubName
                        };

                        EventHubClient eventHub = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
                        var            a        = eventHub.GetRuntimeInformationAsync();
                        eventHub.Close();
                    }
                }

                return(LightHealth.HealthCheck.Healthy);
            }
            catch
            {
                return(LightHealth.HealthCheck.Unhealthy);
            }
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            EventHubClient ehClient = EventHubClient.CreateWithManagedIdentity(new Uri($"sb://{txtNamespace.Text}.servicebus.windows.net/"), txtEventHub.Text);

            ehClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(txtData.Text))).GetAwaiter().GetResult();
            txtOutput.Text = $"{DateTime.Now} - SENT{Environment.NewLine}" + txtOutput.Text;
            ehClient.Close();
        }
Ejemplo n.º 12
0
        public Task CloseAsync(PartitionContext context, CloseReason reason)
        {
            _logger.LogInformation($"Processor Shutting Down. Partition '{context.PartitionId}', Reason: '{reason}'.");
            // close the eventhub client
            eventHubClient.Close();

            return(Task.CompletedTask);
        }
Ejemplo n.º 13
0
        public static void Stop()
        {
            cts.Cancel();

            receiverList.ForEach(r => r.Close());
            client.Close();
            factory.Close();
        }
Ejemplo n.º 14
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         _eventHubClient.Close();
         _messsagingFactory.Close();
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Attempts to disconnect from Azure Event Hub.
        /// </summary>
        protected override void AttemptDisconnection()
        {
            m_eventHubDataClient.Close();

            if (m_eventHubDataClient != m_eventHubMetadataClient)
            {
                m_eventHubMetadataClient.Close();
            }
        }
Ejemplo n.º 16
0
        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();
                }
            }
        }
Ejemplo n.º 17
0
        private void btn_closeEventHub_Click(object sender, EventArgs e)
        {
            if (ehClient != null)
            {
                ehClient.Close();
            }

            btn_closeEventHub.Enabled   = false;
            btn_connectEventHub.Enabled = true;
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         GC.SuppressFinalize(this);
     }
     Client.TryDispose();
     Client = default(T);
     NotificationHub.Close();
     NotificationHub = null;
 }
Ejemplo n.º 19
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                handle.Dispose();
                _client.Close();
            }
            disposed = true;
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            Console.WriteLine($"Backend App for C2D scenarios, targeting to simulated device {TargetDeviceId}.");
            Console.WriteLine("Please choose actions you'd like take:");
            Console.WriteLine("1. Send C2D messages");
            Console.WriteLine("2. Receive D2C messages");
            Console.WriteLine("3. Receive file upload notification");
            Console.WriteLine("4. Invoke direct method");
            var input = Console.ReadLine();

            switch (input)
            {
            case "1":
                MyServiceClient = ServiceClient.CreateFromConnectionString(IoTHubConnectionString);
                ReceiveC2dFeedbackAsync();
                SendCloudToDeviceMessagesAsync();
                Console.WriteLine("Start to send messages... Press Enter to stop and exit!");
                Console.ReadLine();
                MyServiceClient.CloseAsync().Wait();
                break;

            case "2":
                MyEventHubClient = EventHubClient.CreateFromConnectionString(EventHubCompatibleConnectionString);
                ReceiveDeviceToCloudMessagesAsync();
                Console.WriteLine("Start to receive messages... Press Enter to stop and exit!");
                Console.ReadLine();
                MyEventHubClient.Close();
                break;

            case "3":
                MyServiceClient = ServiceClient.CreateFromConnectionString(IoTHubConnectionString);
                ReceiveFileUploadNotificationAsync();
                Console.WriteLine("Start to receive file upload notification... Press Enter to stop and exit!");
                Console.ReadLine();
                MyServiceClient.CloseAsync().Wait();
                break;

            case "4":
                MyServiceClient = ServiceClient.CreateFromConnectionString(IoTHubConnectionString);
                InvokeDirectMethodAsync();
                Console.WriteLine("Start to invoke direct method... Press Enter to stop and exit!");
                Console.ReadLine();
                MyServiceClient.CloseAsync().Wait();
                break;

            default:
                Console.WriteLine("Wrong input! Please just input actions index provided above!");
                break;
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Method to run Health Check for Azure Event hub
 /// </summary>
 /// <param name="serviceKey"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public LightHealth.HealthCheck HealthCheck(string serviceKey, string value)
 {
     try
     {
         EventHubClient eventHub = EventHubClient.CreateFromConnectionString(config.ConnectionString);
         var            a        = eventHub.GetRuntimeInformationAsync();
         eventHub.Close();
         return(LightHealth.HealthCheck.Healthy);
     }
     catch
     {
         return(LightHealth.HealthCheck.Unhealthy);
     }
 }
Ejemplo n.º 22
0
        public override void StopListening()
        {
            try
            {
                receivers.ForEach(r => r.Close());

                eventHubClient.Close();
                eventHubClient = null;
                listenerTimer?.Cancel();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Gap Detection: {e.Message}");
            }
        }
        public async Task ProducerCanSendWhenClientIsClosed()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        client.Close();

                        var events = new EventData(Encoding.UTF8.GetBytes("Do not delete me!"));
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
Ejemplo n.º 24
0
        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                eventHubClient.Close();
            }

            // Free any unmanaged objects here.
            //
            disposed = true;
        }
Ejemplo n.º 25
0
        public static async Task Main(string[] args)
        {
            try
            {
                _eventHubClient = CreateEventHubClient();
                await ReceiveData();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }

            Console.WriteLine("-- Press Key --");
            Console.ReadKey();
            _eventHubClient.Close();
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            SendMessagesToEventHub(500).Wait();

            eventHubClient.Close();

            Console.WriteLine("Press any key to continue ...");
            Console.ReadKey();
        }
Ejemplo n.º 27
0
        public async Task PublishWithAPartitionKey()
        {
            await using var scope = await EventHubScope.CreateAsync(1);

            #region Snippet:EventHubs_Migrate_T1_PublishWithAPartitionKey
#if SNIPPET
            var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>";
            var eventHubName     = "<< NAME OF THE EVENT HUB >>";
#else
            var connectionString = TestUtility.EventHubsConnectionString;
            var eventHubName     = scope.EventHubName;
#endif

            var builder = new EventHubsConnectionStringBuilder(connectionString);
            builder.EntityPath = eventHubName;

            EventHubClient client = EventHubClient.CreateFromConnectionString(builder.ToString());

            try
            {
                var batchOptions = new BatchOptions
                {
                    PartitionKey = "Any Value Will Do..."
                };

                using var eventBatch = client.CreateBatch(batchOptions);

                for (var index = 0; index < 5; ++index)
                {
                    var eventData = new EventData(Encoding.UTF8.GetBytes($"Event #{ index }"));

                    if (!eventBatch.TryAdd(eventData))
                    {
                        throw new Exception($"The event at { index } could not be added");
                    }
                }

                await client.SendAsync(eventBatch);
            }
            finally
            {
                client.Close();
            }

            #endregion
        }
Ejemplo n.º 28
0
        public async Task PublishToSpecificPartition()
        {
            await using var scope = await EventHubScope.CreateAsync(1);

            #region Snippet:EventHubs_Migrate_T1_PublishToSpecificPartition
#if SNIPPET
            var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>";
            var eventHubName     = "<< NAME OF THE EVENT HUB >>";
#else
            var connectionString = TestUtility.EventHubsConnectionString;
            var eventHubName     = scope.EventHubName;
#endif

            var builder = new EventHubsConnectionStringBuilder(connectionString);
            builder.EntityPath = eventHubName;

            EventHubClient  client = EventHubClient.CreateFromConnectionString(builder.ToString());
            PartitionSender sender = default;

            try
            {
                using var eventBatch = client.CreateBatch();

                for (var index = 0; index < 5; ++index)
                {
                    var eventData = new EventData(Encoding.UTF8.GetBytes($"Event #{ index }"));

                    if (!eventBatch.TryAdd(eventData))
                    {
                        throw new Exception($"The event at { index } could not be added");
                    }
                }

                string firstPartition = (await client.GetRuntimeInformationAsync()).PartitionIds.First();
                sender = client.CreatePartitionSender(firstPartition);

                await sender.SendAsync(eventBatch);
            }
            finally
            {
                sender?.Close();
                client.Close();
            }

            #endregion
        }
Ejemplo n.º 29
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience),
                TransportType = TransportType.Amqp
            };

            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/",
                                                                        messagingFactorySettings);

            EventHubClient ehClient = messagingFactory.CreateEventHubClient(txtEventHub.Text);

            ehClient.Send(new EventData(Encoding.UTF8.GetBytes(txtData.Text)));
            ehClient.Close();
            messagingFactory.Close();
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            SendMessagesToEventHub(500).Wait();

            eventHubClient.Close();

            //File.WriteAllText("SEN01.json", JsonConvert.SerializeObject(messages));

            Console.WriteLine("Press any key to continue ...");
            Console.ReadKey();
        }