public async Task DisableWithReceiverOptions()
        {
            await using (var scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString  = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient          = EventHubClient.CreateFromConnectionString(connectionString);
                var partitionReceiver = default(PartitionReceiver);

                try
                {
                    // Send single event
                    await TestUtility.SendToPartitionAsync(ehClient, targetPartitionId, "this is the message body");

                    // Enable runtime metrics on the client.
                    ehClient.EnableReceiverRuntimeMetric = true;

                    // Create a new receiver and disable runtime metrics via ReceiverOptions.
                    partitionReceiver =
                        ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, targetPartitionId, EventPosition.FromStart(),
                                                new ReceiverOptions()
                    {
                        EnableReceiverRuntimeMetric = false
                    });

                    await ValidateDisabledBehavior(partitionReceiver);
                }
                finally
                {
                    await Task.WhenAll(
                        partitionReceiver?.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
        public async Task BasicValidation()
        {
            await using (var scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString  = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient          = EventHubClient.CreateFromConnectionString(connectionString);
                var partitionReceiver = default(PartitionReceiver);

                try
                {
                    // Send some number of messages to target partition.
                    await TestUtility.SendToPartitionAsync(ehClient, targetPartitionId, "this is the message body", 10);

                    // Get partition runtime info so we can compare with runtime metrics.
                    var pInfo = await ehClient.GetPartitionRuntimeInformationAsync(targetPartitionId);

                    // Create a new receiver with ReceiverOptions setting to enable runtime metrics.
                    partitionReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName,
                                                                targetPartitionId,
                                                                EventPosition.FromStart(),
                                                                new ReceiverOptions()
                    {
                        EnableReceiverRuntimeMetric = true
                    });

                    await ValidateEnabledBehavior(partitionReceiver, pInfo);
                }
                finally
                {
                    await Task.WhenAll(
                        partitionReceiver?.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
Example #3
0
        public async Task CloseReceiverClient()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var pSender          = ehClient.CreatePartitionSender("0");
                var pReceiver        = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());

                try
                {
                    TestUtility.Log("Sending single event to partition 0");
                    var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));
                    await pSender.SendAsync(eventData);

                    TestUtility.Log("Receiving the event.");
                    var events = await pReceiver.ReceiveAsync(1);

                    Assert.True(events != null && events.Count() == 1, "Failed to receive 1 event");
                }
                finally
                {
                    TestUtility.Log("Closing partition receiver");
                    await Task.WhenAll(
                        pReceiver.CloseAsync(),
                        ehClient.CloseAsync());
                }

                await Assert.ThrowsAsync <ObjectDisposedException>(async() =>
                {
                    TestUtility.Log("Receiving another event from partition 0 on the closed receiver, this should fail");
                    await pReceiver.ReceiveAsync(1);
                });
            }
        }
Example #4
0
        public async Task PartitionReceiverReceive()
        {
            var partitionId   = "1";
            var payloadString = "Hello EventHub!";

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

                try
                {
                    TestUtility.Log("Receiving Events via PartitionReceiver.ReceiveAsync");

                    using (var sendEvent = new EventData(Encoding.UTF8.GetBytes(payloadString)))
                        using (var receivedEvent = await SendAndReceiveEventAsync(partitionId, sendEvent, ehClient))
                        {
                            Assert.True(Encoding.UTF8.GetString(receivedEvent.Body.Array) == payloadString, "Received payload string isn't the same as sent payload string.");
                        }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
Example #5
0
        public async Task SendAndReceiveLargeMessage()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var bodySize         = 250 * 1024;
                var targetPartition  = "0";
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);

                try
                {
                    using (var edToSend = new EventData(new byte[bodySize]))
                    {
                        TestUtility.Log($"Sending one message with body size {bodySize} bytes.");
                        var edReceived = await SendAndReceiveEventAsync(targetPartition, edToSend, ehClient);

                        // Validate body size.
                        Assert.True(edReceived.Body.Count == bodySize, $"Sent {bodySize} bytes and received {edReceived.Body.Count}");
                    }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
Example #6
0
        public async Task PartitionSenderSend()
        {
            TestUtility.Log("Sending single Event via PartitionSender.SendAsync(EventData)");

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

                try
                {
                    using (var eventData = new EventData(Encoding.UTF8.GetBytes("Hello again EventHub Partition 1!")))
                    {
                        await partitionSender1.SendAsync(eventData);
                    }
                }
                finally
                {
                    await Task.WhenAll(
                        partitionSender1?.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
        public async Task GetEventHubRuntimeInformation()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);

                try
                {
                    TestUtility.Log("Getting  EventHubRuntimeInformation");
                    var eventHubRuntimeInformation = await ehClient.GetRuntimeInformationAsync();

                    Assert.True(eventHubRuntimeInformation != null, "eventHubRuntimeInformation was null!");
                    Assert.True(eventHubRuntimeInformation.PartitionIds != null, "eventHubRuntimeInformation.PartitionIds was null!");
                    Assert.True(eventHubRuntimeInformation.PartitionIds.Length != 0, "eventHubRuntimeInformation.PartitionIds.Length was 0!");

                    TestUtility.Log("Found partitions:");
                    foreach (string partitionId in eventHubRuntimeInformation.PartitionIds)
                    {
                        TestUtility.Log(partitionId);
                    }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
Example #8
0
        public async Task SendAndReceiveArraySegmentEventData()
        {
            var targetPartition = "0";
            var byteArr         = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

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

                try
                {
                    using (var edToSend = new EventData(new ArraySegment <byte>(byteArr)))
                    {
                        var edReceived = await SendAndReceiveEventAsync(targetPartition, edToSend, ehClient);

                        // Validate array segment count.
                        Assert.True(edReceived.Body.Count == byteArr.Count(), $"Sent {byteArr.Count()} bytes and received {edReceived.Body.Count}");
                    }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
Example #9
0
        public async Task PartitionReceiverEpochReceive()
        {
            TestUtility.Log("Testing EpochReceiver semantics");

            await using (var scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var epochReceiver1   = ehClient.CreateEpochReceiver(PartitionReceiver.DefaultConsumerGroupName, "1", EventPosition.FromStart(), 1);
                var epochReceiver2   = ehClient.CreateEpochReceiver(PartitionReceiver.DefaultConsumerGroupName, "1", EventPosition.FromStart(), 2);
                try
                {
                    // Read the events from Epoch 1 Receiver until we're at the end of the stream
                    TestUtility.Log("Starting epoch 1 receiver");
                    IEnumerable <EventData> events;
                    do
                    {
                        events = await epochReceiver1.ReceiveAsync(10);

                        var count = events?.Count() ?? 0;
                    }while (events != null);

                    TestUtility.Log("Starting epoch 2 receiver");
                    var epoch2ReceiveTask = epochReceiver2.ReceiveAsync(10);

                    DateTime stopTime = DateTime.UtcNow.AddSeconds(30);
                    do
                    {
                        events = await epochReceiver1.ReceiveAsync(10);

                        var count = events?.Count() ?? 0;
                        TestUtility.Log($"Epoch 1 receiver got {count} event(s)");
                    }while (DateTime.UtcNow < stopTime);

                    throw new InvalidOperationException("Epoch 1 receiver should have encountered an exception by now!");
                }
                catch (ReceiverDisconnectedException disconnectedException)
                {
                    TestUtility.Log($"Received expected exception {disconnectedException.GetType()}: {disconnectedException.Message}");

                    try
                    {
                        await epochReceiver1.ReceiveAsync(10);

                        throw new InvalidOperationException("Epoch 1 receiver should throw ReceiverDisconnectedException here too!");
                    }
                    catch (ReceiverDisconnectedException e)
                    {
                        TestUtility.Log($"Received expected exception {e.GetType()}");
                    }
                }
                finally
                {
                    await Task.WhenAll(
                        epochReceiver1.CloseAsync(),
                        epochReceiver2.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
        public async Task CreatingPartitionKeyBatchOnPartitionSenderShouldFail()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var partitionSender  = ehClient.CreatePartitionSender("0");

                try
                {
                    Assert.Throws <InvalidOperationException>(() =>
                    {
                        TestUtility.Log("Attempting to create a partition-key batch on partition sender. This should fail.");
                        partitionSender.CreateBatch(new BatchOptions()
                        {
                            PartitionKey = "this is the key to fail"
                        });
                    });
                }
                finally
                {
                    await Task.WhenAll(
                        partitionSender.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
Example #11
0
        public async Task SendAndReceiveZeroLengthBody()
        {
            var targetPartition = "0";

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

                try
                {
                    using (var zeroBodyEventData = new EventData(new byte[0]))
                    {
                        var edReceived = await SendAndReceiveEventAsync(targetPartition, zeroBodyEventData, ehClient);

                        // Validate body.
                        Assert.True(edReceived.Body.Count == 0, $"Received event's body isn't zero byte long.");
                    }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
        public async Task InvalidPrefetchCount()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var receiver         = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());

                try
                {
                    await Assert.ThrowsAsync <ArgumentOutOfRangeException>(() =>
                    {
                        receiver.PrefetchCount = 3;
                        throw new Exception("Setting PrefetchCount to 3 didn't fail.");
                    });

                    TestUtility.Log("Setting PrefetchCount to 10.");
                    receiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());
                    receiver.PrefetchCount = 10;

                    TestUtility.Log("Setting PrefetchCount to int.MaxValue.");
                    receiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());
                    receiver.PrefetchCount = int.MaxValue;
                }
                finally
                {
                    await Task.WhenAll(
                        receiver.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
        public async Task NonexsistentEntity()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                // Rebuild connection string with a nonexistent entity.
                var csb = new EventHubsConnectionStringBuilder(connectionString);
                csb.EntityPath = Guid.NewGuid().ToString();

                var eventProcessorHost = new EventProcessorHost(
                    string.Empty,
                    PartitionReceiver.DefaultConsumerGroupName,
                    csb.ToString(),
                    TestUtility.StorageConnectionString,
                    scope.EventHubName.ToLower());

                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);
            }
        }
        public async Task HostReregisterShouldFail()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString   = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var eventProcessorHost = new EventProcessorHost(
                    string.Empty,
                    PartitionReceiver.DefaultConsumerGroupName,
                    connectionString,
                    TestUtility.StorageConnectionString,
                    scope.EventHubName.ToLower());

                try
                {
                    // Calling register for the first time should succeed.
                    TestUtility.Log("Registering EventProcessorHost for the first time.");
                    await eventProcessorHost.RegisterEventProcessorAsync <TestEventProcessor>();

                    await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                    {
                        TestUtility.Log("Registering EventProcessorHost for the second time which should fail.");
                        await eventProcessorHost.RegisterEventProcessorAsync <TestEventProcessor>();
                    });
                }
                finally
                {
                    await eventProcessorHost.UnregisterEventProcessorAsync();
                }
            }
        }
        public async Task SendingPartitionKeyBatchOnPartitionSenderShouldFail()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var partitionSender  = default(PartitionSender);

                try
                {
                    var partitions = await GetPartitionsAsync(ehClient);

                    var partitionId = partitions[this.random.Next(partitions.Length)];
                    partitionSender = ehClient.CreatePartitionSender(partitionId);

                    var batchOptions = new BatchOptions()
                    {
                        PartitionKey = "this is the partition key"
                    };
                    var batcher = ehClient.CreateBatch(batchOptions);

                    await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                    {
                        TestUtility.Log("Attempting to send a partition-key batch on partition sender. This should fail.");
                        await partitionSender.SendAsync(batcher);
                    });
                }
                finally
                {
                    await Task.WhenAll(
                        partitionSender.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
Example #16
0
        public async Task PartitionSenderSendBatch()
        {
            TestUtility.Log("Sending single Event via PartitionSender.SendAsync(IEnumerable<EventData>)");

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

                try
                {
                    using (var eventData1 = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!")))
                        using (var eventData2 = new EventData(Encoding.UTF8.GetBytes("This is another message in the batch!")))
                        {
                            eventData2.Properties["ContosoEventType"] = "some value here";
                            await partitionSender1.SendAsync(new[] { eventData1, eventData2 });
                        }
                }
                finally
                {
                    await Task.WhenAll(
                        partitionSender1?.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
Example #17
0
        /// <summary>
        ///   Performs the tasks needed to initialize and set up the environment for an instance
        ///   of the test scenario.  When multiple instances are run in parallel, setup will be
        ///   run once for each prior to its execution.
        /// </summary>
        ///
        public async override Task SetupAsync()
        {
            await base.SetupAsync().ConfigureAwait(false);

            // Attempt to take a consumer group from the available set; to ensure that the
            // test scenario can support the requested level of parallelism without violating
            // the concurrent reader limits of a consumer group, the default consumer group
            // should not be used.

            if (!s_consumerGroups.TryDequeue(out var consumerGroup))
            {
                throw new InvalidOperationException("Unable to reserve a consumer group to read from.");
            }

            _client      = EventHubClient.CreateFromConnectionString(TestUtility.BuildEventHubsConnectionString(s_scope.EventHubName));
            _partitionId = (await _client.GetRuntimeInformationAsync().ConfigureAwait(false)).PartitionIds[0];

            _receiver = _client.CreateReceiver(
                consumerGroup,
                _partitionId,
                EventPosition.FromStart());

            // Force the connection and link creation by reading a single event.

            await _receiver.ReceiveAsync(1).ConfigureAwait(false);
        }
Example #18
0
 public async Task Unregistering_plugin_should_complete_without_plugin_set()
 {
     await using (var scope = await EventHubScope.CreateAsync(1))
     {
         var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
         this.EventHubClient = EventHubClient.CreateFromConnectionString(connectionString);
         this.EventHubClient.UnregisterPlugin("Non-existant plugin");
         await this.EventHubClient.CloseAsync();
     }
 }
Example #19
0
        public async Task ReceiverIdentifier()
        {
            await using (var scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var receivers        = new List <PartitionReceiver>();

                try
                {
                    for (int i = 0; i < 5; i++)
                    {
                        TestUtility.Log($"Creating receiver {i}");
                        var newReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "1", EventPosition.FromStart(),
                                                                  new ReceiverOptions()
                        {
                            Identifier = $"receiver{i}"
                        });

                        // Issue a receive call so link will become active.
                        await newReceiver.ReceiveAsync(10);

                        receivers.Add(newReceiver);
                    }

                    try
                    {
                        // Attempt to create 6th receiver. This should fail.
                        var failReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "1", EventPosition.FromStart());
                        await failReceiver.ReceiveAsync(10);

                        throw new InvalidOperationException("6th receiver should have encountered QuotaExceededException.");
                    }
                    catch (QuotaExceededException ex)
                    {
                        TestUtility.Log($"Received expected exception {ex.GetType()}: {ex.Message}");
                        foreach (var receiver in receivers)
                        {
                            Assert.True(ex.Message.Contains(receiver.Identifier), $"QuotaExceededException message is missing receiver identifier '{receiver.Identifier}'");
                        }
                    }
                }
                finally
                {
                    // Close all receivers.
                    foreach (var receiver in receivers)
                    {
                        await Task.WhenAll(
                            receiver.CloseAsync(),
                            ehClient.CloseAsync());
                    }
                }
            }
        }
        public async Task GetEventHubPartitionRuntimeInformation()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var csb        = new EventHubsConnectionStringBuilder(connectionString);
                var ehClient   = EventHubClient.CreateFromConnectionString(csb.ToString());
                var partitions = await this.GetPartitionsAsync(ehClient);

                try
                {
                    TestUtility.Log("Getting EventHubPartitionRuntimeInformation on each partition in parallel");
                    var tasks = partitions.Select(async(pid) =>
                    {
                        // Send some messages so we can have meaningful data returned from service call.
                        PartitionSender partitionSender = ehClient.CreatePartitionSender(pid);

                        try
                        {
                            TestUtility.Log($"Sending single event to partition {pid}");
                            var eDataToSend = new EventData(new byte[1]);
                            await partitionSender.SendAsync(eDataToSend);

                            TestUtility.Log($"Getting partition runtime information on partition {pid}");
                            var partition = await ehClient.GetPartitionRuntimeInformationAsync(pid);
                            TestUtility.Log($"Path:{partition.Path} PartitionId:{partition.PartitionId} BeginSequenceNumber:{partition.BeginSequenceNumber} LastEnqueuedOffset:{partition.LastEnqueuedOffset} LastEnqueuedTimeUtc:{partition.LastEnqueuedTimeUtc} LastEnqueuedSequenceNumber:{partition.LastEnqueuedSequenceNumber}");

                            // Validations.
                            Assert.True(partition.Path == csb.EntityPath, $"Returned path {partition.Path} is different than {csb.EntityPath}");
                            Assert.True(partition.PartitionId == pid, $"Returned partition id {partition.PartitionId} is different than {pid}");
                            Assert.True(partition.LastEnqueuedOffset != null, "Returned LastEnqueuedOffset is null");
                            Assert.True(partition.LastEnqueuedTimeUtc != null, "Returned LastEnqueuedTimeUtc is null");

                            // Validate returned data regarding recently sent event.
                            // Account 60 seconds of max clock skew.
                            Assert.True(partition.LastEnqueuedOffset != "-1", $"Returned LastEnqueuedOffset is {partition.LastEnqueuedOffset}");
                            Assert.True(partition.BeginSequenceNumber >= 0, $"Returned BeginSequenceNumber is {partition.BeginSequenceNumber}");
                            Assert.True(partition.LastEnqueuedSequenceNumber >= 0, $"Returned LastEnqueuedSequenceNumber is {partition.LastEnqueuedSequenceNumber}");
                            Assert.True(partition.LastEnqueuedTimeUtc >= DateTime.UtcNow.AddSeconds(-60), $"Returned LastEnqueuedTimeUtc is {partition.LastEnqueuedTimeUtc}");
                        }
                        finally
                        {
                            await partitionSender.CloseAsync();
                        }
                    });

                    await Task.WhenAll(tasks);
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
        public async Task UseSharedAccessSignature()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var csb           = new EventHubsConnectionStringBuilder(connectionString);
                var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(csb.SasKeyName, csb.SasKey);
                var token         = await tokenProvider.GetTokenAsync(csb.Endpoint.ToString(), TimeSpan.FromSeconds(120));

                var sas = token.TokenValue.ToString();

                // Update connection string builder to use shared access signature instead.
                csb.SasKey                = "";
                csb.SasKeyName            = "";
                csb.SharedAccessSignature = sas;

                // Create new client with updated connection string.
                var ehClient = EventHubClient.CreateFromConnectionString(csb.ToString());

                // Send one event
                TestUtility.Log($"Sending one message.");
                var ehSender  = ehClient.CreatePartitionSender("0");
                var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));
                await ehSender.SendAsync(eventData);

                // Receive event.
                PartitionReceiver ehReceiver = null;
                try
                {
                    TestUtility.Log($"Receiving one message.");
                    ehReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());
                    var msg = await ehReceiver.ReceiveAsync(1);

                    Assert.True(msg != null, "Failed to receive message.");
                }
                finally
                {
                    await ehReceiver?.CloseAsync();
                }

                // Get EH runtime information.
                TestUtility.Log($"Getting Event Hub runtime information.");
                var ehInfo = await ehClient.GetRuntimeInformationAsync();

                Assert.True(ehInfo != null, "Failed to get runtime information.");

                // Get EH partition runtime information.
                TestUtility.Log($"Getting Event Hub partition '0' runtime information.");
                var partitionInfo = await ehClient.GetPartitionRuntimeInformationAsync("0");

                Assert.True(ehInfo != null, "Failed to get runtime partition information.");
            }
        }
Example #22
0
        public async Task InvalidProxy()
        {
            // Send call should fail.
            await Assert.ThrowsAsync <WebSocketException>(async() =>
            {
                await using (var scope = await EventHubScope.CreateAsync(2))
                {
                    var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                    var ehClient         = EventHubClient.CreateFromConnectionString(GetWebSocketConnectionString(connectionString));
                    ehClient.WebProxy    = new WebProxy("http://1.2.3.4:9999");
                    var edToFail         = new EventData(Encoding.UTF8.GetBytes("This is a sample event."));
                    await ehClient.SendAsync(edToFail);
                }
            });



            // Receive call should fail.
            await Assert.ThrowsAsync <WebSocketException>(async() =>
            {
                await using (var scope = await EventHubScope.CreateAsync(2))
                {
                    var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                    var ehClient         = EventHubClient.CreateFromConnectionString(GetWebSocketConnectionString(connectionString));
                    ehClient.WebProxy    = new WebProxy("http://1.2.3.4:9999");
                    await ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart()).ReceiveAsync(1);
                }
            });



            // Management link call should fail.
            await Assert.ThrowsAsync <WebSocketException>(async() =>
            {
                await using (var scope = await EventHubScope.CreateAsync(2))
                {
                    var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                    var ehClient         = EventHubClient.CreateFromConnectionString(GetWebSocketConnectionString(connectionString));
                    ehClient.WebProxy    = new WebProxy("http://1.2.3.4:9999");
                    await ehClient.GetRuntimeInformationAsync();
                }
            });



            // Send/receive should work fine w/o proxy.
            await using (var scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehNoProxyClient  = EventHubClient.CreateFromConnectionString(GetWebSocketConnectionString(connectionString));
                var eventData        = new EventData(Encoding.UTF8.GetBytes("This is a sample event."));
            }
        }
Example #23
0
        public async Task PartitionReceiverReceiveBatch()
        {
            const int MaxBatchSize = 5;

            TestUtility.Log("Receiving Events via PartitionReceiver.ReceiveAsync(BatchSize)");
            const string partitionId = "0";

            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString  = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient          = EventHubClient.CreateFromConnectionString(connectionString);
                var partitionSender   = ehClient.CreatePartitionSender(partitionId);
                var partitionReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, partitionId, EventPosition.FromEnqueuedTime(DateTime.UtcNow.AddMinutes(-10)));

                try
                {
                    int eventCount = 20;
                    TestUtility.Log($"Sending {eventCount} events to Partition {partitionId}");
                    var sendEvents = new List <EventData>(eventCount);
                    for (int i = 0; i < eventCount; i++)
                    {
                        sendEvents.Add(new EventData(Encoding.UTF8.GetBytes($"Hello EventHub! Message {i}")));
                    }
                    await partitionSender.SendAsync(sendEvents);

                    int maxReceivedBatchSize = 0;
                    while (true)
                    {
                        IEnumerable <EventData> partition1Events = await partitionReceiver.ReceiveAsync(MaxBatchSize);

                        int receivedEventCount = partition1Events != null?partition1Events.Count() : 0;

                        TestUtility.Log($"Received {receivedEventCount} event(s)");

                        if (partition1Events == null)
                        {
                            break;
                        }

                        maxReceivedBatchSize = Math.Max(maxReceivedBatchSize, receivedEventCount);
                    }

                    Assert.True(maxReceivedBatchSize == MaxBatchSize, $"A max batch size of {MaxBatchSize} events was not honored! Actual {maxReceivedBatchSize}.");
                }
                finally
                {
                    await Task.WhenAll(
                        partitionReceiver.CloseAsync(),
                        partitionSender.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
Example #24
0
        public async Task CreateReceiverWithSequenceNumber()
        {
            var receiver = default(PartitionReceiver);

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

                try
                {
                    // Randomly pick one of the available partitons.
                    var partitions = await this.GetPartitionsAsync(ehClient);

                    var partitionId = partitions[new Random().Next(partitions.Length)];
                    TestUtility.Log($"Randomly picked partition {partitionId}");

                    // Send and receive a message to identify the end of stream.
                    var pInfo = await ehClient.GetPartitionRuntimeInformationAsync(partitionId);

                    // Send a new message which is expected to go to the end of stream.
                    // We are expecting to receive only this message.
                    var eventSent = new EventData(new byte[1]);
                    eventSent.Properties["stamp"] = Guid.NewGuid().ToString();
                    await ehClient.CreatePartitionSender(partitionId).SendAsync(eventSent);

                    // Create a new receiver which will start reading from the last message on the stream.
                    TestUtility.Log($"Creating a new receiver with sequence number {pInfo.LastEnqueuedSequenceNumber}");
                    receiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, partitionId, EventPosition.FromSequenceNumber(pInfo.LastEnqueuedSequenceNumber));
                    var receivedMessages = await receiver.ReceiveAsync(100);

                    // We should have received only 1 message from this call.
                    Assert.True(receivedMessages.Count() == 1, $"Didn't receive 1 message. Received {receivedMessages.Count()} messages(s).");

                    // Check stamp.
                    Assert.True(receivedMessages.Single().Properties["stamp"].ToString() == eventSent.Properties["stamp"].ToString()
                                , "Stamps didn't match on the message sent and received!");

                    TestUtility.Log("Received correct message as expected.");

                    // Next receive on this partition shouldn't return any more messages.
                    receivedMessages = await receiver.ReceiveAsync(100, TimeSpan.FromSeconds(15));

                    Assert.True(receivedMessages == null, $"Received messages at the end.");
                }
                finally
                {
                    await Task.WhenAll(
                        receiver.CloseAsync(),
                        ehClient.CloseAsync());
                }
            }
        }
Example #25
0
        /// <summary>
        ///   Performs the tasks needed to initialize and set up the environment for the test scenario.
        ///   When multiple instances are run in parallel, the setup will take place once, prior to the
        ///   execution of the first test instance.
        /// </summary>
        ///
        public async override Task GlobalSetupAsync()
        {
            await base.GlobalSetupAsync().ConfigureAwait(false);

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

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

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

            await s_client.SendAsync(new[] { new EventData(Array.Empty <byte>()) }).ConfigureAwait(false);
        }
Example #26
0
        public async Task Unregistering_plugin_should_complete_with_plugin_set()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                this.EventHubClient = EventHubClient.CreateFromConnectionString(connectionString);
                var firstPlugin = new SamplePlugin();

                this.EventHubClient.RegisterPlugin(firstPlugin);
                this.EventHubClient.UnregisterPlugin(firstPlugin.Name);
                await this.EventHubClient.CloseAsync();
            }
        }
        public async Task SendToInvalidPartition()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var             connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var             ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                PartitionSender sender           = null;

                try
                {
                    // Some invalid partition values.
                    var invalidPartitions = new List <string>()
                    {
                        "XYZ", "-1", "1000", "-"
                    };

                    foreach (var invalidPartitionId in invalidPartitions)
                    {
                        await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() =>
                        {
                            TestUtility.Log($"Sending to invalid partition {invalidPartitionId}");
                            sender = ehClient.CreatePartitionSender(invalidPartitionId);
                            await sender.SendAsync(new EventData(new byte[1]));
                        });

                        await sender.CloseAsync();
                    }

                    // Some other invalid partition values. These will fail on the client side.
                    invalidPartitions = new List <string>()
                    {
                        "", " ", null
                    };
                    foreach (var invalidPartitionId in invalidPartitions)
                    {
                        await Assert.ThrowsAsync <ArgumentNullException>(async() =>
                        {
                            TestUtility.Log($"Sending to invalid partition {invalidPartitionId}");
                            sender = ehClient.CreatePartitionSender(invalidPartitionId);
                            await sender.SendAsync(new EventData(new byte[1]));
                        });

                        await sender.CloseAsync();
                    }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }
Example #28
0
        public async Task ClosingReceiverEntity()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient         = EventHubClient.CreateFromConnectionString(connectionString);
                var ehReceiver       = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());

                await ehReceiver.CloseAsync();

                Assert.True(ehReceiver.IsClosed, "ehReceiver.IsClosed is not true.");
                Assert.True(!ehClient.IsClosed, "ehClient.IsClosed is not false.");
            }
        }
Example #29
0
        public async Task Registering_plugin_multiple_times_should_throw()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                this.EventHubClient = EventHubClient.CreateFromConnectionString(connectionString);
                var firstPlugin  = new SamplePlugin();
                var secondPlugin = new SamplePlugin();

                this.EventHubClient.RegisterPlugin(firstPlugin);
                Assert.Throws <ArgumentException>(() => EventHubClient.RegisterPlugin(secondPlugin));
                await EventHubClient.CloseAsync();
            }
        }
        public async Task ReceiveFromInvalidPartition()
        {
            await using (var scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString       = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);
                var ehClient               = EventHubClient.CreateFromConnectionString(connectionString);
                PartitionReceiver receiver = null;

                try
                {
                    // Some invalid partition values. These will fail on the service side.
                    var invalidPartitions = new List <string>()
                    {
                        "XYZ", "-1", "1000", "-"
                    };
                    foreach (var invalidPartitionId in invalidPartitions)
                    {
                        await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() =>
                        {
                            TestUtility.Log($"Receiving from invalid partition {invalidPartitionId}");
                            receiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, invalidPartitionId, EventPosition.FromStart());
                            await receiver.ReceiveAsync(1);
                        });

                        await receiver.CloseAsync();
                    }

                    // Some invalid partition values. These will fail on the client side.
                    invalidPartitions = new List <string>()
                    {
                        " ", null, ""
                    };
                    foreach (var invalidPartitionId in invalidPartitions)
                    {
                        await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                        {
                            TestUtility.Log($"Receiving from invalid partition {invalidPartitionId}");
                            receiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, invalidPartitionId, EventPosition.FromStart());
                            await receiver.ReceiveAsync(1);
                        });

                        await receiver.CloseAsync();
                    }
                }
                finally
                {
                    await ehClient.CloseAsync();
                }
            }
        }