Ejemplo n.º 1
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("IoT Hub Quickstarts - Read device to cloud messages. Ctrl-C to exit.\n");

            string EventHubconnectionString = "<Event Hub connection string>";

            s_eventHubClient = EventHubClient.CreateFromConnectionString(EventHubconnectionString);

            string IoTHubconnectionString = "<IoT Hub Service(IoTOwner) connection string>";

            s_iothubRegistryManager = RegistryManager.CreateFromConnectionString(IoTHubconnectionString);

            // Create a PartitionReciever for each partition on the hub.
            var runtimeInfo = await s_eventHubClient.GetRuntimeInformationAsync();

            var d2cPartitions = runtimeInfo.PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            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));
            }

            // Wait for all the PartitionReceivers to finsih.
            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 2
0
        public async Task SendBatch()
        {
            TestUtility.Log("Sending multiple Events via EventHubClient.SendAsync(IEnumerable<EventData>)");

            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);

                try
                {
                    using (var eventData1 = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!")))
                        using (var eventData2 = new EventData(Encoding.UTF8.GetBytes("This is another message in the batch!")))
                        {
                            eventData2.Properties["ContosoEventType"] = "some value here";
                            await ehClient.SendAsync(new[] { eventData1, eventData2 });
                        }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
Ejemplo n.º 3
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());
        }
Ejemplo n.º 4
0
        private async Task SendEventHubMessage()
        {
#if EVENTHUB
            if (String.IsNullOrEmpty(Simulator.AccessKey))
            {
                await Popups.ShowAsync("Access Key is missing");

                return;
            }

            var connectionString        = $"Endpoint=sb://{Simulator.DefaultEndPoint}.servicebus.windows.net/;SharedAccessKeyName={Simulator.AccessKeyName};SharedAccessKey={Simulator.AccessKey}";
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString)
            {
                EntityPath = Simulator.HubName
            };

            var client = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            await client.SendAsync(new EventData(GetMessageBytes()));

            ReceivedContennt = $"{DateTime.Now} {SimulatorCoreResources.SendMessage_MessageSent}";
#else
            await Task.FromResult(default(object));
#endif
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Listener for event hub
        /// </summary>
        /// <param name="connStr">Connection string</param>
        /// <param name="path">The Path to the Event Hub </param>
        /// <param name="startTime"></param>
        /// <param name="consumerGroup"></param>
        public TeleMetryListener(string connStr, string path = "messages/events", DateTime?startTime = null, string consumerGroup = "$Default")
        {
            this.m_Path          = path;
            this.m_ConsumerGroup = consumerGroup;
            this.m_ConnStr       = connStr;

            if (startTime.HasValue)
            {
                this.m_StartTime = startTime.Value;
            }
            else
            {
                this.m_StartTime = DateTime.UtcNow;
            }

            if (m_Path != null)
            {
                m_EventHubClient = EventHubClient.CreateFromConnectionString(m_ConnStr, m_Path);
            }
            else
            {
                m_EventHubClient = EventHubClient.CreateFromConnectionString(m_ConnStr);
            }
        }
Ejemplo n.º 6
0
        static void ScanVehicles(int laneNo)
        {
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);

            while (true)
            {
                try
                {
                    var vehicleNo   = $"{registrationState} 0{laneNo} { RandomGenerator.GetLetter()} { RandomGenerator.Get4DigitNumber()}";
                    var tollCharges = RandomGenerator.GetRandomCharge();
                    var message     = $"{{  \"LaneNo\" : {laneNo}, \"VehicleNo\" : \"{vehicleNo}\", \"Payment\" : {{ \"Charges\" : {tollCharges}, \"Status\" : \"{(tollCharges != 0)}\" }}, \"Timestamp\" : \"{DateTime.Now}\" }}";
                    Console.WriteLine($"{DateTime.Now} > Scanned Vehicle: {vehicleNo}");
                    eventHubClient.Send(new EventData(Encoding.UTF8.GetBytes(message)));
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
                    Console.ResetColor();
                }

                Thread.Sleep(RandomGenerator.GetRandomInterval());
            }
        }
