static async Task Main(string[] args)
        {
            // read environment vars from .env file
            DotNetEnv.Env.Load();

            string eventHubConnectionString = System.Environment.GetEnvironmentVariable("EventHubConnectionString");
            string eventHubName             = System.Environment.GetEnvironmentVariable("EventHubName");
            var    connectionStringBuilder  = new EventHubsConnectionStringBuilder(eventHubConnectionString)
            {
                EntityPath = eventHubName
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            Console.WriteLine($"Sending {args[0]} messages to event hub stream....");

            var eventList = new List <EventData>();
            var uuid      = Guid.NewGuid().ToString();

            for (int x = 0; x < int.Parse(args[0]); x++)
            {
                var message = new {
                    ActivityID     = uuid,
                    MessageNumber  = x,
                    PublishTime    = ToRfc3339String(DateTime.UtcNow),
                    ThrowException = x % 10 == 0
                };
                eventList.Add(new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))));
                if (eventList.Count >= 100)
                {
                    await SendEvents(eventList);

                    eventList.Clear();
                }
            }
            if (eventList.Count > 0)
            {
                await SendEvents(eventList);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Add a connection for sending messages to an event hub. Connect via the connection string.
        /// </summary>
        /// <param name="eventHubName">name of the event hub. </param>
        /// <param name="sendConnectionString">connection string for sending messages. If this includes an EntityPath, it takes precedence over the eventHubName parameter.</param>
        public void AddSender(string eventHubName, string sendConnectionString)
        {
            if (eventHubName == null)
            {
                throw new ArgumentNullException("eventHubName");
            }
            if (sendConnectionString == null)
            {
                throw new ArgumentNullException("sendConnectionString");
            }

            EventHubsConnectionStringBuilder sb = new EventHubsConnectionStringBuilder(sendConnectionString);

            if (string.IsNullOrWhiteSpace(sb.EntityPath))
            {
                sb.EntityPath = eventHubName;
            }

            var client = EventHubClient.CreateFromConnectionString(sb.ToString());

            AddEventHubClient(eventHubName, client);
        }
Esempio n. 3
0
        static async Task MainAsync(string[] args)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
                                          // Endpoint=sb://namespace_DNS_Name;EntityPath=
            {
                EntityPath = "myeventhub",
                Endpoint   = new Uri("sb://testingevent.servicebus.windows.net/"),
                SasKeyName = "iothubroutes_mytesting",
                SasKey     = "oEQ4T5iB/tsFwbXrYc4nAxUJujXaHvqEcGBLSTV4WRo="
                             //Endpoint=sb://testingevent.servicebus.windows.net/;SharedAccessKeyName=iothubroutes_mytesting;SharedAccessKey=oEQ4T5iB/tsFwbXrYc4nAxUJujXaHvqEcGBLSTV4WRo=;EntityPath=myeventhub
                             // Endpoint = new Uri("Endpoint=sb://mytesting.azure-devices.net;EntityPath=mytesting;SharedAccessKeyName=iothubowner;SharedAccessKey=4b4wUQny9H83mZ0NIh1VChWqIiEmIWt/yKFcsr3+oEM=")
            };

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

            await SendMessagesToEventHub(10);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
        public async void StartListening(GapDetection detectionEvent)
        {
            if (gapDetectionEvent != null)
            {
                return;
            }

            try
            {
                var connectionString =
                    new EventHubsConnectionStringBuilder(
                        new Uri(GapConfig.EventHubsCompatibleEndpoint),
                        GapConfig.EventHubsCompatiblePath,
                        GapConfig.IotHubSasKeyName,
                        GapConfig.IotHubSasKey);

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

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

                var d2cPartitions = runtimeInfo.PartitionIds;

                // TODO: listening on partition 0 only.
                receivers =
                    d2cPartitions
                    .Select(d2c => eventHubClient.CreateReceiver("$Default", d2c, EventPosition.FromEnqueuedTime(DateTime.Now)))
                    .ToList();

                gapTimer = ThreadPoolTimer.CreatePeriodicTimer(BackgroundListen, timerPeriod);

                GapDetectionEvent += detectionEvent;
                gapDetectionEvent  = detectionEvent;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Esempio n. 5
0
        public async Task <bool> AddAsync(
            MessageAddOptions messageAddOptions)
        {
            var connectionStringBuilder =
                new EventHubsConnectionStringBuilder(_options.ConnectionString)
            {
                EntityPath = messageAddOptions.Type
            };


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

            await eventHubClient.SendAsync(
                new EventData(
                    Encoding.UTF8.GetBytes(
                        JsonConvert.SerializeObject(messageAddOptions, Formatting.Indented))));

            await eventHubClient.CloseAsync();

            return(true);
        }
        // === EventHub methods below

        private static void SendEventHubMessages(int messageCount)
        {
            Log("SendEventHubMessages: " + messageCount);
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(eventHubConnStr)
            {
                EntityPath = eventHubName
            };

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

            Random random = new Random();

            for (int seq = 1; seq <= messageCount; seq++)
            {
                var     index   = random.Next(0, airportData.airports.Count);
                JObject airport = (JObject)airportData.airports[index];
                airportData.AddRandomEvent(airport, seq);
                Console.WriteLine(airport);
                Task task = SendMessageAsync(airport);
                task.Wait();
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            // 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());
        }
Esempio n. 8
0
        static async Task Main(string[] args)
        {
            // Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
            // Typically, the connection string should have the entity path in it, but this simple scenario
            // uses the connection string from the namespace.
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

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

            // Specify a specific partition Id to send the messages to.
            partitionSender = eventHubClient.CreatePartitionSender("2");

            await SendEventsToEventHub(100);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
        private static async Task MainAsync(string[] args)
        {
            // Creates an EventHubsConnectionStringBuilder object from 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
            };

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

            var connectionStringBuilder2 = new EventHubsConnectionStringBuilder(EventHubConnectionString2)
            {
                EntityPath = EventHubName2
            };

            eventHubClient2 = EventHubClient.CreateFromConnectionString(connectionStringBuilder2.ToString());

            //send to the event hubs in parallel

            Thread t1 = new Thread(async() =>
            {
                await SendMessagesToEventHub1(1000);
            });

            Thread t2 = new Thread(async() =>
            {
                await SendMessagesToEventHub2(1000);
            });

            t1.Start();
            t2.Start();

            //await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Esempio n. 10
0
        public IotHub(string iotHubConnectionString, string eventHubEndpoint, Option <Uri> proxyUri)
        {
            this.eventHubEndpoint       = eventHubEndpoint;
            this.iotHubConnectionString = iotHubConnectionString;
            Option <IWebProxy> proxy = proxyUri.Map(p => new WebProxy(p) as IWebProxy);

            this.registryManager = new Lazy <RegistryManager>(
                () =>
            {
                var settings = new HttpTransportSettings();
                proxy.ForEach(p => settings.Proxy = p);
                return(RegistryManager.CreateFromConnectionString(
                           this.iotHubConnectionString,
                           settings));
            });

            this.serviceClient = new Lazy <ServiceClient>(
                () =>
            {
                var settings = new ServiceClientTransportSettings();
                proxy.ForEach(p => settings.HttpProxy = p);
                return(ServiceClient.CreateFromConnectionString(
                           this.iotHubConnectionString,
                           DeviceTransportType.Amqp_WebSocket_Only,
                           settings));
            });

            this.eventHubClient = new Lazy <EventHubClient>(
                () =>
            {
                var builder = new EventHubsConnectionStringBuilder(this.eventHubEndpoint)
                {
                    TransportType = EventHubTransportType.AmqpWebSockets
                };
                var client = EventHubClient.CreateFromConnectionString(builder.ToString());
                proxy.ForEach(p => client.WebProxy = p);
                return(client);
            });
        }
Esempio n. 11
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("IoT Hub Quickstarts - Read device to cloud messages. Ctrl-C to exit.\n");

            // Create an EventHubClient instance to connect to the
            // IoT Hub Event Hubs-compatible endpoint.
            var connectionString = new EventHubsConnectionStringBuilder(new Uri(eventHubsCompatibleEndpoint), eventHubsCompatiblePath, iotHubSasKeyName, iotHubSasKey);

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

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(azureStorageConnectionString);
            var blobClient = storageAccount.CreateCloudBlobClient();

            cloudBlobContainer = blobClient.GetContainerReference("azure-webjobs-eventhub/" + eventHubHostname + "/" + eventHubsCompatiblePath + "/" + targetConsumerGroup);

            // Create a PartitionReciever for each partition on the hub.
            var runtimeInfo = await 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());
        }
Esempio n. 12
0
        public void ParseAndBuild()
        {
            var csb = new EventHubsConnectionStringBuilder(TestUtility.EventHubsConnectionString);

            // Try update settings and rebuild the connection string.
            csb.Endpoint         = new Uri("sb://newendpoint");
            csb.EntityPath       = "newentitypath";
            csb.OperationTimeout = TimeSpan.FromSeconds(100);
            csb.SasKeyName       = "newsaskeyname";
            csb.SasKey           = "newsaskey";
            var newConnectionString = csb.ToString();

            // Now try creating a new ConnectionStringBuilder from modified connection string.
            var newCsb = new EventHubsConnectionStringBuilder(newConnectionString);

            // Validate modified values on the new connection string builder.
            Assert.Equal(new Uri("sb://newendpoint"), newCsb.Endpoint);
            Assert.Equal("newentitypath", newCsb.EntityPath);
            Assert.Equal(TimeSpan.FromSeconds(100), newCsb.OperationTimeout);
            Assert.Equal("newsaskeyname", newCsb.SasKeyName);
            Assert.Equal("newsaskey", newCsb.SasKey);
        }
Esempio n. 13
0
        /// <summary>
        /// Attempts to connect to Azure Event Hub database.
        /// </summary>
        protected override void AttemptConnection()
        {
            try
            {
                // Establish data event hub connection
                EventHubsConnectionStringBuilder builder = new EventHubsConnectionStringBuilder(EventHubDataClientConnectionString)
                {
                    EntityPath = EventHubDataClientName
                };

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

                if (string.IsNullOrWhiteSpace(EventHubMetadataClientConnectionString))
                {
                    m_eventHubMetadataClient = m_eventHubDataClient;
                }
                else
                {
                    // Establish meta-data event hub connection
                    builder = new EventHubsConnectionStringBuilder(EventHubMetadataClientConnectionString)
                    {
                        EntityPath = string.IsNullOrWhiteSpace(EventHubMetadataClientName) ? EventHubDataClientName : EventHubMetadataClientName
                    };

                    m_eventHubMetadataClient = EventHubClient.CreateFromConnectionString(builder.ToString());
                }

                m_connectionResponse = "Connected";
            }
            catch (Exception ex)
            {
                // Hang onto response for status logging
                m_connectionResponse = ex.Message;

                // Re-throw any captured exceptions, this will restart connection cycle as needed
                throw;
            }
        }
        private static IEventHubReceiver CreateReceiver(EventHubPartitionSettings partitionSettings, string offset, ILogger logger, ITelemetryProducer telemetryProducer)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(partitionSettings.Hub.ConnectionString)
            {
                EntityPath = partitionSettings.Hub.Path
            };
            EventHubClient client = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            EventPosition eventPosition;

            // If we have a starting offset, read from offset
            if (offset != EventHubConstants.StartOfStream)
            {
                logger.Info("Starting to read from EventHub partition {0}-{1} at offset {2}", partitionSettings.Hub.Path, partitionSettings.Partition, offset);
                eventPosition = EventPosition.FromOffset(offset, true);
            }
            // else, if configured to start from now, start reading from most recent data
            else if (partitionSettings.ReceiverOptions.StartFromNow)
            {
                eventPosition = EventPosition.FromEnd();
                logger.Info("Starting to read latest messages from EventHub partition {0}-{1}.", partitionSettings.Hub.Path, partitionSettings.Partition);
            }
            else
            // else, start reading from begining of the partition
            {
                eventPosition = EventPosition.FromStart();
                logger.Info("Starting to read messages from begining of EventHub partition {0}-{1}.", partitionSettings.Hub.Path, partitionSettings.Partition);
            }

            PartitionReceiver receiver = client.CreateReceiver(partitionSettings.Hub.ConsumerGroup, partitionSettings.Partition, eventPosition);

            if (partitionSettings.ReceiverOptions.PrefetchCount.HasValue)
            {
                receiver.PrefetchCount = partitionSettings.ReceiverOptions.PrefetchCount.Value;
            }

            return(new EventHubReceiverProxy(receiver));
        }
Esempio n. 15
0
        private static async Task 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(EhConnectionString)
            {
                EntityPath = EhEntityPath
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            var rec = eventHubClient.CreateReceiver("$Default", "0", new DateTime(2017 / 02 / 26));


            await SendMessagesToEventHub(100);

            int idxread = 0;

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

                if (t == null || t.Count() == 0)
                {
                    break;
                }
                foreach (var a in t)
                {
                    idxread++;
                    Console.WriteLine("idxread:" + idxread + " *->" + Encoding.UTF8.GetString(a.Body.Array));
                }
            }
            Console.WriteLine("ya sali de la cola.");
            await eventHubClient.CloseAsync();

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Esempio n. 16
0
        private static async Task StartEventGenerationAsync(CancellationToken cancellationToken)
        {
            var random = new Random((int)DateTimeOffset.UtcNow.Ticks);

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

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

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    // Simulate sending data from 100 weather sensors
                    var devicesData = new List <EventData>();

                    for (int i = 0; i < 100; i++)
                    {
                        int       scaleFactor        = random.Next(0, 25);
                        var       windTurbineMeasure = GenerateTurbineMeasure("Turbine_" + i, scaleFactor);
                        EventData evData             = SerializeWindTurbineToEventData(windTurbineMeasure);
                        devicesData.Add(evData);
                    }

                    Console.Write(".");
                    await client.SendAsync(devicesData);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error generating turbine data. Exception: {0}", ex);
                    Console.Write("E");
                }

                await Task.Delay(1000, cancellationToken);
            }
        }
