Ejemplo n.º 1
0
        public async Task ProducerCanSendAnEventBatchUsingAPartitionHashKey()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(2))
            {
                IEnumerable <EventData> events = Enumerable
                                                 .Range(0, 25)
                                                 .Select(index => new EventData(Encoding.UTF8.GetBytes(new string('X', index + 5))));

                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                var batchOptions     = new BatchOptions {
                    PartitionKey = "some123key-!d"
                };

                await using (var client = new EventHubClient(connectionString))
                    await using (EventHubProducer producer = client.CreateProducer())
                    {
                        using EventDataBatch batch = await producer.CreateBatchAsync(batchOptions);

                        foreach (EventData eventData in events)
                        {
                            Assert.That(() => batch.TryAdd(eventData), Is.True, "An event was rejected by the batch; all events should be accepted.");
                        }

                        Assert.That(async() => await producer.SendAsync(batch), Throws.Nothing);
                    }
            }
        }
Ejemplo n.º 2
0
        public async Task ProducerCanSendLargeBatch()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString, new EventHubClientOptions {
                    RetryOptions = new RetryOptions {
                        TryTimeout = TimeSpan.FromMinutes(5)
                    }
                }))
                    await using (var producer = client.CreateProducer())
                    {
                        // Actual limit is 1046520 for a single event.
                        var events = new[]
                        {
                            new EventData(new byte[1000000 / 3]),
                            new EventData(new byte[1000000 / 3]),
                            new EventData(new byte[1000000 / 3])
                        };

                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerCanSendEventsWithCustomProperties()
        {
            await using (var scope = await EventHubScope.CreateAsync(4))
            {
                var events = new[]
                {
                    new EventData(new byte[] { 0x22, 0x33 }),
                    new EventData(Encoding.UTF8.GetBytes("This is a really long string of stuff that I wanted to type because I like to")),
                    new EventData(Encoding.UTF8.GetBytes("I wanted to type because I like to")),
                    new EventData(Encoding.UTF8.GetBytes("If you are reading this, you really like test cases"))
                };

                for (var index = 0; index < events.Length; ++index)
                {
                    events[index].Properties[index.ToString()] = "some value";
                    events[index].Properties["Type"]           = $"com.microsoft.test.Type{ index }";
                }

                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerCannotSendWhenClosed(bool sync)
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        var events = new[] { new EventData(Encoding.UTF8.GetBytes("Dummy event")) };
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);

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

                        Assert.That(async() => await producer.SendAsync(events), Throws.TypeOf <ObjectDisposedException>());
                    }
            }
        }
        public async Task ProducerCanSendBatchToASpecificPartition()
        {
            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();
                    var producerOptions = new EventHubProducerOptions {
                        PartitionId = partition
                    };

                    await using (var producer = client.CreateProducer(producerOptions))
                    {
                        var events = new[]
                        {
                            new EventData(Encoding.UTF8.GetBytes("This is a message")),
                            new EventData(Encoding.UTF8.GetBytes("This is another message")),
                            new EventData(Encoding.UTF8.GetBytes("Do we need more messages"))
                        };

                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public async Task ProducerCanSendLargeEventBatch()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString, new EventHubClientOptions {
                    RetryOptions = new RetryOptions {
                        TryTimeout = TimeSpan.FromMinutes(5)
                    }
                }))
                    await using (EventHubProducer producer = client.CreateProducer())
                    {
                        using EventDataBatch batch = await producer.CreateBatchAsync();

                        // Actual limit is 1046520 for a single event.
                        batch.TryAdd(new EventData(new byte[100000 / 3]));
                        batch.TryAdd(new EventData(new byte[100000 / 3]));
                        batch.TryAdd(new EventData(new byte[100000 / 3]));

                        Assert.That(batch.Count, Is.EqualTo(3), "The batch should contain all 3 events.");
                        Assert.That(async() => await producer.SendAsync(batch), Throws.Nothing);
                    }
            }
        }
Ejemplo n.º 7
0
        static async Task Produce(string connectionString, string eventHubName)
        {
            try
            {
                await using (var client = new EventHubClient(connectionString, eventHubName))
                    await using (var producer = client.CreateProducer())
                    {
                        var temperature = new Random();

                        // Send 10 messages to the topic
                        for (int i = 0; i < 10; i++)
                        {
                            var message = $"Temperature is: {temperature.Next(0, 45)}";

                            await producer.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));

                            Console.WriteLine($"SENT: {message}");
                        }
                    }
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Exception Occurred - {0}", e.Message));
            }
        }
