Ejemplo n.º 1
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //------------------------------------------------------------------------------------------------------------------------
        public EventHubDirectConsumer(EventHubClient client)
        {
            //create event hub direct consumer
            EventHubConsumerGroup group = client.GetDefaultConsumerGroup();
            var x = client.GetRuntimeInformation().PartitionIds[0];
            eventHubDirectReceiver = group.CreateReceiver(client.GetRuntimeInformation().PartitionIds[0]);
        }
Ejemplo n.º 2
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //------------------------------------------------------------------------------------------------------------------------
        public EventHubDirectConsumer(EventHubClient client)
        {
            //create event hub direct consumer
            EventHubConsumerGroup group = client.GetDefaultConsumerGroup();
            var x = client.GetRuntimeInformation().PartitionIds[0];

            eventHubDirectReceiver = group.CreateReceiver(client.GetRuntimeInformation().PartitionIds[0]);
        }
Ejemplo n.º 3
0
        public async Task Setup(NetworkParameters parameters)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(parameters.ConnectionString, "messages/events");
            Console.WriteLine("Created client");
            var runtimeinfo = eventHubClient.GetRuntimeInformation();

            partitionsCount = runtimeinfo.PartitionCount;

            var partition = EventHubPartitionKeyResolver.ResolveToPartition(parameters.DeviceName, partitionsCount);

            Console.WriteLine("Got partition");

            if (parameters.StartTime == null)
            {
                parameters.StartTime = DateTime.Now;
            }

            eventHubReceiver = eventHubClient.GetConsumerGroup(parameters.ConsumerGroupName).CreateReceiver(partition, parameters.StartTime);
            Console.WriteLine("Created reciever");

            var pastEvents = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(3));

            int cnt = 0;

            foreach (var ev in pastEvents)
            {
                cnt++;
            }
            Console.WriteLine("Got {0} events from past", cnt);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());


            //var eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            //string partition = EventHubPartitionKeyResolver.ResolveToPartition("123", eventHubPartitionsCount);
            ////eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);

            //ReceiveMessagesFromDeviceAsync(partition, cts.Token).Wait();

            //ReceiveFromIothubAsync().Wait();
        }