Ejemplo n.º 7
0
        static void EventHubIngestion()
        {
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
            int counter        = 0;

            while (true)
            {
                int recordsPerMessage = 3;
                try
                {
                    List <string> records = Enumerable
                                            .Range(0, recordsPerMessage)
                                            .Select(recordNumber => $"{{\"timeStamp\": \"{DateTime.UtcNow.AddSeconds(100 * counter)}\", \"name\": \"{$"name {counter}"}\", \"metric\": {counter + recordNumber}, \"source\": \"EventHubMessage\"}}")
                                            .ToList();
                    string recordString = string.Join(Environment.NewLine, records);

                    EventData eventData = new EventData(Encoding.UTF8.GetBytes(recordString));
                    Console.WriteLine($"sending message {counter}");
                    // Optional "dynamic routing" properties for the database, table, and mapping you created.
                    //eventData.Properties.Add("Database", "TestDatabase");
                    //eventData.Properties.Add("Table", "TestTable");
                    //eventData.Properties.Add("IngestionMappingReference", "TestMapping");
                    eventHubClient.Send(eventData);
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                    Console.ResetColor();
                }

                counter += recordsPerMessage;

                Thread.Sleep(10000);
            }
        }
        public async Task Send_with_envelopes_sends_multiple_messages_correctly()
        {
            // Arrange
            var eventHubClient = EventHubClient.CreateFromConnectionString(_connectionString);
            var eventSender    = new EventMessageSender(eventHubClient);
            var serializer     = new EventDataSerializer();
            var sut            = new EventHubMessageBus(eventSender);

            var envelopes = new Fixture()
                            .CreateMany <Message>()
                            .Select(message => new Envelope(
                                        messageId: Guid.NewGuid(),
                                        message,
                                        operationId: $"{Guid.NewGuid()}",
                                        correlationId: Guid.NewGuid(),
                                        contributor: $"{Guid.NewGuid()}"))
                            .ToList();

            IEnumerable <PartitionReceiver> receivers = await GetReceivers(eventHubClient, _consumerGroupName);

            // Act
            await sut.Send(envelopes, CancellationToken.None);

            // Assert
            IEnumerable <EventData> received = await ReceiveAll(receivers);

            await eventHubClient.CloseAsync();

            IEnumerable <Envelope> actual = from eventData in received
                                            select serializer.Deserialize(eventData);

            actual.Should().BeEquivalentTo(
                envelopes,
                opts =>
                opts.RespectingRuntimeTypes());
        }
//        const int MAXTRANSMISSIONSIZE = 2 * 1024;

        public static async Task obEventHub(string newClientContent, TraceWriter log)
        {
            string EventHubConnectionString = GetEnvironmentVariable("eventHubConnection");
            string EventHubName             = GetEnvironmentVariable("eventHubName");

            if (EventHubConnectionString.Length == 0 || EventHubName.Length == 0)
            {
                log.Error("Values for eventHubConnection and eventHubName are required.");
                return;
            }

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            foreach (var bundleOfMessages in bundleMessages(newClientContent, log))
            {
                //log.Info(String.Format("-----Outgoing message is: {0}", bundleOfMessages));

                await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(bundleOfMessages)));
            }
        }