Ejemplo n.º 8
0
        public async Task ReceiveCanReadOneEventBatch()
        {
            await using (var scope = await EventHubScope.CreateAsync(4))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                var eventBatch = new[]
                {
                    new EventData(Encoding.UTF8.GetBytes("One")),
                    new EventData(Encoding.UTF8.GetBytes("Two")),
                    new EventData(Encoding.UTF8.GetBytes("Three"))
                };

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

                    await using (var producer = client.CreateProducer(new EventHubProducerOptions {
                        PartitionId = partition
                    }))
                        await using (var consumer = client.CreateConsumer(partition, EventPosition.Latest))
                        {
                            // Initiate an operation to force the consumer to connect and set its position at the
                            // end of the event stream.

                            Assert.That(async() => await consumer.ReceiveAsync(1, TimeSpan.Zero), Throws.Nothing);

                            // Send the batch of events.

                            await producer.SendAsync(eventBatch);

                            // Recieve and validate the events; because there is some non-determinism in the messaging flow, the
                            // sent events may not be immediately available.  Allow for a small number of attempts to receive, in order
                            // to account for availability delays.

                            var receivedEvents = new List <EventData>();
                            var index          = 0;

                            while ((receivedEvents.Count < eventBatch.Length) && (++index < 5))
                            {
                                receivedEvents.AddRange(await consumer.ReceiveAsync(eventBatch.Length + 10, TimeSpan.FromMilliseconds(25)));
                            }

                            index = 0;

                            Assert.That(receivedEvents, Is.Not.Empty, "There should have been a set of events received.");

                            foreach (var receivedEvent in receivedEvents)
                            {
                                Assert.That(receivedEvent.IsEquivalentTo(eventBatch[index]), Is.True, $"The received event at index: { index } did not match the sent batch.");
                                ++index;
                            }

                            Assert.That(index, Is.EqualTo(eventBatch.Length), "The number of received events did not match the batch size.");
                        }
                }
            }
        }
        public async Task SendDoesNotUpdatePartitionPropertiesWhenSendingToDifferentPartition()
        {
            await using (var scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

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

                    var events = new[] { new EventData(Encoding.UTF8.GetBytes("I should not update stuff")) };

                    await using (var producer0 = client.CreateProducer(new EventHubProducerOptions {
                        PartitionId = partitionIds[0]
                    }))
                        await using (var producer1 = client.CreateProducer(new EventHubProducerOptions {
                            PartitionId = partitionIds[1]
                        }))
                        {
                            // Sending events beforehand so the partition has some information

                            await producer0.SendAsync(events);

                            var oldPartitionProperties = await client.GetPartitionPropertiesAsync(partitionIds[0]);

                            Assert.That(oldPartitionProperties, Is.Not.Null, "A set of partition properties should have been returned.");

                            await producer1.SendAsync(events);

                            var newPartitionProperties = await client.GetPartitionPropertiesAsync(partitionIds[0]);

                            Assert.That(newPartitionProperties, Is.Not.Null, "A set of partition properties should have been returned.");

                            // All properties should remain the same

                            Assert.That(newPartitionProperties.Id, Is.EqualTo(oldPartitionProperties.Id));
                            Assert.That(newPartitionProperties.EventHubPath, Is.EqualTo(oldPartitionProperties.EventHubPath));
                            Assert.That(newPartitionProperties.BeginningSequenceNumber, Is.EqualTo(oldPartitionProperties.BeginningSequenceNumber));
                            Assert.That(newPartitionProperties.LastEnqueuedSequenceNumber, Is.EqualTo(oldPartitionProperties.LastEnqueuedSequenceNumber));
                            Assert.That(newPartitionProperties.LastEnqueuedOffset, Is.EqualTo(oldPartitionProperties.LastEnqueuedOffset));
                        }
                }
            }
        }
Ejemplo n.º 10
0
        private static async Task CreateSenderAndReceiver()
        {
            Console.Write("Creating the Sender and Receivers... ");
            var partition       = (await client.GetPartitionIdsAsync()).First();
            var producerOptions = new EventHubProducerOptions
            {
                PartitionId = partition
            };

            sender   = client.CreateProducer(producerOptions);
            receiver = client.CreateConsumer(EventHubConsumer.DefaultConsumerGroupName, partition, EventPosition.Latest);
            Console.WriteLine("\tdone");
        }
