Ejemplo n.º 1
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("KAIT.PushNotificationService has been started");

            string storage = "DefaultEndpointsProtocol=https;AccountName=inceptionasamonitoring;AccountKey=Lwtx59G+gypbFHrk0+DT8ggdk045CQBp/qXrlUlclVqOhTyIIo7u72DnnEhWzu6bgPtnJ948Ad4M2/gSWx7osw==";

            string serviceBus = "Endpoint=sb://inceptioningess-ns.servicebus.windows.net/;SharedAccessKeyName=ListenPolicy;SharedAccessKey=jMkbgtpkPb9pwVTKLoIKhuKAgN6Q6BHHpf00kPQ2AxU=";


            string eventHubName = "interactionsnotifications";

            EventHubClient client = EventHubClient.CreateFromConnectionString(serviceBus, eventHubName);

            Trace.TraceInformation("Consumer group is: " + client.GetDefaultConsumerGroup().GroupName);

            _host = new EventProcessorHost("singleworker", eventHubName, client.GetDefaultConsumerGroup().GroupName, serviceBus, storage);

            Trace.TraceInformation("Created event processor host...");



            return(result);
        }
Ejemplo n.º 2
0
        private void ReceiveMessagesFromDevice(string partition, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.Now.AddDays(-1));
            //var eventHubReceiver = eventHubClient.GetConsumerGroup("webapp").CreateReceiver(partition, DateTime.Now.AddDays(-1));
            int i = 0;

            while (i < 4)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = eventHubReceiver.Receive();
                //if (eventData == null) continue;

                if (eventData == null)
                {
                    break;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());

                /*MemoryStream stream1 = new MemoryStream(eventData.GetBytes());
                 * DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Sensor));
                 *
                 * stream1.Position = 0;
                 * Sensor sensor = (Sensor)ser.ReadObject(stream1);*/

                JavaScriptSerializer json_serializer = new JavaScriptSerializer();

                Sensor sensor = json_serializer.Deserialize <Sensor>(data);

                db.Sensors.Add(sensor);
                db.SaveChanges();
                i++;

                //Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);

                /*Sensor sensor = new Sensor (data.);
                 * db.Sensors.Add(sensor);
                 * db.SaveChanges();*/
            }

            eventHubReceiver.Close();

            //return RedirectToAction("Index");


            return;
        }
Ejemplo n.º 3
0
        private async static Task ReceiveMessagesFromDeviceAsync(string partition)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());

                evData d = JsonConvert.DeserializeObject <evData>(data);

                StreamWriter writer = new StreamWriter("c:\\gps\\download\\"
                                                       + d.id + "." + DateTime.Now.Year + "." + DateTime.Now.Month
                                                       + "." + DateTime.Now.Day + "." + DateTime.Now.Hour + "."
                                                       + DateTime.Now.Minute + "." + DateTime.Now.Second + ".csv");

                writer.Write(d.data);
                writer.Close();
                Console.WriteLine(string.Format("Message received from {0}.\n{1}", d.id, d.data));
            }
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("EventsForwarding OnStart()...\n");

            connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            eventHubName = ConfigurationManager.AppSettings["Microsoft.ServiceBus.EventHubName"];

            string storageAccountName = ConfigurationManager.AppSettings["AzureStorage.AccountName"];
            string storageAccountKey = ConfigurationManager.AppSettings["AzureStorage.Key"];
            string storageAccountString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                storageAccountName, storageAccountKey);

            string iotHubConnectionString = ConfigurationManager.AppSettings["AzureIoTHub.ConnectionString"];
            iotHubServiceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);

            var defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();

            string eventProcessorHostName = "SensorEventProcessor";
            EventProcessorHost eventProcessorHost = new EventProcessorHost(eventProcessorHostName, eventHubName, defaultConsumerGroup.GroupName, connectionString, storageAccountString);
            eventProcessorHost.RegisterEventProcessorAsync<SensorEventProcessor>().Wait();

            Trace.TraceInformation("Receiving events...\n");

            return result;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Receive Messages from device.  By default if reads partition 0 but you can specifiy the partition
        /// </summary>
        /// <param name="partition"></param>
        /// <returns></returns>
        public static async Task <EventData> ReceiveMessagesFromDeviceAsync(string partition = "0")
        {
            try
            {
                // If you are running this from a client you are likely to have to open up ports on the client
                // firewall of specifiy HTTP for transport
                //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

                // get all messages
                var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition,
                                                                                               DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0)));

                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData != null)
                {
                    string data = Encoding.UTF8.GetString(eventData.GetBytes());

                    Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
                }

                return(eventData);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{Utils.FormatExceptionMessage(ex)}");
                throw ex;
            }
        }