Ejemplo n.º 10
0
        static async Task SendingRandomMessages()
        {
            var eventHubConnectionString = GetEventHubConnectionString();
            var eventHubClient           = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName);

            while (true)
            {
                try
                {
                    var message = Guid.NewGuid().ToString();
                    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now.ToString(), message);
                    await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{0} > Exception: {1}", DateTime.Now.ToString(), exception.Message);
                    Console.ResetColor();
                }

                // we send it slowly...
                await Task.Delay(200);
            }
        }
        /// <summary>
        ///   Performs the tasks needed to initialize and set up the environment for the test scenario.
        ///   When multiple instances are run in parallel, the setup will take place once, prior to the
        ///   execution of the first test instance.
        /// </summary>
        ///
        public async override Task GlobalSetupAsync()
        {
            await base.GlobalSetupAsync().ConfigureAwait(false);

            s_scope = await EventHubScope.CreateAsync(4).ConfigureAwait(false);

            s_client    = EventHubClient.CreateFromConnectionString(TestUtility.BuildEventHubsConnectionString(s_scope.EventHubName));
            s_eventBody = EventGenerator.CreateRandomBody(Options.Size);

            var partition = (await s_client.GetRuntimeInformationAsync().ConfigureAwait(false)).PartitionIds[0];

            s_sender = s_client.CreatePartitionSender(partition);

            // Publish an empty event to force the connection and link to be established.

            using var batch = s_sender.CreateBatch();

            if (!batch.TryAdd(new EventData(Array.Empty <byte>())))
            {
                throw new InvalidOperationException("The empty event could not be added to the batch during global setup.");
            }

            await s_sender.SendAsync(batch).ConfigureAwait(false);
        }
Ejemplo n.º 12
0
        static void SendMessages()
        {
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString);

            for (int i = 0; i < 1; i++)
            {
                try
                {
                    var message = Guid.NewGuid().ToString();
                    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, message);
                    var eventData = new EventData(Encoding.UTF8.GetBytes(message));
                    eventData.PartitionKey = "device" + i;
                    eventHubClient.Send(eventData);
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                    Console.ResetColor();
                }

                Thread.Sleep(200);
            }
        }
Ejemplo n.º 13
0
        public async Task <(string, bool)> IsHealthy(HttpContext context, LivenessExecutionContext livenessContext, CancellationToken cancellationToken = default)
        {
            try
            {
                var connectionStringBuilder = new EventHubsConnectionStringBuilder(_connectionString)
                {
                    EntityPath = _eventHubName
                };

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

                await eventHubClient.GetRuntimeInformationAsync();

                return(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_OK_MESSAGE, true);
            }
            catch (Exception ex)
            {
                var message = !livenessContext.IsDevelopment ? string.Format(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_ERROR_MESSAGE, livenessContext.Name)
                    : $"Exception {ex.GetType().Name} with message ('{ex.Message}')";

                return(message, false);
            }
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            colorMessage("Cheese Cave Operator\n", ConsoleColor.Yellow);

            // Create an EventHubClient instance to connect to the IoT Hub Event Hubs-compatible endpoint.
            var connectionString = new EventHubsConnectionStringBuilder(new Uri(s_eventHubsCompatibleEndpoint), s_eventHubsCompatiblePath, s_iotHubSasKeyName, s_iotHubSasKey);

            s_eventHubClient = EventHubClient.CreateFromConnectionString(connectionString.ToString());

            // Create a PartitionReceiver for each partition on the hub.
            var runtimeInfo   = s_eventHubClient.GetRuntimeInformationAsync().GetAwaiter().GetResult();
            var d2cPartitions = runtimeInfo.PartitionIds;

            // Create receivers to listen for messages.
            var tasks = new List <Task>();

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

            // Wait for all the PartitionReceivers to finish.
            Task.WaitAll(tasks.ToArray());
        }
        public static async Task SendJSONMessagesAsync(string eventId, string connectionString)
        {
            // write 3 events
            List <EventData> events = new List <EventData>();

            string[] ids = new string[3];
            for (int i = 0; i < 3; i++)
            {
                ids[i] = eventId + $"TestEvent{i}";
                JObject jo = new JObject
                {
                    { "value", ids[i] }
                };
                var evt = new EventData(Encoding.UTF8.GetBytes(jo.ToString(Formatting.None)));
                evt.Properties.Add("TestIndex", i);
                events.Add(evt);
            }

            EventHubsConnectionStringBuilder builder = new EventHubsConnectionStringBuilder(connectionString);

            builder.EntityPath = Constants.InputJsonEventHubName;
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(builder.ToString());
            await eventHubClient.SendAsync(events);
        }