Ejemplo n.º 11
0
        /// <summary>
        ///   Runs the sample using the specified Event Hubs connection information.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string for the Event Hubs namespace that the sample should target.</param>
        /// <param name="eventHubName">The name of the Event Hub, sometimes known as its path, that she sample should run against.</param>
        ///
        public async Task RunAsync(string connectionString,
                                   string eventHubName)
        {
            // We will start by creating a client using its default set of options.

            await using (var client = new EventHubClient(connectionString, eventHubName))
            {
                // Because partitions are owned by the Event Hubs service, it is not advised to assume that they have a stable
                // and predictable set of identifiers.  We'll inspect the Event Hub and select the first partition to use for
                // publishing our event batch.

                string[] partitionIds = await client.GetPartitionIdsAsync();

                // In order to request that a producer be associated with a specific partition, it needs to be created with a custom
                // set of options.  Like the Event Hub client, there are options for a producer available to tune the behavior for
                // operations that interact with the Event Hubs service.
                //
                // In our case, we will set the partition association but otherwise make use of the default options.

                var producerOptions = new EventHubProducerOptions
                {
                    PartitionId = partitionIds[0]
                };

                await using (var producer = client.CreateProducer(producerOptions))
                {
                    // When an Event Hub producer is associated with any specific partition, it can publish events only to that partition.
                    // The producer has no ability to ask for the service to route events, including by using a partition key.
                    //
                    // If you attempt to use a partition key with an Event Hub producer that is associated with a partition, an exception
                    // will occur.  Otherwise, publishing to a specific partition is exactly the same as other publishing scenarios.

                    // We will publish a small batch of events based on simple sentences.

                    var eventBatch = new EventData[]
                    {
                        new EventData(Encoding.UTF8.GetBytes("Hello, Event Hubs!")),
                        new EventData(Encoding.UTF8.GetBytes("Goodbye, Event Hubs!"))
                    };

                    await producer.SendAsync(eventBatch);

                    Console.WriteLine("The event batch has been published.");
                }
            }

            // At this point, our client and producer have passed their "using" scope and have safely been disposed of.  We
            // have no further obligations.

            Console.WriteLine();
        }