Ejemplo n.º 5
0
        public void ReceiveMessages()
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;


            CancellationTokenSource cts = new CancellationTokenSource();

            /*
             * System.Console.CancelKeyPress += (s, e) =>
             * {
             *  e.Cancel = true;
             *  cts.Cancel();
             *  Console.WriteLine("Exiting...");
             * };
             */

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }

            //tasks.Add(ReceiveMessagesFromDeviceAsync("1", cts.Token));


            //Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            var       hubConnection = new HubConnection("http://localhost:8080/");
            IHubProxy myHubProxy    = hubConnection.CreateHubProxy("MyHub");

            hubConnection.Start();

            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, myHubProxy, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
        public static Task <EventHubTestListener> CreateListenerPal(string deviceName)
        {
            EventHubReceiver receiver = null;
            Stopwatch        sw       = new Stopwatch();

            sw.Start();

            EventHubClient eventHubClient          = EventHubClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString, "messages/events");
            var            eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string         partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string         consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            while (receiver == null && sw.Elapsed.TotalMinutes < MaximumWaitTimeInMinutes)
            {
                try
                {
                    receiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now.AddMinutes(-LookbackTimeInMinutes));
                }
                catch (QuotaExceededException ex)
                {
                    s_log.WriteLine($"{nameof(EventHubTestListener)}.{nameof(CreateListener)}: Cannot create receiver: {ex}");
                }
            }

            sw.Stop();

            return(Task.FromResult(new EventHubTestListener(receiver)));
        }
        //static string deviceKey;
        //static DeviceClient deviceClient;
        //static string iotHubUri = "TemperaturHub.azure-devices.net";

        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);
            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
                System.Threading.Thread.Sleep(3000);
                return;
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromHubAsync(partition, cts.Token));
            }

            Task.WaitAll(tasks.ToArray());

            Console.ReadLine();
        }
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            EventHubReceiver eventHubReceiver = null;
            Stopwatch        sw = new Stopwatch();

            sw.Start();

            eventHubClient = EventHubClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.EventHubConsumerGroup;

            while (eventHubReceiver == null && sw.Elapsed.Minutes < 1)
            {
                try
                {
                    eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now, FaultInjection.EventHubEpoch++);
                }
                catch (QuotaExceededException ex)
                {
                    Debug.WriteLine(ex);
                }
            }

            sw.Stop();

            return(eventHubReceiver);
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");

            var builder = new ServiceBusConnectionStringBuilder(connectionString)
            {
                TransportType = TransportType.Amqp,
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(builder.ToString(), iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Execute the Command
        /// </summary>
        /// <returns></returns>
        public Task Execute()
        {
            var t = Task.Run(() =>
            {
                Console.WriteLine("Receive messages\n");

                var d2cPartitions = m_EventHubClient.GetRuntimeInformation().PartitionIds;

                foreach (string partition in d2cPartitions)
                {
                    var partitionTask = receiveMessagesAsync(partition);
                    partitionTask.ContinueWith((abc) =>
                    {
                        //throw new Exception(abc.Exception.Message);
                        Console.WriteLine($" Partition {partition} failed!");
                    }, TaskContinuationOptions.OnlyOnFaulted
                                               );
                    partitionTask.Start();
                }
            });

            //m_Event.WaitOne();

            return(t);
        }
Ejemplo n.º 12
0
        // GET: Sensors
        public ActionResult Index()
        {
            Response.AddHeader("Refresh", "60");    //Refresca la página cada 60 segundos para recuperar los datos nuevos.

            if (Request.Url != Request.UrlReferrer) //No estoy refrescando la página, es el primer acceso.
            {                                       // Muestro directamente lo que hay en BD, sin ir a recibirlos del EventHub
                return(View(db.Sensors.ToList()));
            }
            else    //Vengo de la misma página en la que se muestran los datos,
            {       //bien por el refresco, bien porque he clickado en el enlace "Sensores Cloud" del menú superior
                eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

                var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

                CancellationTokenSource cts = new CancellationTokenSource();

                /*System.Console.CancelKeyPress += (s, e) =>
                 * {
                 *  e.Cancel = true;
                 *  cts.Cancel();
                 *  Console.WriteLine("Exiting...");
                 * };*/



                //var tasks = new List<Task>();
                foreach (string partition in d2cPartitions)
                {
                    //tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
                    ReceiveMessagesFromDevice(partition, cts.Token);
                }
                //Task.WaitAll(tasks.ToArray());
                return(View(db.Sensors.ToList()));
            }
        }
Ejemplo n.º 13
0
        public async Task <bool> ReadMessages()
        {
            if (eventHubClient == null)
            {
                return(false);
            }

            try
            {
                var d2cPartitions           = eventHubClient.GetRuntimeInformation().PartitionIds;
                CancellationTokenSource cts = new CancellationTokenSource();

                System.Console.CancelKeyPress += (s, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

                var tasks = new List <Task>();
                foreach (string partition in d2cPartitions)
                {
                    tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
            }

            return(true);
        }
Ejemplo n.º 14
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");
            _eventHubClient = EventHubClient.CreateFromConnectionString(_connectionString, _iotHubD2CEndpoint);

            var d2CPartitions = _eventHubClient.GetRuntimeInformation().PartitionIds;

            var cts = new CancellationTokenSource();

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (var partition in d2CPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }

            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 15
0
        //--------------------------------------------------------------------
        // Purpose:
        //     Constructor
        //
        // Notes:
        //     None.
        //--------------------------------------------------------------------
        public JimsFridgeIotHubTest()
        {
            InitializeComponent();

            mServiceClient = ServiceClient.CreateFromConnectionString(
                mConfig.mConnectionString);

            Thread.Sleep(300);

            mEventHubClient1 = EventHubClient.CreateFromConnectionString(
                mConfig.mConnectionString, mConfig.mIOTHubD2CEndpoint1);

            Thread.Sleep(300);

            // Start the receivers up
            var d2cPartitions = mEventHubClient1.GetRuntimeInformation().PartitionIds;
            var tasks         = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition));
            }

            tDisplay.Enabled = true;
        }
Ejemplo n.º 16
0
        public ReadDeviceToAzureMessages(List <IoTDevice> azureDevices, List <Value> temperatureValues, List <Value> humidityValues)
        {
            ReadDeviceToAzureMessages.HumidityValues    = humidityValues;
            ReadDeviceToAzureMessages.AzureDevices      = azureDevices;
            ReadDeviceToAzureMessages.TemperatureValues = temperatureValues;

            Console.WriteLine("Received messages: (Ctrl-C to exit.)\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 17
0
        public static void Main()
        {
     //       string connectionString =
     //ConfigurationManager.ConnectionStrings["RootManageSharedAccessKey"].ConnectionString;
     //       Action<BrokeredMessage> callback = x =>
     //       {
                
     //       };
     //       var clients = new List<SubscriptionClient>();
     //       for (int i = 0; i < 5; i++)
     //       {
     //           var client = TopicClient.CreateFromConnectionString(connectionString, "signalr_topic_push_" + i);
     //           client.
     //           client.OnMessage(callback);
     //           clients.Add(client);
     //       }
     //       Console.ReadLine();
            //var ctx = GlobalHost.ConnectionManager.GetHubContext<yourhub>();
            //ctx.Clients.Client(connectionId).< your method >

            var cloudStorage = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["DataStorage"].ConnectionString);
            var tableClient = cloudStorage.CreateCloudTableClient();
            _tickEvents = tableClient.GetTableReference("tickevents");
            _tickEvents.CreateIfNotExists();
            var host = new JobHost();
            var cancelToken = new WebJobsShutdownWatcher().Token;
            _eventHubClient = EventHubClient.CreateFromConnectionString(ConfigurationManager.ConnectionStrings["IotHubConnection"].ConnectionString, iotHubD2cEndpoint);
            var d2CPartitions = _eventHubClient.GetRuntimeInformation().PartitionIds;
            Task.WaitAll(d2CPartitions.Select(partition => ListenForEvent(host, partition, cancelToken)).ToArray(), cancelToken);
            host.RunAndBlock();
        }
Ejemplo n.º 18
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.º 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            // Why????
            CancellationTokenSource cts = new CancellationTokenSource();    // Signals to a CancellationToken that it should be canceled.

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();   // Communicates a request for cancellation.
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 20
0
        public EventsReaderViewModel()
        {
            DeviceId = Globals.DEVICE_ID;

            Log = new ObservableCollection <DataItem>();

            Console.WriteLine("Receive messages.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(Globals.CONNECTIONSTRING_OWNER, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(receiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            tasks.Add(receiveWebSocketMessagesFromDeviceAsync(cts.Token));
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            if (string.IsNullOrWhiteSpace(connectionString) && (args.Length < 1))
            {
                Console.WriteLine("ReadDeviceToCloudMessages <connectionString>");
                return;
            }

            connectionString = args[0];
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 22
0
        public static async Task ReadTelemetry(string deviceId, CancellationToken ct)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;
            var consumerGroup = ConfigurationManager.AppSettings["ConsumerGroup"];

            try
            {
                var ioTHubConnectionString = ConfigurationManager.AppSettings["IOTHubConnectionString"];
                eventHubClient = EventHubClient.CreateFromConnectionString(ioTHubConnectionString, "messages/events");
                //var ioTHubConnectionString =
                //    "Endpoint=sb://ihsuprodhkres004dednamespace.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=Rte+iSJejSjnT4pXbdbGoRd786APJGiX/5pEkk1mAU8=";
                //eventHubClient = EventHubClient.CreateFromConnectionString(ioTHubConnectionString,
                //    "iothub-ehub-raghuhub-1063-f06377c774");
                Console.WriteLine("Receiving events...\r\n");
                var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceId, eventHubPartitionsCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroup).CreateReceiver(partition);

                while (!ct.IsCancellationRequested)
                {
                    EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(10));

                    if (eventData != null)
                    {
                        Console.WriteLine("Received Message : ");
                        Console.WriteLine(Encoding.UTF8.GetString(eventData.GetBytes()));
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
        /// <summary>
        /// Recieve message from IoT Device
        /// </summary>
        /// <param name="eventHubClient">EventHubClient object value</param>
        private void ReceiveMessagesFromDeviceAsync(EventHubClient eventHubClient)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            try
            {
                Console.WriteLine("About to receive messages. Press Ctrl-C to exit.\n");

                var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

                CancellationTokenSource cts = new CancellationTokenSource();

                Console.CancelKeyPress += (s, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                    Console.WriteLine("Exiting...");
                    return;
                };

                var tasks = new List <Task>();
                foreach (string partition in d2cPartitions)
                {
                    tasks.Add(ReceiveMessagesFromDeviceAsync(eventHubClient, partition, cts.Token));
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error occurred !");
                Console.WriteLine(exception);
            }
        }
        public static void CreateListenerPalAndReceiveMessages()
        {
            EventHubClient eventHubClient          = EventHubClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString, "messages/events");
            var            eventRuntimeInformation = eventHubClient.GetRuntimeInformation();
            string         consumerGroupName       = Configuration.IoTHub.EventHubConsumerGroup;

            foreach (string partitionId in eventRuntimeInformation.PartitionIds)
            {
                try
                {
                    EventHubReceiver receiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partitionId, DateTime.Now.AddMinutes(-LookbackTimeInMinutes));
                    s_log.WriteLine($"EventHub receiver created for partition {partitionId}, listening from {LookbackTimeInMinutes}");

                    new Task(async() =>
                    {
                        while (true)
                        {
                            IEnumerable <EventData> eventDatas = await receiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(OperationTimeoutInSeconds)).ConfigureAwait(false);
                            ProcessEventData(eventDatas);
                        }
                    }).Start();
                }
                catch (QuotaExceededException ex)
                {
                    s_log.WriteLine($"{nameof(EventHubTestListener)}.{nameof(CreateListenerPalAndReceiveMessages)}: Cannot create receiver for partitionID {partitionId}: {ex}");
                }
            }
        }
        /// <summary>
        /// Execute the Command
        /// </summary>
        /// <returns></returns>
        public Task Execute()
        {
            var t = Task.Run(() =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;

                Console.WriteLine("Message Receiving ...\n");

                var d2cPartitions = m_EventHubClient.GetRuntimeInformation().PartitionIds;

                foreach (string partition in d2cPartitions)
                {
                    try
                    {
                        var eventHubReceiver = m_EventHubClient.GetConsumerGroup(m_ConsumerGroup).CreateReceiver(partition, m_StartTime);
                        Console.WriteLine($"Connected to partition {partition}");
                        var n = receiveMessagesAsync(eventHubReceiver, partition);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    //partitionTask.ContinueWith((task) =>
                    //{
                    //    Console.WriteLine(task.Exception.Message);
                    //},TaskContinuationOptions.OnlyOnFaulted);
                    //Console.WriteLine($"Connected to partition {partition}");
                }
            });

            //m_Event.WaitOne();

            return(t);
        }
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            EventHubReceiver eventHubReceiver = null;
            Stopwatch        sw = new Stopwatch();

            sw.Start();

            eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Environment.GetEnvironmentVariable("IOTHUB_EVENTHUB_CONSUMER_GROUP") ?? "$Default";

            while (eventHubReceiver == null && sw.Elapsed.Minutes < 1)
            {
                try
                {
                    eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);
                }
                catch (QuotaExceededException ex)
                {
                }
            }

            sw.Stop();

            return(eventHubReceiver);
        }
        public static async Task ReceiveMessagesFromDeviceAsync(CancellationToken cancelToken)
        {
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);
            var            d2cPartitions  = eventHubClient.GetRuntimeInformation().PartitionIds;

            await Task.WhenAll(d2cPartitions.Select(partition => ReceiveMessagesFromDeviceAsync(eventHubClient, partition, cancelToken)));
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            //currentPort.Open();
            Console.WriteLine("Press ctrl+C to exit\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            System.Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Bye...");
            };

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());

            //currentPort.Close();
        }
        public void connect()
        {
            processData("internal", "Connect Entered - running " + running.ToString());
            if (running)
            {
                return;
            }
            running     = true;
            CancelToken = new CancellationTokenSource();
            try
            {
                processData("internal", "Try ServiceClient.CreateFromConnectionString");
                ServiceClient = ServiceClient.CreateFromConnectionString(ConnectionString);
                processData("internal", "ServiceClient created");

                processData("internal", "Try EventHubClient.CreateFromConnectionString");
                EventHubClient = EventHubClient.CreateFromConnectionString(ConnectionString, IotHubD2cEndpoint);
                processData("internal", "EventHubClient created");

                var d2cPartitions = EventHubClient.GetRuntimeInformation().PartitionIds;

                var tasks = new List <Task>();
                foreach (string partition in d2cPartitions)
                {
                    Debug.WriteLine("Found partition {0}\n", partition);
                    tasks.Add(ReceiveMessagesFromDeviceAsync(partition, CancelToken.Token));
                }
            }
            catch (Exception ex)
            {
                processData("internal - exception", ex.ToString());
            }
            //Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 30
0
        async Task Receive(int partno)
        {
            var ehcg = hub.GetDefaultConsumerGroup();

            Console.WriteLine("Listening to part={0}", hub.GetRuntimeInformation().PartitionIds[partno]);
            var      rec = ehcg.CreateReceiver(hub.GetRuntimeInformation().PartitionIds[partno]);
            DateTime lst = DateTime.Now;

            while (true)
            {
                var msg = await rec.ReceiveAsync();

                var  s = Encoding.UTF8.GetString(msg.GetBytes());
                Data D;
                try
                {
                    D = Newtonsoft.Json.JsonConvert.DeserializeObject <Data>(s);
                }
                catch { continue; }
                if (msg.EnqueuedTimeUtc.AddHours(3) > lst)
                //if (DateTime.Now-lst>TimeSpan.FromSeconds(0.9))
                {
                    Console.WriteLine(s);
                    if (D.Table >= 0 && D.Table < 10 && D.No >= 0 && D.No < 9)
                    {
                        Tables[D.Table, D.No].Fill = new SolidColorBrush(Colors.Red);
                        var d = new DispatcherTimer()
                        {
                            Interval = TimeSpan.FromSeconds(0.9)
                        };
                        d.Tick += ((sender, ea) =>
                        {
                            Tables[D.Table, D.No].Fill = new SolidColorBrush(Colors.White);
                            ((DispatcherTimer)sender).Stop();
                        });
                        d.Start();
                    }
                }
                else
                {
                    Console.Write('.');
                }
                // lst = DateTime.Now;
            }
        }
Ejemplo n.º 31
0
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Configuration.IoTHub.ConsumerGroup;

            return(eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now, TestUtil.EventHubEpoch++));
        }