Ejemplo n.º 16
0
        public void Run(string connectionString, string hubName, string measureNameFilter)
        {
            NamespaceManager    nsmgr = NamespaceManager.CreateFromConnectionString(connectionString);
            EventHubDescription desc  = nsmgr.GetEventHub(hubName);

            string consumerGroupName = _consumerGroupPrefix + DateTime.UtcNow.Ticks.ToString();
            ConsumerGroupDescription consumerGroupDesc = nsmgr.CreateConsumerGroupIfNotExists(new ConsumerGroupDescription(hubName, consumerGroupName));

            EventHubClient client = EventHubClient.CreateFromConnectionString(connectionString, hubName);

            int numPartitions = desc.PartitionCount;

            _receivers = new EventHubReceiver[numPartitions];
            //_receiversLastUpdate = new DateTime[numPartitions];
            //for (int i = 0; i < numPartitions; i++)
            //{
            //    _receiversLastUpdate[i] = DateTime.UtcNow;
            //}

            _tasks             = new Task[numPartitions];
            _buffers           = new Dictionary <string, CircularBuffer <SensorDataContract> >();
            _measureNameFilter = measureNameFilter;

            for (int iPart = 0; iPart < desc.PartitionCount; iPart++)
            {
                EventHubReceiver receiver = client.GetConsumerGroup(consumerGroupName).CreateReceiver(
                    desc.PartitionIds[iPart], DateTime.UtcNow - TimeSpan.FromMinutes(2));
                _receivers[iPart] = receiver;

                Task <IEnumerable <EventData> > task = receiver.ReceiveAsync(1000, TimeSpan.FromSeconds(1));

                int thisPart = iPart;
                task.ContinueWith(new Action <Task <IEnumerable <EventData> > >((t) => OnTaskComplete(t, thisPart)));
                _tasks[iPart] = task;
            }
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Receive messages, Ctrl-C to exit.\n");
            eventHubClient = EventHubClient.CreateFromConnectionString(iotConnectionString, iotHubD2cEndpoint);
            //queueClient = QueueClient.CreateFromConnectionString(serviceBusConnectionString, queueName);

            var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

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

            /*queueClient.OnMessage(message =>
             * {
             *  Stream stream = message.GetBody<Stream>();
             *  StreamReader reader = new StreamReader(stream, Encoding.ASCII);
             *
             *  String result = reader.ReadToEnd();
             *  Console.WriteLine("Queued Message Received: " + result);
             * });
             *
             * queueClient.Send(new BrokeredMessage("test message"));*/

            var tasks = new List <Task>();

            foreach (string partition in d2cPartitions)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cancellationTokenSource.Token));
            }
            Task.WaitAll(tasks.ToArray());
        }
Ejemplo n.º 18
0
        /*
         *  the following function should be removed from the final deployment
         *  it is only used to send test messages to event hub
         */


        private static async Task SendToEventsToEventHubAsync(
            int NumberOfMessages,
            string PublisherName,
            EventHubDefinition HubDefinition)
        {
            string EventHubConnectionString = HubDefinition.ConnectionString;
            string EventHubName             = HubDefinition.EventHubName;

            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(EventHubConnectionString, EventHubName);
            int            current        = 1;
            Random         rand           = new Random();

            do
            {
                var Event = new
                {
                    DeviceId   = PublisherName,
                    FloorId    = string.Concat("f", rand.Next(1, 10).ToString()),
                    BuildingId = string.Concat("b", rand.Next(1, 10).ToString()),
                    TempF      = rand.Next(1, 100).ToString(),
                    Humidity   = rand.Next(1, 100).ToString(),
                    Motion     = rand.Next(1, 10).ToString(),
                    light      = rand.Next(1, 10).ToString(),
                    EventDate  = DateTime.UtcNow.ToString()
                };

                // Powershell redirects stdout to PS console.
                Console.WriteLine(
                    string.Format("sending message# {0}/{1} for Publisher {2} Hub:{3}", current, NumberOfMessages, PublisherName, HubDefinition.EventHubName));
                EventData ev = new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Event)));
                ev.SystemProperties[EventDataSystemPropertyNames.Publisher] = PublisherName;
                await eventHubClient.SendAsync(ev);

                current++;
            } while (current <= NumberOfMessages);
        }