Ejemplo n.º 12
0
        public async Task ProducerCanSendSingleZeroLengthEvent()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (EventHubProducer producer = client.CreateProducer())
                    {
                        var singleEvent = new EventData(Array.Empty <byte>());
                        Assert.That(async() => await producer.SendAsync(singleEvent), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerWithNoOptionsCanSend()
        {
            await using (var scope = await EventHubScope.CreateAsync(4))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        var events = new[] { new EventData(Encoding.UTF8.GetBytes("AWord")) };
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerCanSendWhenClientIsClosed()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        client.Close();

                        var events = new EventData(Encoding.UTF8.GetBytes("Do not delete me!"));
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerWithOptionsCanSend()
        {
            await using (var scope = await EventHubScope.CreateAsync(4))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                var producerOptions  = new EventHubProducerOptions {
                    Retry = new ExponentialRetry(TimeSpan.FromSeconds(0.25), TimeSpan.FromSeconds(45), 5)
                };

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer(producerOptions))
                    {
                        var events = new[] { new EventData(Encoding.UTF8.GetBytes("AWord")) };
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        /// <summary>
        ///   Runs the sample using the specified Event Hubs connection information.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string for the Event Hubs namespace that the sample should target.</param>
        /// <param name="eventHubName">The name of the Event Hub, sometimes known as its path, that she sample should run against.</param>
        ///
        public async Task RunAsync(string connectionString,
                                   string eventHubName)
        {
            // We will start by creating a client and a producer, each using their default set of options.

            await using (var client = new EventHubClient(connectionString, eventHubName))
                await using (EventHubProducer producer = client.CreateProducer())
                {
                    // When an Event Hub producer is not associated with any specific partition, it may be desirable to request that
                    // the Event Hubs service keep different events or batches of events together on the same partition.  This can be
                    // accomplished by setting a partition key when publishing the events.
                    //
                    // The partition key is NOT the identifier of a specific partition.  Rather, it is an arbitrary piece of string data
                    // that Event Hubs uses as the basis to compute a hash value.  Event Hubs will associate the hash value with a specific
                    // partition, ensuring that any events published with the same partition key are routed to the same partition.
                    //
                    // Note that there is no means of accurately predicting which partition will be associated with a given partition key;
                    // we can only be assured that it will be a consistent choice of partition.  If you have a need to understand which
                    // exact partition an event is published to, you will need to use an Event Hub producer associated with that partition.

                    // We will publish a small batch of events based on simple sentences.

                    var eventBatch = new EventData[]
                    {
                        new EventData(Encoding.UTF8.GetBytes("Hello, Event Hubs!")),
                        new EventData(Encoding.UTF8.GetBytes("Goodbye, Event Hubs!"))
                    };

                    // To choose a partition key, you will need to create a custom set of send options.

                    var sendOptions = new SendOptions
                    {
                        PartitionKey = "Any Value Will Do..."
                    };

                    await producer.SendAsync(eventBatch, sendOptions);

                    Console.WriteLine("The event batch has been published.");
                }

            // At this point, our client and producer have passed their "using" scope and have safely been disposed of.  We
            // have no further obligations.

            Console.WriteLine();
        }
Ejemplo n.º 17
0
        /// <summary>
        ///   Runs the sample using the specified Event Hubs connection information.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string for the Event Hubs namespace that the sample should target.</param>
        /// <param name="eventHubName">The name of the Event Hub, sometimes known as its path, that she sample should run against.</param>
        ///
        public async Task RunAsync(string connectionString,
                                   string eventHubName)
        {
            // To create an Event Hub producer, a client is needed.  We will start by creating a client with
            // the default set of options.
            //
            // Using our client, we will then create a producer.  Like the client, our Event Hub producer also manages resources
            // and should be explicitly closed or disposed, but it is not necessary to do both.  In our case, we will take
            // advantage of the new asynchronous dispose to ensure that we clean up our client and producer when we are
            // done or when an exception is encountered.

            await using (var client = new EventHubClient(connectionString, eventHubName))
                await using (EventHubProducer producer = client.CreateProducer())
                {
                    // By default, an Event Hub producer is not associated with any specific partition.  When publishing events,
                    // it will allow the Event Hubs service to route the event to an available partition.
                    //
                    // Allowing automatic routing of partitions is recommended when:
                    //  - The publishing of events needs to be highly available.
                    //  - The event data should be evenly distributed among all available partitions.


                    // An event is represented by an arbitrary collection of bytes and metadata.  Event Hubs does not make any
                    // assumptions about the data nor attempt to perform any operations on it; you are free to create the data
                    // in whatever form makes sense for your scenario.
                    //
                    // In our case, we will translate a simple sentence into bytes and send it to our Event Hub.

                    var eventData = new EventData(Encoding.UTF8.GetBytes("Hello, Event Hubs!"));

                    // When the producer sends the event, it will receive an acknowledgment from the Event Hubs service; so
                    // long as there is no exception thrown by this call, the service is now responsible for delivery.  Your
                    // event data will be published to one of the Event Hub partitions, though there may be a (very) slight
                    // delay until it is available to be consumed.

                    await producer.SendAsync(eventData);

                    Console.WriteLine("The event has been published.");
                }

            // At this point, our client and producer have passed their "using" scope and have safely been disposed of.  We
            // have no further obligations.

            Console.WriteLine();
        }
        public async Task ProducerCannotSendSingleEventLargerThanMaximumSize()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        // Actual limit is 1046520 for a single event
                        var singleEvent = new EventData(new byte[1500000]);
                        var eventBatch  = new[] { new EventData(new byte[1500000]) };

                        Assert.That(async() => await producer.SendAsync(singleEvent), Throws.TypeOf <TrackOne.MessageSizeExceededException>());
                        Assert.That(async() => await producer.SendAsync(eventBatch), Throws.TypeOf <TrackOne.MessageSizeExceededException>());
                    }
            }
        }
        public async Task ProducerCanSendSingleLargeEvent()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        // Actual limit is 1046520 for a single event
                        var singleEvent = new EventData(new byte[1000000]);
                        var eventBatch  = new[] { new EventData(new byte[1000000]) };

                        Assert.That(async() => await producer.SendAsync(singleEvent), Throws.Nothing);
                        Assert.That(async() => await producer.SendAsync(eventBatch), Throws.Nothing);
                    }
            }
        }