Esempio n. 17
0
        private static async Task MainEventHubAsync(string[] args)
        {
            WriteLine("Enter your Event Hub connection string:");
            var EventHubConnectionString = ReadLine();

            while (EventHubConnectionString.Length == 0)
            {
                WriteLine("Try again, this value must have a length > 0");
                WriteLine("Enter your Event Hub connection string:");
                EventHubConnectionString = ReadLine();
            }
            WriteLine("Enter your Event Hub name:");
            var EventHubName = ReadLine();

            while (EventHubName.Length == 0)
            {
                WriteLine("Try again, this value must have a length > 0");
                WriteLine("Enter your Event Hub name:");
                EventHubName = ReadLine();
            }
            WriteLine("Enter number of events to add: ");
            int EventHubEventsToSend = 0;

            while (!int.TryParse(ReadLine(), out EventHubEventsToSend))
            {
                WriteLine("Try again, this value must be numeric.");
            }

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            await SendMessagesToEventHub(EventHubEventsToSend);

            await eventHubClient.CloseAsync();
        }
Esempio n. 18
0
        /// <summary>
        /// The most detailed method with full fragmentation
        /// </summary>
        /// <param name="endpointAddress">Endpoint address</param>
        /// <param name="entityPath">Entity path</param>
        /// <param name="sharedAccessKeyName">Shared access key name</param>
        /// <param name="sharedAccessKey">Shared access key value</param>
        /// <returns></returns>
        public static AzureEventHubPublisher Create(Uri endpointAddress, string entityPath, string sharedAccessKeyName, string sharedAccessKey)
        {
            if (endpointAddress == null)
            {
                throw new ArgumentNullException(nameof(endpointAddress));
            }
            if (entityPath == null)
            {
                throw new ArgumentNullException(nameof(entityPath));
            }
            if (sharedAccessKeyName == null)
            {
                throw new ArgumentNullException(nameof(sharedAccessKeyName));
            }
            if (sharedAccessKey == null)
            {
                throw new ArgumentNullException(nameof(sharedAccessKey));
            }

            var csb = new EventHubsConnectionStringBuilder(endpointAddress, entityPath, sharedAccessKeyName, sharedAccessKey);

            return(new AzureEventHubPublisher(csb.ToString()));
        }
        static void ReceiveMessages(string partitionId)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder("[Event Hub Connection String]")
            {
                EntityPath = "number-egress"
            };
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            var receiver       = eventHubClient.CreateEpochReceiver("$Default", partitionId, DateTime.Now, 1);

            while (true)
            {
                var data = receiver.ReceiveAsync(5).Result;
                if (data != null)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    foreach (var item in data)
                    {
                        Console.WriteLine("{0} - {2} > Data: {1}", DateTime.Now, Encoding.UTF8.GetString(item.Body.Array), partitionId);
                    }
                    Console.ResetColor();
                }
            }
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHub
            };

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

            SetTimer();

            if (eventHubClient == null)
            {
                Console.WriteLine("Failed to create EventHub Client!");
                //SensorTimer.Stop();
            }

            Console.WriteLine("\nPress the Enter key to exit the application...\n");
            Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
            Console.ReadLine();
            //SensorTimer.Stop();
            //SensorTimer.Dispose();
        }