Ejemplo n.º 32
0
 // Please set the following connection strings in app.config for this WebJob to run:
 // AzureWebJobsDashboard and AzureWebJobsStorage
 static void Main()
 {
     _host = new JobHost();
     var connectionString = ConfigurationManager.ConnectionStrings["IoTHub"].ConnectionString;
     _eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, "messages/events");
     _serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
     Task.WaitAll(_eventHubClient.GetRuntimeInformation().PartitionIds.Select(Listen).ToArray());
     _host.RunAndBlock();
 }
Ejemplo n.º 33
0
        private EventHubReceiver CreateEventHubReceiver(string deviceName, out EventHubClient eventHubClient)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, eventHubPartitionsCount);
            string consumerGroupName = Environment.GetEnvironmentVariable("IOTHUB_EVENTHUB_CONSUMER_GROUP") ?? "$Default";

            return(eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now));
        }
Ejemplo n.º 34
0
        protected void Application_Start( object sender, EventArgs e )
        {
            ThreadPool.QueueUserWorkItem( _ =>
            {
                eventHubClient = EventHubClient.CreateFromConnectionString( connectionString, iotHubD2cEndpoint );

                var d2cPartitions = eventHubClient.GetRuntimeInformation( ).PartitionIds;

                foreach ( string partition in d2cPartitions )
                    ReceiveMessagesFromDeviceAsync( partition );
            } );
        }
        //public event MessageReceived


        public IoTMessageManager(string iotHubConnectionString)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            foreach (string partition in d2cPartitions)
                ReceiveMessagesFromDeviceAsync(partition);

            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice"/*deviceId */, deviceKey));

            //SendDeviceToCloudMessagesAsync();
        }
