Ejemplo n.º 1
0
 private void StopEventhub()
 {
     if (eventHubClient != null)
     {
         eventHubClient.CloseAsync();
     }
 }
        public async Task ClientCannotRetrieveMetadataWhenClosed(bool sync)
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

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

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

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

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

                    Assert.That(async() => await client.GetPartitionIdsAsync(), Throws.TypeOf <ObjectDisposedException>());
                    Assert.That(async() => await client.GetPropertiesAsync(), Throws.TypeOf <ObjectDisposedException>());
                    Assert.That(async() => await client.GetPartitionPropertiesAsync(partition), Throws.TypeOf <ObjectDisposedException>());
                }
            }
        }
Ejemplo n.º 3
0
        private static async Task MainAsync(string[] args)
        {
            try
            {
                var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
                {
                    EntityPath = EventHubName
                };

                while (true)
                {
                    Console.WriteLine("Quanti eventi vuoi generare?");
                    eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
                    int eventsCount = int.Parse(Console.ReadLine());

                    await SendMessagesToEventHub(eventsCount);

                    await eventHubClient.CloseAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Ejemplo n.º 4
0
        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(EhConnectionString)
            {
                EntityPath = EhEntityPath
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            //Using external package Newtonsoft.json to read in the downloaded blob file and then deserialize the JSON as a list of type x
            //Read File into List and Deserialise JSON to type 'Airline'
            var airline = JsonConvert.DeserializeObject <List <Airline> >(File.ReadAllText(@"./blobDownload.json"));

            //Calling Method to send messages to Event Hub
            await SendMessagesToEventHub(airline);

            //Closing connection
            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit");
            //Keep Console open till user input
            Console.ReadLine();
        }
Ejemplo n.º 5
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                          .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                          .Value;

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            string jsonString = JsonConvert.SerializeObject(data);

            // Set name to query string or body data
            name = name ?? data?.name;

            InitialiseClient();
            log.Info("Event Hub client initialized.");

            await SendMessagesToEventHub(jsonString, 500, log);

            await eventHubClient.CloseAsync();

            log.Info("Event Hub client closed.");



            return(name == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Hello " + name));
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(
                EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

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

            for (var i = 0; i < numMessagesToSend; i++)
            {
                try
                {
                    var message = $"Message {i}";
                    Console.WriteLine($"Sending message: {message}");
                    eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
                }

                Task.Delay(10);
            }

            Console.WriteLine($"{numMessagesToSend} messages sent.");

            eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
        public async Task Post()
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(Environment.GetEnvironmentVariable("EventHubConnectionString"))
            {
                EntityPath = Environment.GetEnvironmentVariable("EventHubName")
            };

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

            try
            {
                string value;
                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    value = await reader.ReadToEndAsync();
                }
                await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(value)));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{DateTime.Now} > Exception: {ex.Message}");
            }

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 8
0
        private static async Task MainAsync(string[] args)
        {
            int maxRecordCount = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Seconds delay each call:");
            int delay = Convert.ToInt32(Console.ReadLine());

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

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

            await SendMessagesToEventHub(messageCount, delay);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 9
0
        private static async Task MainAsync(string[] args)
        {
            // Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath. updated
            // 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(EhConnectionString)
            {
                EntityPath = EhEntityPath
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            while (true)
            {
                Console.WriteLine("Enter Message to send");
                string message = Console.ReadLine();
                if (message == "stop")
                {
                    break;
                }
                await SendMessagesToEventHub(message);
            }
            await eventHubClient.CloseAsync();


            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 10
0
        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(EhConnectionString)
            {
                EntityPath = EhEntityPath
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            //watch();
            //FileSystemWatcher watcher = new FileSystemWatcher();
            //watcher.Path = @"C:\Amitha NEU\Engg Big Data\Final\SAJ\output";
            //watcher.NotifyFilter = NotifyFilters.LastWrite;
            //watcher.Filter = "*.*";
            //watcher.Changed += new FileSystemEventHandler(OnChanged);
            //watcher.EnableRaisingEvents = true;
            String fullPath = @"C:\Amitha NEU\Engg Big Data\Final\SAJ\output\CAVtagsJson_Final.json";

            LoadJson(fullPath);
            await SendJsonObjectsToEventHub();

            await eventHubClient.CloseAsync();

            //Console.WriteLine("Press Enter");
            Console.ReadLine();
        }
Ejemplo n.º 11
0
        public async Task CloseAsync()
        {
            try
            {
                // Close EventHubReceiver
                foreach (EventHubReceiver recv in _eventHubReceiverList)
                {
                    await recv.CloseAsync();
                }

                _eventHubReceiverList.Clear();
                _infoLogger.InfoFormat("EventHubReceiver has been closed.");
                // Close EventHubClient
                await _eventHubClient.CloseAsync();

                _infoLogger.InfoFormat("EventHubClient has been closed.");
                // Close UDP socket
                // _UDPConnector.Close();
                _infoLogger.InfoFormat("UDPConnector has been closed.");
            }
            catch (Exception ex)
            {
                _errorLogger.ErrorFormat("IoTHubReceiver closing got an error: {0}",
                                         ex.ToString().Replace("\r\n", " "));
            }
        }
Ejemplo n.º 12
0
        private static async Task MainAsync(string[] args)
        {
            if (!long.TryParse(args[0], out var startSequenceNo))
            {
                startSequenceNo = 1;
            }
            if (!long.TryParse(args[1], out var endSequenceNo))
            {
                endSequenceNo = 1000;
            }
            if (!int.TryParse(args[2], out var interval))
            {
                interval = 10;
            }
            if (!int.TryParse(args[3], out var batchSize))
            {
                batchSize = 10;
            }

            Console.WriteLine($"Sequence [{startSequenceNo}:{endSequenceNo}] in {batchSize*interval}/s");

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString);

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

            await SendMessagesToEventHub(startSequenceNo, endSequenceNo, interval, batchSize);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 13
0
        private static async Task MainAsync(string[] args)
        {
            eventHubClient = EventHubClient.CreateFromConnectionString(EhConnectionString);
            await SendMessagesToEventHub(numMsgs);

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 14
0
    public static async Task SendAsync(string message)
    {
        var connection = new EventHubsConnectionStringBuilder(Constants.EhConnectionString)
        {
            EntityPath = Constants.EhEntityPath
        };
        eventHubClient = EventHubClient.CreateFromConnectionString(connection.ToString());
        //for (int i = 0; i < 10; i++)
        //{
        //    var msgBytes = Encoding.UTF8.GetBytes(message + i);
        //    await eventHubClient.SendAsync(new EventData(msgBytes));
        //}
        var input = "";
        do
        {
            Console.WriteLine("Enter message or q for quit \r\n");
            input = Console.ReadLine();
            var msgBytes = Encoding.UTF8.GetBytes(input);
            await eventHubClient.SendAsync(new EventData(msgBytes));
        } while (input != "q");
        

        await Task.Delay(5);
        await eventHubClient.CloseAsync();

    }
Ejemplo n.º 15
0
        public async Task SendEventJsonAsync(string name, string eventJson, ConcurrentDictionary <string, object> properties = null)
        {
            if (string.IsNullOrWhiteSpace(eventJson) || !JsonHelper.IsValidJson(eventJson))
            {
                throw new ArgumentNullException("eventJson", "Could not be null or empty and the event must have a valid json format.");
            }

            ProducerConfigurationsOptions producerConfiguration = GetProducerConfiguration(name);

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(producerConfiguration.ConnectionString)
            {
                EntityPath = producerConfiguration.EventHubName
            };

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

            var eventData = new EventData(Encoding.UTF8.GetBytes(eventJson));

            if (properties != null && properties.Any())
            {
                foreach (var propertie in properties)
                {
                    eventData.Properties.Add(propertie.Key, propertie.Value);
                }
            }

            await eventHubClient.SendAsync(eventData);

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 16
0
    // Use this for initialization
    public async void TestEventHubsSender()
    {
        try
        {
#if !UNITY_WSA
            //Unity will complain that the following statement is deprecated
            //however, it's working :)
            ServicePointManager.CertificatePolicy = new CustomCertificatePolicy();

            //this 'workaround' seems to work for the .NET Storage SDK, but not here. Leaving this for clarity
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#endif

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
            {
                EntityPath = EhEntityPath
            };


            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            await SendMessagesToEventHub(4);
        }
        catch (Exception ex)
        {
            WriteLine(ex.Message);
        }
        finally
        {
            await eventHubClient.CloseAsync();
        }
    }
Ejemplo n.º 17
0
        public Task CloseAsync(IWorkContext context)
        {
            context = context.With(_tag);

            context.Telemetry.Verbose(context, $"Closing event hub client for {_conntectionString.EntityPath}");
            return(_client.CloseAsync());
        }
        private static async Task SendEvents()
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(eventHubConnString)
            {
                EntityPath = eventHubEntityPath
            };

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

            Random ran = new Random();

            for (int i = 0; i < eventsToSend; i++)
            {
                string randomData = PrepareRandomData(ran);
                try
                {
                    await client.SendAsync(new EventData(Encoding.UTF8.GetBytes(randomData)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{DateTime.Now} - Exception: {ex.ToString()}");
                }
                await Task.Delay(milisecondsBetweenEvents);
            }
            await client.CloseAsync();
        }
Ejemplo n.º 19
0
        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(connectionString)
            {
                EntityPath = eventHubName
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            Task[] allTask = new Task[10000];
            for (int i = 0; i < allTask.Length; i++) //Run 10 methods simultaneously
            {
                var myTask = Task.Run(async() =>
                {
                    await SendMessagesToEventHub(100, 1);
                }
                                      );
                allTask[i] = myTask;
            }

            await Task.WhenAll(allTask);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 20
0
        //The primary entry point for the application
        private static async Task MainAsync(string[] args)
        {
            if (args.Length != 0)
            {
                numMessages = Convert.ToInt32(args[0]);
            }
            // 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
            };

            //Open up an event hub connection
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            //Async call to send messages (passing the number of messages as a parameter)
            await SendMessagesToEventHub(numMessages);

            //Once we've finished sending messages, close the client down
            await eventHubClient.CloseAsync();

            Console.WriteLine("Press the enter key to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 21
0
        public async Task <List <EventData> > GetMessagesForDevice(string deviceId, DateTime startTime, int maxPerPartition = 100, int waitTimeSecs = 5)
        {
            var messages = new List <EventData>();

            EventHubClient    eventHubClient    = EventHubClient.CreateFromConnectionString(this.eventHubConnectionString);
            PartitionReceiver partitionReceiver = eventHubClient.CreateReceiver(
                EventHubConsumerGroup,
                EventHubPartitionKeyResolver.ResolveToPartition(deviceId, (await eventHubClient.GetRuntimeInformationAsync()).PartitionCount),
                EventPosition.FromEnqueuedTime(startTime));

            // Retry a few times due to weird behavior with ReceiveAsync() not returning all messages available
            for (int i = 0; i < 3; i++)
            {
                IEnumerable <EventData> events = await partitionReceiver.ReceiveAsync(maxPerPartition, TimeSpan.FromSeconds(waitTimeSecs));

                if (events != null)
                {
                    messages.AddRange(events);
                }

                if (i < 3)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }

            await partitionReceiver.CloseAsync();

            await eventHubClient.CloseAsync();

            return(messages);
        }
Ejemplo n.º 22
0
        private static async Task MainAsync(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", false, false)
                                    .Build();

            string EventHubConnectionString = config["EventHubConnectionString"];
            string EventHubName             = config["EventHubName"];

            // 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();
        }
Ejemplo n.º 23
0
        public async Task <IEnumerable <string> > GetPartitionIdsAsync()
        {
            if (this.partitionIds == null)
            {
                EventHubClient eventHubClient = null;
                try
                {
                    eventHubClient = EventHubClient.CreateFromConnectionString(this.host.EventHubConnectionString);
                    var runtimeInfo = await eventHubClient.GetRuntimeInformationAsync().ConfigureAwait(false);

                    this.partitionIds = runtimeInfo.PartitionIds.ToList();
                }
                catch (Exception e)
                {
                    throw new EventProcessorConfigurationException("Encountered error while fetching the list of EventHub PartitionIds", e);
                }
                finally
                {
                    if (eventHubClient != null)
                    {
                        await eventHubClient.CloseAsync().ConfigureAwait(false);
                    }
                }

                ProcessorEventSource.Log.EventProcessorHostInfo(this.host.Id, $"PartitionCount: {this.partitionIds.Count}");
            }

            return(this.partitionIds);
        }
Ejemplo n.º 24
0
        public async Task SendEventMessageAsync(string name, IEnumerable <string> eventMessageList, ConcurrentDictionary <string, object> properties = null)
        {
            if (eventMessageList == null || !eventMessageList.Any())
            {
                throw new ArgumentNullException("eventMessageList", "Could not be null or empty.");
            }

            ProducerConfigurationsOptions producerConfiguration = GetProducerConfiguration(name);
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(producerConfiguration.ConnectionString)
            {
                EntityPath = producerConfiguration.EventHubName
            };
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            var eventDataBatch = new EventDataBatch(long.MaxValue);

            foreach (var eventMessage in eventMessageList)
            {
                if (string.IsNullOrWhiteSpace(eventMessage))
                {
                    throw new ArgumentNullException("eventMessage", "EventSendMessage must be defined.");
                }

                var eventData = await GetEventData(eventMessage, properties);

                eventDataBatch.TryAdd(eventData);
            }

            await eventHubClient.SendAsync(eventDataBatch);

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 25
0
        static async Task MainAsync(string[] args)
        {
            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("settings.json", true, true)
                                           .AddJsonFile("local.settings.json", false, true)
                                           .Build();

            // 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(configuration["EventHubConnectionString"])
            {
                EntityPath = configuration["EventHubName"]
            };

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

            await SendMessagesToEventHub(10);

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 26
0
        public async Task SendEventDataAsync(string name, IEnumerable <EventData> eventDataList)
        {
            if (eventDataList == null || !eventDataList.Any())
            {
                throw new ArgumentNullException("eventMessageList", "Could not be null or empty.");
            }

            ProducerConfigurationsOptions producerConfiguration = GetProducerConfiguration(name);
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(producerConfiguration.ConnectionString)
            {
                EntityPath = producerConfiguration.EventHubName
            };
            EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            var eventDataBatch = new EventDataBatch(long.MaxValue);

            foreach (var eventData in eventDataList)
            {
                eventDataBatch.TryAdd(eventData);
            }

            await eventHubClient.SendAsync(eventDataBatch);

            await eventHubClient.CloseAsync();
        }
        public async Task Close()
        {
            if (ProcessReceiver != null)
            {
                logger.LogDebug($"Closing EventHub Receiver");
                await ProcessReceiver.CloseAsync();
            }

            if (ResponseReceiver != null)
            {
                logger.LogDebug($"Closing Response Receiver");
                await ResponseReceiver.CloseAsync();
            }

            logger.LogDebug($"Closing EventHub Process Clients");
            await Task.WhenAll(_eventHubClients.Values.Select(s => s.CloseAsync()).ToList());

            if (_doorbellClient != null)
            {
                logger.LogDebug($"Closing Eventhub Doorbell Client {_doorbellClient.ClientId}");
                await _doorbellClient.CloseAsync();
            }

            if (_responseClient != null)
            {
                logger.LogDebug($"Closing Eventhub Response Client {_responseClient.ClientId}");
                await _responseClient.CloseAsync();
            }
        }
Ejemplo n.º 28
0
        public async Task SendEventObjectMessageAsync <TEventMessage>(string name, EventSendMessage <TEventMessage> eventMessage)
        {
            if (eventMessage == null || eventMessage.EventMessage == null)
            {
                throw new ArgumentNullException(nameof(eventMessage.EventMessage), "EventSendMessage must be defined.");
            }

            ProducerConfigurationsOptions producerConfiguration = GetProducerConfiguration(name);

            var connectionStringBuilder = new EventHubsConnectionStringBuilder(producerConfiguration.ConnectionString)
            {
                EntityPath = producerConfiguration.EventHubName
            };

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

            var eventData = new EventData(eventMessage.EventMessage.ToByteArray());

            if (eventMessage.Properties != null && eventMessage.Properties.Any())
            {
                foreach (var property in eventMessage.Properties)
                {
                    eventData.Properties.Add(property.Key, property.Value);
                }
            }

            await eventHubClient.SendAsync(eventData);

            await eventHubClient.CloseAsync();
        }
Ejemplo n.º 29
0
        private static async Task MainAsync(string[] args)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

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

            using (var reader = new StreamReader("FeedData.csv"))
                using (var csv = new CsvReader(reader))
                {
                    var records = csv.GetRecords <CustomEvent>();

                    foreach (var rec in records)
                    {
                        await SendMessagesToEventHub(rec);

                        await Task.Delay(1000);
                    }
                }

            await eventHubClient.CloseAsync();

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 30
0
        private static async Task MainAsync(string[] args)
        {
            var configurationRoot       = new ConfigurationBuilder().AddUserSecrets <Program>().Build();
            var config                  = new TheConfig(configurationRoot);
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(config.EventHubConnectionString)
            {
                EntityPath = config.EventHubName
            };

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

            int numMessagesToSend = 100;

            for (var i = 0; i < numMessagesToSend; i++)
            {
                try
                {
                    var message = i.ToString();
                    Console.WriteLine($"Sending number: {message}");
                    await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
                }
            }

            Console.WriteLine($"{numMessagesToSend} messages sent.");

            await eventHubClient.CloseAsync();
        }