Ejemplo n.º 19
0
        public byte[] Execute(ActionTrigger actionTrigger, ActionContext context)
        {
            try
            {
                Context       = context;
                ActionTrigger = actionTrigger;

                // Create the connection string
                var builder = new ServiceBusConnectionStringBuilder(EventHubsConnectionString)
                {
                    TransportType =
                        TransportType
                        .Amqp
                };

                // Create the EH Client
                var eventHubClient = EventHubClient.CreateFromConnectionString(builder.ToString(), EventHubsName);

                // muli partition sample
                var namespaceManager    = NamespaceManager.CreateFromConnectionString(builder.ToString());
                var eventHubDescription = namespaceManager.GetEventHub(EventHubsName);

                // Use the default consumer group
                foreach (var partitionId in eventHubDescription.PartitionIds)
                {
                    var myNewThread = new Thread(() => ReceiveDirectFromPartition(eventHubClient, partitionId));
                    myNewThread.Start();
                }
                return(null);
            }
            catch (Exception)
            {
                // ignored
                return(null);
            }
        }
Ejemplo n.º 20
0
        public async Task InvalidProxy()
        {
            // Send call should fail.
            await Assert.ThrowsAsync <WebSocketException>(async() =>
            {
                var ehClient      = EventHubClient.CreateFromConnectionString(webSocketConnString);
                ehClient.WebProxy = new WebProxy("http://1.2.3.4:9999");
                var edToFail      = new EventData(Encoding.UTF8.GetBytes("This is a sample event."));
                await ehClient.SendAsync(edToFail);
                throw new InvalidOperationException("Send call should have failed");
            });

            // Receive call should fail.
            await Assert.ThrowsAsync <WebSocketException>(async() =>
            {
                var ehClient      = EventHubClient.CreateFromConnectionString(webSocketConnString);
                ehClient.WebProxy = new WebProxy("http://1.2.3.4:9999");
                await ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart()).ReceiveAsync(1);
                throw new InvalidOperationException("Receive call should have failed");
            });

            // Management link call should fail.
            await Assert.ThrowsAsync <WebSocketException>(async() =>
            {
                var ehClient      = EventHubClient.CreateFromConnectionString(webSocketConnString);
                ehClient.WebProxy = new WebProxy("http://1.2.3.4:9999");
                await ehClient.GetRuntimeInformationAsync();
                throw new InvalidOperationException("GetRuntimeInformation call should have failed");
            });

            // Send/receive should work fine w/o proxy.
            var ehNoProxyClient = EventHubClient.CreateFromConnectionString(webSocketConnString);
            var eventData       = new EventData(Encoding.UTF8.GetBytes("This is a sample event."));

            await this.SendAndReceiveEventAsync("0", eventData, ehNoProxyClient);
        }