Ejemplo n.º 36
0
        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            foreach (string partition in d2cPartitions)
            {
                ReceiveMessagesFromDeviceAsync(partition);
            }
            Console.ReadLine();
        }
Ejemplo n.º 37
0
        public bool GetMessagesFromHub()
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(IoTHubConnectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            foreach (string partition in d2cPartitions)
            {
                ReceiveMessagesFromDeviceAsync(partition);
            }

            return true;
        }
Ejemplo n.º 38
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Receiving messages...");

            _eventHubClient = EventHubClient.CreateFromConnectionString(_connectionString, _endpoint);

            var partitions = _eventHubClient.GetRuntimeInformation().PartitionIds;
            foreach (var partition in partitions)
            {
                ReceiveMessagesFromDeviceAsync(partition);
            }

            Console.ReadLine();
        }
Ejemplo n.º 39
0
        public AzureIoTHubMonitor(CancellationTokenSource cancellationTokenSource, List<AzureIoTDevice> allDevices, DateTime? startTime = null)
        {
            this.StartTime                = startTime.HasValue ? startTime.Value:DateTime.Now;
            this._allDevices              = allDevices;
            var consumerGroupName         = "$Default";
            this._cancellationTokenSource = cancellationTokenSource;
            _eventHubClient               = EventHubClient.CreateFromConnectionString(AzureIoTHubDevices.ConnectionString, "messages/events");
            var eventHubPartitionsCount   = _eventHubClient.GetRuntimeInformation().PartitionCount;

            foreach (var d in this._allDevices)
            {
                var partition = EventHubPartitionKeyResolver.ResolveToPartition(d.DeviceId, eventHubPartitionsCount);
                _eventHubReceivers.Add(d, _eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, this.StartTime));
            }
        }