Ejemplo n.º 20
0
        public async Task ProducerCannotSendWhenProxyIsInvalid()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                var clientOptions    = new EventHubClientOptions
                {
                    Proxy         = new WebProxy("http://1.2.3.4:9999"),
                    TransportType = TransportType.AmqpWebSockets
                };

                await using (var invalidProxyClient = new EventHubClient(connectionString, clientOptions))
                    await using (var invalidProxyProducer = invalidProxyClient.CreateProducer())
                    {
                        Assert.That(async() => await invalidProxyProducer.SendAsync(new EventData(new byte[1])), Throws.InstanceOf <WebSocketException>());
                    }
            }
        }
Ejemplo n.º 21
0
        public async Task ProducerCanSendZeroLengthEventBatch()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (EventHubProducer producer = client.CreateProducer())
                    {
                        using EventDataBatch batch = await producer.CreateBatchAsync();

                        batch.TryAdd(new EventData(Array.Empty <byte>()));

                        Assert.That(batch.Count, Is.EqualTo(1), "The batch should contain a single event.");
                        Assert.That(async() => await producer.SendAsync(batch), Throws.Nothing);
                    }
            }
        }
        public async Task SendUpdatesPartitionProperties()
        {
            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();
                    var events    = new[] { new EventData(Encoding.UTF8.GetBytes("I should update stuff")) };

                    await using (var producer = client.CreateProducer(new EventHubProducerOptions {
                        PartitionId = partition
                    }))
                    {
                        // Sending events beforehand so the partition has some information

                        await producer.SendAsync(events);

                        var oldPartitionProperties = await client.GetPartitionPropertiesAsync(partition);

                        Assert.That(oldPartitionProperties, Is.Not.Null, "A set of partition properties should have been returned.");

                        await producer.SendAsync(events);

                        var newPartitionProperties = await client.GetPartitionPropertiesAsync(partition);

                        Assert.That(newPartitionProperties, Is.Not.Null, "A set of partition properties should have been returned.");

                        // The following properties should not have been altered

                        Assert.That(newPartitionProperties.Id, Is.EqualTo(oldPartitionProperties.Id));
                        Assert.That(newPartitionProperties.EventHubPath, Is.EqualTo(oldPartitionProperties.EventHubPath));
                        Assert.That(newPartitionProperties.BeginningSequenceNumber, Is.EqualTo(oldPartitionProperties.BeginningSequenceNumber));

                        // The following properties should have been updated

                        Assert.That(newPartitionProperties.LastEnqueuedSequenceNumber, Is.GreaterThan(oldPartitionProperties.LastEnqueuedSequenceNumber));
                        Assert.That(newPartitionProperties.LastEnqueuedOffset, Is.GreaterThan(oldPartitionProperties.LastEnqueuedOffset));
                    }
                }
            }
        }
        public async Task ProducerCannotSendToInvalidPartition(string invalidPartition)
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                {
                    var events = new[] { new EventData(Encoding.UTF8.GetBytes("Lorem Ipsum")) };

                    await using (var producer = client.CreateProducer(new EventHubProducerOptions {
                        PartitionId = invalidPartition
                    }))
                    {
                        Assert.That(async() => await producer.SendAsync(events), Throws.TypeOf <ArgumentOutOfRangeException>());
                    }
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        ///   Runs the sample using the specified Event Hubs connection information.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string for the Event Hubs namespace that the sample should target.</param>
        /// <param name="eventHubName">The name of the Event Hub, sometimes known as its path, that she sample should run against.</param>
        ///
        public async Task RunAsync(string connectionString,
                                   string eventHubName)
        {
            // We will start by creating a client and a producer, each using their default set of options.

            await using (var client = new EventHubClient(connectionString, eventHubName))
                await using (EventHubProducer producer = client.CreateProducer())
                {
                    // Because an event consists mainly of an opaque set of bytes, it may be difficult for consumers of those events to
                    // make informed decisions about how to process them.
                    //
                    // In order to allow event publishers to offer better context for consumers, event data may also contain custom metadata,
                    // in the form of a set of key/value pairs.  This metadata is not used by, or in any way meaningful to, the Event Hubs
                    // service; it exists only for coordination between event publishers and consumers.
                    //
                    // One common scenario for the inclusion of metadata is to provide a hint about the type of data contained by an event,
                    // so that consumers understand its format and can deserialize it appropriately.
                    //
                    // We will publish a small batch of events based on simple sentences, but will attach some custom metadata with
                    // pretend type names and other hints.  Note that the set of metadata is unique to an event; there is no need for every
                    // event in a batch to have the same metadata properties available nor the same data type for those properties.

                    var firstEvent = new EventData(Encoding.UTF8.GetBytes("Hello, Event Hubs!"));
                    firstEvent.Properties.Add("EventType", "com.microsoft.samples.hello-event");
                    firstEvent.Properties.Add("priority", 1);
                    firstEvent.Properties.Add("score", 9.0);

                    var secondEvent = new EventData(Encoding.UTF8.GetBytes("Goodbye, Event Hubs!"));
                    secondEvent.Properties.Add("EventType", "com.microsoft.samples.goodbye-event");
                    secondEvent.Properties.Add("priority", "17");
                    secondEvent.Properties.Add("blob", true);

                    await producer.SendAsync(new[] { firstEvent, secondEvent });

                    Console.WriteLine("The event batch has been published.");
                }

            // At this point, our client and producer have passed their "using" scope and have safely been disposed of.  We
            // have no further obligations.

            Console.WriteLine();
        }
        public async Task ProducerCanSendWhenPartitionIsNull()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                {
                    var producerOptions = new EventHubProducerOptions {
                        PartitionId = null
                    };

                    await using (var producer = client.CreateProducer(producerOptions))
                    {
                        var events = new[] { new EventData(Encoding.UTF8.GetBytes("Will it work")) };
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
                }
            }
        }
        public async Task ProducerCanSendZeroLengthBatch()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        var events = new[]
                        {
                            new EventData(new byte[0]),
                            new EventData(new byte[0]),
                            new EventData(new byte[0])
                        };

                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerCanSendBatch()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        var events = new[]
                        {
                            new EventData(Encoding.UTF8.GetBytes("This is a message")),
                            new EventData(Encoding.UTF8.GetBytes("This is another message")),
                            new EventData(Encoding.UTF8.GetBytes("So many messages"))
                        };

                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }
        public async Task ProducerCanSendEventsUsingAPartitionHashHey()
        {
            await using (var scope = await EventHubScope.CreateAsync(4))
            {
                var events = Enumerable
                             .Range(0, 25)
                             .Select(index => new EventData(Encoding.UTF8.GetBytes(new String('X', index + 5))));

                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (var producer = client.CreateProducer())
                    {
                        var batchOptions = new SendOptions {
                            PartitionKey = "some123key-!d"
                        };
                        Assert.That(async() => await producer.SendAsync(events, batchOptions), Throws.Nothing);
                    }
            }
        }