Ejemplo n.º 21
0
        public EventHubSink(SubscriptionMetadata metadata, ILog logger = null)
            : base(metadata, logger)
        {
            queue = new ConcurrentQueue <byte[]>();

            auditor = AuditFactory.CreateSingleton().GetAuditor(AuditType.Message);
            uri     = new Uri(metadata.NotifyAddress);
            NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query);

            keyName          = nvc["keyname"];
            partitionId      = nvc["partitionid"];
            hubName          = nvc["hub"];
            connectionString =
                $"Endpoint=sb://{uri.Authority}/;SharedAccessKeyName={keyName};SharedAccessKey={metadata.SymmetricKey}";

            if (!int.TryParse(nvc["clients"], out clientCount))
            {
                clientCount = 1;
            }

            if (!string.IsNullOrEmpty(partitionId))
            {
                senderArray = new PartitionSender[clientCount];
            }

            storageArray = new EventHubClient[clientCount];
            for (int i = 0; i < clientCount; i++)
            {
                storageArray[i] = EventHubClient.CreateFromConnectionString(connectionString);

                if (!string.IsNullOrEmpty(partitionId))
                {
                    senderArray[i] = storageArray[i].CreatePartitionSender(partitionId);
                }
            }
        }
        private static async Task MainAsync()
        {
            Console.WriteLine("Connecting to Event Hub.....");
            var eventHubClient = EventHubClient.CreateFromConnectionString(EventHubConnectionString);

            Console.WriteLine("Waiting to process incoming messages....");
            var eventRuntimeInformation = await eventHubClient.GetRuntimeInformationAsync();

            //var partitionReceivers = eventRuntimeInformation.PartitionIds.Select(partitionId => eventHubClient.CreateReceiver("$Default",partitionId, EventPosition.FromEnqueuedTime(DateTime.Now))).ToList();
            var partitionReceivers = eventRuntimeInformation.PartitionIds.Select(partitionId => eventHubClient.CreateReceiver("wired_brain_coffee_console_direct", partitionId, EventPosition.FromOffset(partitionId == "0" ? "24384" : "23800", true))).ToList();

            foreach (var partitionReceiver in partitionReceivers)
            {
                partitionReceiver.SetReceiveHandler(new WiredBrainCoffeeParitionReceiverHandler(partitionReceiver.PartitionId));
            }



            Console.WriteLine("Press any key to shutdown....");

            Console.ReadLine();

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 23
0
    // Use this for initialization
    public async void TestEventHubsSender()
    {
        try
        {
#if UNITY_2018_1
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => { return(true); };
#endif
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
            {
                EntityPath = EhEntityPath
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            await SendMessagesToEventHub(10);
        }
        catch (Exception ex)
        {
            WriteLine(ex.Message);
        }
        finally
        {
            await eventHubClient.CloseAsync();
        }
    }
Ejemplo n.º 24
0
        private static async Task <int> MainAsync(string[] args)
        {
            // Creates an EventHubsConnectionStringBuilder object from a the connection string, and sets the EntityPath.
            // Typically the connection string should have the Entity Path in it, but for the sake of this simple scenario
            // we are using the connection string from the namespace.
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName,
            };

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

            while (true)
            {
                await SendMessagesToEventHubAsync(10000);

                await eventHubClient.CloseAsync();

                Console.WriteLine("Press [enter] to exit.");
                Console.ReadLine();
            }

            return(0);
        }
Ejemplo n.º 25
0
        private async void btnUpdate(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(App.IoTHubConnectionString);

            string[] segments         = tb2.Text.Split(';');
            string   uri              = segments[0].Substring(segments[0].IndexOf("sb:/"));
            var      connectionString = new EventHubsConnectionStringBuilder(new Uri(uri), tb1.Text, "iothubowner", builder.SharedAccessKey);

            s_eventHubClient = EventHubClient.CreateFromConnectionString(connectionString.ToString());
            ApplicationData.Current.LocalSettings.Values["eventHubName"]     = tb1.Text;
            ApplicationData.Current.LocalSettings.Values["eventHubEndpoint"] = tb2.Text;

            // Create a PartitionReciever for each partition on the hub.
            var runtimeInfo = await s_eventHubClient.GetRuntimeInformationAsync();

            var d2cPartitions = runtimeInfo.PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

            foreach (string partition in d2cPartitions)
            {
                ReceiveMessagesFromDeviceAsync(partition, cts.Token);
            }
        }
Ejemplo n.º 26
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 https://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("TempAlerts has been started...\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 = "TempAlertProcessor";
            EventProcessorHost eventProcessorHost     = new EventProcessorHost(eventProcessorHostName, eventHubName, defaultConsumerGroup.GroupName, connectionString, storageAccountString);

            eventProcessorHost.RegisterEventProcessorAsync <TempAlertProcessor>().Wait();

            Trace.TraceInformation("Processing alerts...\n");

            return(result);
        }