Ejemplo n.º 40
0
        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages\n");

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);
            //NOTE: if UnauthorizedException, with additional information: 
            //Put token failed. status-code: 401, status-description: The specified SAS token is expired.
            //-> change time on client pc, it's (way) off....!!
            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            foreach (string partition in d2cPartitions)
            {
                ReceiveMessagesFromDeviceAsync(partition);
            }
            Console.ReadLine();
        }
Ejemplo n.º 41
0
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
            eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            foreach (string partition in d2cPartitions)
            {
                ReceiveMessagesFromDeviceAsync(cancellationToken, partition);
            }
            while (!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(1000);
            }
        }
Ejemplo n.º 42
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Receive messages. Ctrl-C to exit.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            Console.CancelKeyPress += (src, evt) =>
            {
                evt.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            var tasks = new List<Task>();
            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
 public PartitionListenerControl(WriteToLogDelegate writeToLog,
                                 Func<Task> stopLog,
                                 Action startLog,
                                 string iotHubConnectionString,
                                 string consumerGroupName)
 {
     Task.Factory.StartNew(AsyncTrackEventData).ContinueWith(t =>
     {
         if (t.IsFaulted && t.Exception != null)
         {
             writeToLog(t.Exception.Message);
         }
     });
     this.iotHubConnectionString = iotHubConnectionString;
     this.writeToLog = writeToLog;
     this.stopLog = stopLog;
     this.startLog = startLog;
     serviceBusHelper = new ServiceBusHelper(writeToLog);
     eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, "messages/events");
     consumerGroup = string.Compare(consumerGroupName,
                                    DefaultConsumerGroupName,
                                    StringComparison.InvariantCultureIgnoreCase) == 0
                                    ? eventHubClient.GetDefaultConsumerGroup()
                                    : eventHubClient.GetConsumerGroup(consumerGroupName);
     IList<string> partitionIdList = new List<string>(eventHubClient.GetRuntimeInformation().PartitionIds);
     foreach (var id in partitionIdList)
     {
         partitionRuntumeInformationList.Add(eventHubClient.GetPartitionRuntimeInformation(id));
     }
     partitionCount = partitionRuntumeInformationList.Count;
     InitializeComponent();
     InitializeControls();
     Disposed += ListenerControl_Disposed;
 }