Ejemplo n.º 6
0
        static void PrintMessages(string partitionId, long offset, int numberOfEvents)
        {
            EventHubReceiver receiver;

            try
            {
                receiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partitionId, offset.ToString(), true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("No data for the specified offset in this partition.");
                return;
            }

            try
            {
                foreach (var e in receiver.Receive(numberOfEvents, TimeSpan.FromMinutes(1)))
                {
                    Console.WriteLine(Encoding.UTF8.GetString(e.GetBytes()));
                    Console.WriteLine("----");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            receiver.Close();
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            string                ehname     = "<eventhubname>";
            string                connection = "Endpoint=sb://<eventhubnamespace>.servicebus.windows.net/;SharedAccessKeyName=<policy>;SharedAccessKey=<key>;TransportType=Amqp";
            MessagingFactory      factory    = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub       = factory.CreateEventHubClient(ehname);
            EventHubConsumerGroup group      = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever   = group.CreateReceiver("0");

            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        string message = Encoding.UTF8.GetString(data.GetBytes());
                        Console.WriteLine(message + " " + DateTime.Now);
                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
Ejemplo n.º 8
0
        static async Task Listen(string partitionId)
        {
            Console.WriteLine("Listening to partition " + partitionId);

            // receive all events after UtcNow (replay events)
            var receiver = await _eventHubClient.GetDefaultConsumerGroup().CreateReceiverAsync(partitionId, DateTime.UtcNow);

            while (true)
            {
                // wait for a event to receive
                var eventData = await receiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                // read event data
                var json       = Encoding.ASCII.GetString(eventData.GetBytes());
                var powerUsage = JsonConvert.DeserializeObject <PowerUsage>(json);
                var deviceId   = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                Console.WriteLine("Event received: " + json);

                // post to signalr (notify web clients)
                var signalrRequest = new DevicePowerUsage
                {
                    Id    = Guid.Parse(deviceId),
                    Value = powerUsage.Value
                };
                await HttpService.Post("api/deviceupdate", signalrRequest);
            }
        }
Ejemplo n.º 9
0
        private async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                var data = Encoding.UTF8.GetString(eventData.GetBytes());
                Debug.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);

                var temperature = JsonConvert.DeserializeObject <TemperatureData>(data);
                temperature.PartitionId = partition;

                var hub = new TemperatureHub();
                await hub.NotifyClient(temperature);
            }
        }
Ejemplo n.º 10
0
        private static void EventHubReceive()
        {
            var ehName     = "davnaeventhub";
            var connection = "Endpoint=sb://alewife.servicebus.windows.net/;SharedAccessKeyName=Receiver;SharedAccessKey=3jaTeykwRu84x93OpW3DftRO1WSHt4oi7QB0FRyHoyg=;TransportType=Amqp";

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection);

            EventHubClient        ehub     = factory.CreateEventHubClient(ehName);
            EventHubConsumerGroup group    = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      receiver = group.CreateReceiver("1");

            while (true)
            {
                EventData data = receiver.Receive();

                if (data != null)
                {
                    var message = Encoding.UTF8.GetString(data.GetBytes());

                    Console.WriteLine("PartitionKey: {0}", data.PartitionKey);
                    Console.WriteLine("SequenceNumber: {0}", data.SequenceNumber);
                    Console.WriteLine(message);
                }
            }
        }
Ejemplo n.º 11
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var min = Convert.ToInt32(ConfigurationManager.AppSettings["minutes"]);
            var dte = DateTime.UtcNow.AddMinutes(min);
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, dte);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Message received => Partition: {0}, Data: '{1}'", partition, data);
                Console.ResetColor();
                SendMessagesToRestApi(data);
            }
        }