Esempio n. 21
0
        static void Main()
        {
            var connectionStringBuilder =
                new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubEntityPath
            };

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

            var boiler1 = new Thermometer {
                DeviceName = "Boiler 01"
            };

            while (true)
            {
                var eventDataJson = boiler1.GetTemperatureMessage();
                Console.WriteLine("Sending message: " + eventDataJson);
                var eventData = new EventData(Encoding.UTF8.GetBytes(eventDataJson));
                eventHubClient.SendAsync(eventData).Wait();
                System.Threading.Thread.Sleep(500);
            }
        }
Esempio n. 22
0
        private static async Task AsyncMain()
        {
            var connectionString = new EventHubsConnectionStringBuilder(new Uri(config.EventHubsCompatibleEndpoint), config.EventHubsCompatiblePath, config.IotHubSasKeyName, config.IotHubSasKey);

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


            // Let's create a PartitionReciever for each partition on the hub.

            var runtimeInfo = await s_eventHubClient.GetRuntimeInformationAsync();

            var d2cPartitions = runtimeInfo.PartitionIds;

            var tasks = new List <Task>(); //let's asign each partitionreceiver to one task

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

            // Wait for all the PartitionReceivers to finsih.
            Task.WaitAll(tasks.ToArray());
        }
Esempio n. 23
0
        public async Task NonexsistentEntity()
        {
            // Rebuild connection string with a nonexistent entity.
            var csb = new EventHubsConnectionStringBuilder(TestUtility.EventHubsConnectionString);

            csb.EntityPath = Guid.NewGuid().ToString();

            var eventProcessorHost = new EventProcessorHost(
                string.Empty,
                PartitionReceiver.DefaultConsumerGroupName,
                csb.ToString(),
                TestUtility.StorageConnectionString,
                this.LeaseContainerName);

            TestUtility.Log("Calling RegisterEventProcessorAsync for a nonexistent entity.");
            var ex = await Assert.ThrowsAsync <EventProcessorConfigurationException>(async() =>
            {
                await eventProcessorHost.RegisterEventProcessorAsync <TestEventProcessor>();
            });

            Assert.NotNull(ex.InnerException);
            Assert.IsType <MessagingEntityNotFoundException>(ex.InnerException);
        }