Ejemplo n.º 27
0
        async Task OpenClientsAsync() // throws EventHubsException, IOException, InterruptedException, ExecutionException
        {
            // Create new clients
            object startAt = await this.PartitionContext.GetInitialOffsetAsync().ConfigureAwait(false);

            long epoch = this.Lease.Epoch;

            ProcessorEventSource.Log.PartitionPumpCreateClientsStart(this.Host.Id, this.PartitionContext.PartitionId, epoch, startAt);
            this.eventHubClient = EventHubClient.CreateFromConnectionString(this.Host.EventHubConnectionString);

            // Create new receiver and set options
            if (startAt is string)
            {
                this.partitionReceiver = this.eventHubClient.CreateEpochReceiver(this.PartitionContext.ConsumerGroupName, this.PartitionContext.PartitionId, (string)startAt, epoch);
            }
            else if (startAt is DateTime)
            {
                this.partitionReceiver = this.eventHubClient.CreateEpochReceiver(this.PartitionContext.ConsumerGroupName, this.PartitionContext.PartitionId, (DateTime)startAt, epoch);
            }

            this.partitionReceiver.PrefetchCount = this.Host.EventProcessorOptions.PrefetchCount;

            ProcessorEventSource.Log.PartitionPumpCreateClientsStop(this.Host.Id, this.PartitionContext.PartitionId);
        }
Ejemplo n.º 28
0
        private static async Task SubscribeToEventHubAsync()
        {
            Console.WriteLine("Connect to event hub");

            var eventHubClient = EventHubClient.CreateFromConnectionString(evConnString);

            var runtimeInformation = await eventHubClient.GetRuntimeInformationAsync();

            var partitionReceivers = runtimeInformation.PartitionIds
                                     .Select(x =>
                                             eventHubClient.CreateReceiver("$Default", x, EventPosition.FromEnqueuedTime(DateTime.Now))).ToList();

            Console.WriteLine("Wait for incoming events");

            foreach (var partitionReceiver in partitionReceivers)
            {
                partitionReceiver.SetReceiveHandler(new CoffeeEventReceiver(partitionReceiver.PartitionId));
            }

            Console.WriteLine("Please press any key to close the program");
            Console.ReadLine();

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            string           connection        = "HostName=pltkdpepliot2016S1.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=Q2Lib3zRmGtHYWJMogofGWbhwrBCpGmemnTvXOWj+qE=";
            string           consumerGroupName = "$Default";
            string           deviceName        = "";
            EventHubClient   eventHubClient    = null;
            EventHubReceiver eventHubReceiver  = null;

            eventHubClient = EventHubClient.CreateFromConnectionString(connection, "messages/events");
            var ri = eventHubClient.GetRuntimeInformation();

            if (deviceName != "")
            {
                string partition = EventHubPartitionKeyResolver.ResolveToPartition(deviceName, ri.PartitionCount);
                eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).
                                   CreateReceiver(partition, DateTime.Now);
                Task.Run(() => EventLoopAsync(eventHubReceiver));
            }
            else
            {
                EventHubReceiver[] eventHubReceivers = new EventHubReceiver[ri.PartitionCount];
                Console.WriteLine($"PartitionCount: {ri.PartitionCount}");

                int i = 0;
                foreach (var partition in ri.PartitionIds)
                {
                    Console.WriteLine($"PartitionID: {partition}");
                    eventHubReceivers[i] = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);
                    //Task.Run(() => eventLoop(eventHubReceivers[i])); <- very common bug!
                    var r = eventHubReceivers[i];
                    Task.Run(() => EventLoopAsync(r));
                    i++;
                }
            }
            Console.ReadLine();
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Simulated cell tower\n");

                hubClient = EventHubClient.CreateFromConnectionString(secrets.eventHubConnectionString, secrets.eventHubName);

                // Randomly create instances of the store actions, such as add view remove and checkout a product,
                // convert it into a JSON string and sends to the IoT Hub.
                GenerateRandomEvents();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured: " + e.ToString());
            }
            finally
            {
                Console.WriteLine("DataGen has stopped");
            }

            Console.ReadLine();
        }