Ejemplo n.º 12
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);
            }
        }
        private async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            try
            {
                processData("internal", $"Start listening to Partition: {partition}");
                var eventHubReceiver = EventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }
                    EventData eventData = await eventHubReceiver.ReceiveAsync();

                    if (eventData == null)
                    {
                        continue;
                    }

                    string data   = Encoding.UTF8.GetString(eventData.GetBytes());
                    string device = eventData.SystemProperties.ContainsKey("iothub-connection-device-id")
                    ? eventData.SystemProperties["iothub-connection-device-id"].ToString().Trim()
                    : null;
                    Debug.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
                    processData(device, data);
                }
                Debug.WriteLine("Cancel Receiver task");
            }
            catch (Exception ex)
            {
                processData("internal - exception", ex.ToString());
            }
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            string                ehname     = "<eventhubname>";
            string                connection = "<eventhubconnectionstring>,TransportType=Amqp";
            MessagingFactory      factory    = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub       = factory.CreateEventHubClient(ehname);
            EventHubConsumerGroup group      = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever   = group.CreateReceiver("0");

            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        string message = Encoding.UTF8.GetString(data.GetBytes());
                        //Console.WriteLine("Partition Key: {0}", data.PartitionKey);
                        Console.WriteLine(message);
                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
        public async Task<string> OpenAsync(CancellationToken cancellationToken)
        {
            var builder = new ServiceBusConnectionStringBuilder(_connectionString)
            {
                TransportType = TransportType.Amqp
            };
            _messagingFactory = MessagingFactory.CreateFromConnectionString(builder.ToString());
            _eventHubClient = _messagingFactory.CreateEventHubClient(_eventHubName);
            _consumerGroup = !string.IsNullOrEmpty(_consumerGroupName)
                ? _eventHubClient.GetConsumerGroup(_consumerGroupName)
                : _eventHubClient.GetDefaultConsumerGroup();

            _eventProcessorFactory = new EventProcessorFactory();
            _leaseRepository = new ReliableStateLeaseRepository(_reliableStateManager);
            _checkpointManager = new CheckpointManager(_leaseRepository); 

            var allocatedPartitions = await new EventHubPartitionPartitionAllocationStrategy(_serviceName, _partitionId)
                .AllocateAsync(_eventHubClient, new FabricClient());

            foreach (var partition in allocatedPartitions)
            {
                var lease = await _leaseRepository.GetOrCreateAsync(_connectionString, _consumerGroupName, _eventHubName, partition);

                await _consumerGroup.RegisterProcessorFactoryAsync(lease, _checkpointManager, _eventProcessorFactory);
            }

            return string.Concat(_eventHubName, " @ ", _connectionString);
        }
Ejemplo n.º 16
0
        private async Task ReceiveMessagesFromDeviceAsync(string partition)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.Now);

            while (true)
            {
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Console.WriteLine(string.Format("Message received. Partition: {0} Data: '{1}'", partition, data));

                WeatherRecord record = JsonConvert.DeserializeObject <WeatherRecord>(data);

                try
                {
                    WriteToTable(record);
                }
                catch (Exception ex)
                {
                    ex = ex;
                }
            }
        }
Ejemplo n.º 17
0
        public override void Run()
        {
            string eventHubConnectionString = System.Configuration.ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            string blobConnectionString     = System.Configuration.ConfigurationManager.AppSettings["AzureStorageConnectionString"];
            string workerName   = RoleEnvironment.CurrentRoleInstance.Role.Name;
            string eventHubName = System.Configuration.ConfigurationManager.AppSettings["EventHubName"];

            // Event Hub client
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName);

            // Default Consumer Group
            EventHubConsumerGroup defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();

            // Create the EventProcessorHost
            host = new EventProcessorHost(workerName, eventHubName, defaultConsumerGroup.GroupName, eventHubConnectionString, blobConnectionString);

            // Register our event processor
            host.RegisterEventProcessorAsync <SimpleEventProcessor>();

            // Wait forever
            while (true)
            {
                Task.Delay(60 * 1000);
            }
        }
Ejemplo n.º 18
0
        private async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string           data    = Encoding.UTF8.GetString(eventData.GetBytes());
                IOTMessageFormat message = JsonConvert.DeserializeObject <IOTMessageFormat>(data);
                // bool isAlert = Convert.ToBoolean(eventData.Properties["waterAlert"]);
                if (message.isDry && notificationSentCount < 5)
                {
                    MyNotification.SendFireBaseNotification(configs.FireBaseConnectionString, message.message);
                    notificationSentCount++;
                }
                else
                {
                    MyNotification.SendFireBaseNotification(configs.FireBaseConnectionString, message.message);
                }
                Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
            }
        }