Esempio n. 24
0
        static async Task Main(string[] args)
        {
            // Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
            // Typically, the connection string should have the entity path in it, but this simple scenario
            // uses the connection string from the namespace.
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

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

            var tokenSource = new CancellationTokenSource();
            var ct          = tokenSource.Token;

            Task.Run(() => ReceiveMessagesFromPartition("2", ct), ct);

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
            tokenSource.Cancel();

            await eventHubClient.CloseAsync();
        }
Esempio n. 25
0
        //public  async Task MainAsync(ga_payload gap)
        public async Task MainAsync(Games games)
        {
            // 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());

            //await SendMessagesToEventHub(100);
            //await SendMessagesToEventHub(gap);  //UPDATED
            await SendMessagesToEventHub(games);

            await eventHubClient.CloseAsync();

            //Console.WriteLine("Press any key to exit.");
            //Console.ReadLine();
        }
Esempio n. 26
0
        static void EventHubIngestion()
        {
            // updated with .net core
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString)
            {
                EntityPath = eventHubName
            };
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            long counter = 0;

            while (true)
            {
                // https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.for?view=netcore-3.1
                Parallel.For(1, numthread, (i, state) =>
                {
                    try
                    {
                        string recordString = $"MODEL_{GetRandomNumber(0, 100)}";

                        EventData eventData = new EventData(Encoding.UTF8.GetBytes(recordString));
                        eventHubClient.SendAsync(eventData);
                    }
                    catch (Exception exception)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                        Console.ResetColor();
                    }

                    Thread.Sleep(1000);
                });
                counter++;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Iteration {counter} done");
            }
        }