Ejemplo n.º 29
0
        public async Task ProducerCanSendAnEventBatch()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);

                await using (var client = new EventHubClient(connectionString))
                    await using (EventHubProducer producer = client.CreateProducer())
                    {
                        using EventDataBatch batch = await producer.CreateBatchAsync();

                        batch.TryAdd(new EventData(Encoding.UTF8.GetBytes("This is a message")));
                        batch.TryAdd(new EventData(Encoding.UTF8.GetBytes("This is another message")));
                        batch.TryAdd(new EventData(Encoding.UTF8.GetBytes("So many messages")));

                        Assert.That(batch.Count, Is.EqualTo(3), "The batch should contain all 3 events.");
                        Assert.That(async() => await producer.SendAsync(batch), Throws.Nothing);
                    }
            }
        }
Ejemplo n.º 30
0
        public async Task ProducerWithOptionsCanSend(TransportType transportType)
        {
            await using (var scope = await EventHubScope.CreateAsync(4))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                var producerOptions  = new EventHubProducerOptions {
                    RetryOptions = new RetryOptions {
                        MaximumRetries = 5
                    }
                };

                await using (var client = new EventHubClient(connectionString, new EventHubClientOptions {
                    TransportType = transportType
                }))
                    await using (var producer = client.CreateProducer(producerOptions))
                    {
                        var events = new[] { new EventData(Encoding.UTF8.GetBytes("AWord")) };
                        Assert.That(async() => await producer.SendAsync(events), Throws.Nothing);
                    }
            }
        }