Ejemplo n.º 19
0
        public async void ReadUsingEventHubProcessor()
        {
            string serviceBusNamespace = "iotmc-ns";
            string eventHubName        = "iotmc";
            string eventHubSASKeyName  = "Device01";
            string eventHubSASKey      = "<< Add your SAS here >>";

            string storageAccountName = "iotmc";
            string storageAccountKey  = "<< add your Storage Account key here >>";

            string storageConnectionString  = String.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccountName, storageAccountKey);
            string eventHubConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey(
                ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty),
                eventHubSASKeyName,
                eventHubSASKey);

            EventHubClient        eventHubClient        = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName);
            EventHubConsumerGroup eventHubConsumerGroup = eventHubClient.GetDefaultConsumerGroup();

            EventProcessorHost eventProcessorHost = new EventProcessorHost("MSTechDemoWorker", eventHubClient.Path, eventHubConsumerGroup.GroupName, eventHubConnectionString, storageConnectionString);
            //await eventProcessorHost.RegisterEventProcessorAsync<EventHubEventProcessor>();

            //Ignore older messages even if they are still in the event hub store
            Task t = eventProcessorHost.RegisterEventProcessorAsync <EventHubEventProcessor>(new EventProcessorOptions()
            {
                InitialOffsetProvider = (partitionId) => { return(DateTime.UtcNow.AddHours(-1)); }
            });

            t.Wait();
        }
Ejemplo n.º 20
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(2));

                if (eventData == null)
                {
                    continue;
                }

                var deviceId = eventData.SystemProperties["iothub-connection-device-id"] as string;
                deviceId = deviceId.Substring("dispositivo".Length);


                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Debug.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
                var telemetria = JsonConvert.DeserializeObject <Telemetria>(data);
                telemetria.IdDispositivo = int.Parse(deviceId);

                TelemetriaHub.InviaMessaggio(telemetria);
            }
        }
Ejemplo n.º 21
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    return;
                }

                string      data = Encoding.UTF8.GetString(eventData.GetBytes());
                BaseMessage msg  = MessageHelper.ToObject(data);
                if (msg != null)
                {
                    msgReceiveQueue.Enqueue(msg);
                }
            }
        }
Ejemplo n.º 22
0
        private async static Task ReceiveMessagesFromMonitorAsync(string partition)
        {
            var eventHubReceiver = operHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.Now);

            while (true)
            {
                EventData eventData = null;
                try
                {
                    eventData = await eventHubReceiver.ReceiveAsync();

                    Trace.TraceInformation("RAW MONITOR RECEIVED:{1}: {0}", Encoding.UTF8.GetString(eventData.GetBytes()), DateTime.Now);
                    Console.WriteLine("RAW MONITOR RECEIVED:{1}: {0}", Encoding.UTF8.GetString(eventData.GetBytes()), DateTime.Now);
                }
                catch (Exception e)
                {
                    Trace.TraceWarning("{0}:TIMEOUT at MONITOR occurred", DateTime.Now);
                    Console.WriteLine("{0}:TIMEOUT at MONITOR occurred", DateTime.Now);
                }

                if (eventData == null)
                {
                    continue;
                }


                IoTHubMessage msg = new IoTHubMessage();
                msg.enqueuedTime = eventData.EnqueuedTimeUtc;
                msg.message      = Encoding.UTF8.GetString(eventData.GetBytes());
                //Trace.TraceInformation("RECEIVED: {0}", msg.message);
                //Console.WriteLine("RECEIVED: {0}", msg.message);

                ProcessMonitorMessageAsync(msg);
            }
        }
Ejemplo n.º 23
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();
        }
Ejemplo n.º 24
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            TimeZone localTimeZone = TimeZone.CurrentTimeZone;

            DateTime startDateTimeUtc = DateTimeOffset.Parse(startDateTime).UtcDateTime;
            DateTime currentUTC       = DateTime.UtcNow;

            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, startDateTimeUtc);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
            }
        }