Esempio n. 27
0
        public Task <bool> Submit(EventHubInfo eventHubInfo)
        {
            var status = default(bool);

            try
            {
                if (eventHubInfo == default(EventHubInfo))
                {
                    throw new ArgumentNullException(nameof(eventHubInfo));
                }

                var sensorReadings            = faker.Generate(eventHubInfo.NoOfMessages);
                var ehConnectionStringBuilder = new EventHubsConnectionStringBuilder(eventHubInfo.EventHubConnectionString)
                {
                    EntityPath = eventHubInfo.EventHubPath
                };

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

                foreach (var reading in sensorReadings)
                {
                    var jsonString     = JsonConvert.SerializeObject(reading);
                    var eventDataBytes = Encoding.ASCII.GetBytes(jsonString);
                    var eventData      = new EventData(eventDataBytes);

                    eventHubClient.SendAsync(eventData);
                }

                status = true;
            }
            catch (Exception exceptionObject)
            {
                status = false;
            }

            return(Task.FromResult(status));
        }
        public static async Task <string> Run([ActivityTrigger] EventHubJobProperties ehJobProperties, ILogger log)
        {
            try
            {
                EventHubsConnectionStringBuilder connectionStringBuilder = new EventHubsConnectionStringBuilder(ehJobProperties.ConnectionString)
                {
                    EntityPath = ehJobProperties.EventHub
                };

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

                int secondsPerJobBatch = Convert.ToInt16(Environment.GetEnvironmentVariable("secondsPerBatch"));
                int messagesInJobBatch = ehJobProperties.Frequency * secondsPerJobBatch;
                int messagesPerSend    = 250;

                IEnumerable <string> messages = Messages.CreateMessages(messagesInJobBatch, ehJobProperties.MessageScheme);

                while (messages.Count() > 0)
                {
                    var messagesToSend = messages.Take(messagesPerSend);
                    var ehMessages     = messagesToSend.Select(m => new EventData(Encoding.UTF8.GetBytes(m)));
                    await eventHubClient.SendAsync(ehMessages);

                    messages = messages.Skip(messagesPerSend);
                }
                await eventHubClient.CloseAsync();

                log.LogInformation($"sent batch of {messagesInJobBatch} messages");
                return($"finished sending {messagesInJobBatch} to {ehJobProperties.EventHub}!");
            }
            catch (Exception exception)
            {
                log.LogInformation($"Exception: {exception.Message}");
                return($"Exception: {exception.Message}");
            }
        }
        static async Task Main(string[] args)
        {
            Console.WriteLine("Read temperature messages. Ctrl-C to exit.\n");

            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("conf.json", true, true)
                                    .Build();

            serviceClient = ServiceClient.CreateFromConnectionString(config["IotHubConnectionString"]);

            var connectionString = new EventHubsConnectionStringBuilder(new Uri(config["EventHubsCompatibleEndpoint"]), config["EventHubsCompatiblePath"], config["IotHubSasKeyName"], config["IotHubSasKey"]);

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

            var runtimeInfo = await s_eventHubClient.GetRuntimeInformationAsync();

            var d2cPartitions = runtimeInfo.PartitionIds;

            CancellationTokenSource cts = new CancellationTokenSource();

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

            Console.ReadLine();
        }
Esempio n. 30
0
        static async Task <string> GetHelloWorldAsync()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json", true, true)
                          .AddEnvironmentVariables();

            builder.AddUserSecrets <Program>();

            var config = builder.Build();


            var mySettings = config.GetSection("mySettings").Get <MySettings>();

            Console.WriteLine($"EventHubName:{mySettings.EventHubName}");
            Console.WriteLine($"EventHubConnectionString:{mySettings.EventHubConnectionString}");
            EventHubName             = mySettings.EventHubName;
            EventHubConnectionString = mySettings.EventHubConnectionString;

            // 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());

            await SendMessagesToEventHub(100);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();

            return($" Hello { config["name"] } and {mySettings.Name} !");
        }