Ejemplo n.º 25
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.º 26
0
        private async static Task ReceiveMessagesFromDeviceAsync(CancellationToken cancellationToken, string partition)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (!cancellationToken.IsCancellationRequested)
            {
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Console.WriteLine(string.Format("Message received. Partition: {0} Data: '{1}'", partition, data));

                dynamic dataObject = JsonConvert.DeserializeObject(data);
                Console.WriteLine(string.Format("Throttle received: {0}", dataObject.throttle));
                if (dataObject.throttle > MAX_THROTTLE)
                {
                    Console.WriteLine("throttle over " + MAX_THROTTLE);
                    SendCloudToDeviceMessageAsync().Wait();
                }
            }
        }
Ejemplo n.º 27
0
        public void MessageProcessingWithPartitionDistribution(ConsumerGroupDescription group)
        {
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, this.eventHubName);

            // Get the default Consumer Group
            //defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();

            string blobConnectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"]; // Required for checkpoint/state

            if (null == group)
            {
                //Use default consumer group
                EventHubConsumerGroup defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();
                eventProcessorHost = new EventProcessorHost("singleworker", eventHubClient.Path, defaultConsumerGroup.GroupName, this.eventHubConnectionString, blobConnectionString);
            }
            else
            {
                //Use custom consumer group
                eventProcessorHost = new EventProcessorHost("singleworker", eventHubClient.Path, group.Name, this.eventHubConnectionString, blobConnectionString);
            }

            //Only use events from the time the sender is started.
            EventProcessorOptions options = new EventProcessorOptions();

            options.InitialOffsetProvider = (partitionId) => DateTime.UtcNow;

            eventProcessorHost.RegisterEventProcessorAsync <SimpleEventProcessor>(options).Wait();
        }
Ejemplo n.º 28
0
        private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
            while (true)
            {
                if (ct.IsCancellationRequested) break;

                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null) continue;

                var sensorData = eventData.GetBytes();

                // this is how to calculate the temperature according to the TI docs
                //var ambientTemp = calculator.CalculateAmbientTemperature(sensorData, temperatureScale);
                //var targetTemp = calculator.CalculateTargetTemperature(sensorData, ambientTemp, temperatureScale);

                //Console.WriteLine($"Partion {partition} - {targetTemp}, {ambientTemp}");

                // this is how the Azure IoT Hub Gateway module ble_printer does it 
                double ambient = 0, target = 0;

                sensortag_temp_convert(BitConverter.ToUInt16(sensorData, 2), BitConverter.ToUInt16(sensorData, 0), ref ambient, ref target);

                Console.WriteLine($"Partion {partition} - {target}, {ambient}");
            }
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            // Start a worker that consumes messages from the event hub.
            EventHubClient eventHubReceiveClient = EventHubClient.CreateFromConnectionString(GetAmqpConnectionString(), eventHubName);
            var            subscriberGroup       = eventHubReceiveClient.GetDefaultConsumerGroup();

            EventHubDescription eventHub = NamespaceManager.CreateFromConnectionString(GetAmqpConnectionString()).GetEventHub(eventHubName);

            // Register event processor with each shard to start consuming messages

            List <Worker> allWorkers = new List <Worker>();

            foreach (var partitionId in eventHub.PartitionIds)
            {
                Worker temp = new Worker(subscriberGroup, partitionId);
                allWorkers.Add(temp);
            }

            // Wait for the user to exit this application.
            Console.WriteLine("\nPress ENTER to exit...\n");
            Console.ReadLine();
            foreach (var w in allWorkers)
            {
                w.RequestStop();
            }
        }
Ejemplo n.º 30
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.º 31
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.º 32
0
        public async Task ReadAllAsync(DateTime startTime)
        {
            PrepareToRead();


            try {
                foreach (var p in _partitions)
                {
                    var rcv = await _client.GetDefaultConsumerGroup().CreateReceiverAsync(p.PartitionId, startTime.ToUniversalTime());

                    _runningTasks.Add(p.ReadAsync(rcv, _cancellation));
                }
            }
            catch (OperationCanceledException ex)
            {
                Debug.WriteLine("tasks cancelled");
            }
        }
Ejemplo n.º 33
0
        public void MessageProcessingWithPartitionDistribution()
        {
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, this.eventHubName);

            // Get the default Consumer Group
            defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();
            string blobConnectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"]; // Required for checkpoint/state

            eventProcessorHost = new EventProcessorHost("singleworker", eventHubClient.Path, defaultConsumerGroup.GroupName, this.eventHubConnectionString, blobConnectionString);
            eventProcessorHost.RegisterEventProcessorAsync <SimpleEventProcessor>().Wait();
        }
 public async void ProcessEvents()
 {
     eventHubName = "azureguidanceevnthub";
     connectionString = GetServiceBusConnectionString();
     NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
     eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
     defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();
     string blobConnectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"]; // Required for checkpoint/state
     eventProcessorHost = new EventProcessorHost("AzureGuidanceReceiver", eventHubClient.Path, defaultConsumerGroup.GroupName, connectionString, blobConnectionString);
     await eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>();
                 
 }
Ejemplo n.º 35
0
 public Task InitializeEventProcessor(string connectionString, string eventHubName, string storageConnectionString, string path, string cGroup = null, string vin = null, string activityId = null)
 {
     Filter.BlockingCollection = new BlockingCollection<string>(int.MaxValue);
     Filter.EventDataCollection = new BlockingCollection<EventData>(int.MaxValue);
     Filter.Path = path;
     Filter.Vin = vin;
     Filter.ActivityId = activityId;
     this.eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
     this.consumerGroup = string.IsNullOrWhiteSpace(cGroup)
          ? eventHubClient.GetDefaultConsumerGroup()
          : eventHubClient.GetConsumerGroup(cGroup);
     this.eventProcessorHost = new EventProcessorHost("EventHubReader", eventHubClient.Path, this.consumerGroup.GroupName, connectionString, storageConnectionString);
     return this.eventProcessorHost.RegisterEventProcessorAsync<EventProcessor>();
 }
 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;
 }
 public PartitionListenerControl(WriteToLogDelegate writeToLog,
                                 Func<Task> stopLog,
                                 Action startLog,
                                 ServiceBusHelper serviceBusHelper,
                                 ConsumerGroupDescription consumerGroupDescription,
                                 IEnumerable<PartitionDescription> partitionDescriptions)
 {
     Task.Factory.StartNew(AsyncTrackEventData).ContinueWith(t =>
     {
         if (t.IsFaulted && t.Exception != null)
         {
             writeToLog(t.Exception.Message);
         }
     });
     this.writeToLog = writeToLog;
     this.stopLog = stopLog;
     this.startLog = startLog;
     this.serviceBusHelper = serviceBusHelper;
     eventHubDescription = serviceBusHelper.NamespaceManager.GetEventHub(consumerGroupDescription.EventHubPath);
     eventHubClient = EventHubClient.CreateFromConnectionString(GetAmqpConnectionString(serviceBusHelper.ConnectionString),
                                                                                        consumerGroupDescription.EventHubPath);
     consumerGroup = string.Compare(consumerGroupDescription.Name,
                                    DefaultConsumerGroupName,
                                    StringComparison.InvariantCultureIgnoreCase) == 0
                                    ? eventHubClient.GetDefaultConsumerGroup()
                                    : eventHubClient.GetConsumerGroup(consumerGroupDescription.Name);
     IList<string> partitionIdList = partitionDescriptions.Select(pd => pd.PartitionId).ToList();
     foreach (var id in partitionIdList)
     {
         partitionRuntumeInformationList.Add(eventHubClient.GetPartitionRuntimeInformation(id));
     }
     partitionCount = partitionRuntumeInformationList.Count;
     InitializeComponent();
     InitializeControls();
     Disposed += ListenerControl_Disposed;
 }
        public async Task<string> OpenAsync(CancellationToken cancellationToken)
        {
            await mOptions.PrepareAsync();

            var useDefaultConsumerGroup = !string.IsNullOrEmpty(mOptions.EventHubConsumerGroupName);


            mMessagingFactory = MessagingFactory.CreateFromConnectionString(mOptions.EventHubConnectionString);
            mEventHubClient = mMessagingFactory.CreateEventHubClient(mOptions.EventHubName);
            mConsumerGroup = useDefaultConsumerGroup ?
                                mEventHubClient.GetConsumerGroup(mOptions.EventHubConsumerGroupName)
                              : mEventHubClient.GetDefaultConsumerGroup();

           


            return string.Concat(mEventHubNamespace, "/",
                                 mOptions.EventHubName, "/",
                                 useDefaultConsumerGroup ? "<default group>" : mOptions.EventHubConsumerGroupName);

        }