Пример #1
0
        public async Task BasicQueueCrudOperations()
        {
            var queueName = nameof(BasicQueueCrudOperations).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8);
            var client    = CreateClient();

            var queueOptions = new CreateQueueOptions(queueName)
            {
                AutoDeleteOnIdle                    = TimeSpan.FromHours(1),
                DefaultMessageTimeToLive            = TimeSpan.FromDays(2),
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
                EnableBatchedOperations             = false,
                DeadLetteringOnMessageExpiration    = true,
                EnablePartitioning                  = false,
                ForwardDeadLetteredMessagesTo       = null,
                ForwardTo                  = null,
                LockDuration               = TimeSpan.FromSeconds(45),
                MaxDeliveryCount           = 8,
                MaxSizeInMegabytes         = 1024,
                RequiresDuplicateDetection = true,
                RequiresSession            = false,
                UserMetadata               = nameof(BasicQueueCrudOperations),
                Status = EntityStatus.Disabled
            };

            queueOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                                    "allClaims",
                                                    new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));

            Response <QueueProperties> createdQueueResponse = await client.CreateQueueAsync(queueOptions);

            Response rawResponse = createdQueueResponse.GetRawResponse();

            Assert.NotNull(rawResponse.ClientRequestId);
            Assert.IsTrue(rawResponse.ContentStream.CanRead);
            Assert.AreEqual(0, rawResponse.ContentStream.Position);

            QueueProperties createdQueue = createdQueueResponse.Value;

            if (Mode == RecordedTestMode.Playback)
            {
                Assert.AreEqual(queueOptions, new CreateQueueOptions(createdQueue)
                {
                    AuthorizationRules = queueOptions.AuthorizationRules.Clone()
                });
                Assert.AreEqual(createdQueue, new QueueProperties(queueOptions)
                {
                    AuthorizationRules = createdQueue.AuthorizationRules
                });
            }
            else
            {
                Assert.AreEqual(queueOptions, new CreateQueueOptions(createdQueue));
                Assert.AreEqual(createdQueue, new QueueProperties(queueOptions));
            }
            Response <QueueProperties> getQueueResponse = await client.GetQueueAsync(queueOptions.Name);

            rawResponse = createdQueueResponse.GetRawResponse();
            Assert.NotNull(rawResponse.ClientRequestId);
            Assert.IsTrue(rawResponse.ContentStream.CanRead);
            Assert.AreEqual(0, rawResponse.ContentStream.Position);

            QueueProperties getQueue = getQueueResponse.Value;

            Assert.AreEqual(createdQueue, getQueue);

            getQueue.EnableBatchedOperations = false;
            getQueue.MaxDeliveryCount        = 9;
            getQueue.AuthorizationRules.Clear();
            getQueue.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                                "noManage",
                                                new[] { AccessRights.Send, AccessRights.Listen }));
            getQueue.EnableBatchedOperations = true;
            getQueue.Status             = EntityStatus.Disabled;
            getQueue.AutoDeleteOnIdle   = TimeSpan.FromMinutes(6);
            getQueue.MaxSizeInMegabytes = 1024;
            QueueProperties updatedQueue = await client.UpdateQueueAsync(getQueue);

            if (Mode == RecordedTestMode.Playback)
            {
                // Auth rules use a randomly generated key, but we don't want to store
                // these in our test recordings, so we skip the auth rule comparison
                // when in playback mode.
                var rules = updatedQueue.AuthorizationRules;
                updatedQueue.AuthorizationRules = getQueue.AuthorizationRules.Clone();
                Assert.AreEqual(getQueue, updatedQueue);
                updatedQueue.AuthorizationRules = rules;
            }
            else
            {
                Assert.AreEqual(getQueue, updatedQueue);
            }
            Response <bool> isExistsResponse = await client.QueueExistsAsync(queueName);

            rawResponse = createdQueueResponse.GetRawResponse();

            Assert.NotNull(rawResponse.ClientRequestId);
            Assert.IsTrue(rawResponse.ContentStream.CanRead);
            Assert.AreEqual(0, rawResponse.ContentStream.Position);
            Assert.True(isExistsResponse.Value);

            List <QueueProperties> queueList = new List <QueueProperties>();

            await foreach (QueueProperties queue in client.GetQueuesAsync())
            {
                queueList.Add(queue);
            }

            queueList = queueList.Where(e => e.Name.StartsWith(nameof(BasicQueueCrudOperations).ToLower())).ToList();
            Assert.True(queueList.Count == 1, $"Expected 1 queue but {queueList.Count} queues returned");
            Assert.AreEqual(queueList.First().Name, queueName);

            await client.DeleteQueueAsync(updatedQueue.Name);

            Assert.That(
                async() =>
                await client.GetQueueAsync(queueOptions.Name),
                Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));

            isExistsResponse = await client.QueueExistsAsync(queueName);

            Assert.False(isExistsResponse.Value);
        }
Пример #2
0
        private static async Task SendComplexObjectMessageWithDuplicateDetection()
        {
            const string queueName = "sbq-complex-object-message-with-duplicate";

            var managementClient = new ServiceBusAdministrationClient(Config.Namespace, Config.Credential);

            var createQueueOptions = new CreateQueueOptions(queueName)
            {
                RequiresDuplicateDetection          = true,
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10)
            };

            if (!await managementClient.QueueExistsAsync(queueName))
            {
                await managementClient.CreateQueueAsync(createQueueOptions);
            }

            await using var client = new ServiceBusClient(Config.Namespace, Config.Credential);

            var sender = client.CreateSender(queueName);

            var payments = new List <Payment>
            {
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "132456789",
                    Amount        = 1337m,
                    PaymentDate   = DateTime.Today.AddDays(1),
                    Payee         = "Mr John Smith"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1576321357",
                    Amount        = 6984.56m,
                    PaymentDate   = DateTime.Today.AddDays(3),
                    Payee         = "Mrs Jane Doe"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1867817635",
                    Amount        = 13872m,
                    PaymentDate   = DateTime.Today,
                    Payee         = "Mr Robert Smith"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1779584565",
                    Amount        = 20000m,
                    PaymentDate   = DateTime.Today.AddDays(9),
                    Payee         = "Mrs James Doe"
                },
                new Payment
                {
                    PaymentId     = Guid.NewGuid(),
                    AccountNumber = "1657892587",
                    Amount        = 900000m,
                    PaymentDate   = DateTime.Today,
                    Payee         = "Mr William Tell"
                }
            };

            Console.WriteLine("Press any key to send all payment messages. Press Enter to exit.");

            while (Console.ReadKey(true).Key != ConsoleKey.Enter)
            {
                Console.WriteLine($"Total Payments to send: {payments.Count}");

                foreach (var payment in payments)
                {
                    var message = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(payment))
                    {
                        MessageId = payment.PaymentId.ToString() // Needed to detect duplicate messages
                    };

                    var random = new Random();

                    if (random.NextDouble() > 0.4) // Randomly simulate sending duplicate messages
                    {
                        await sender.SendMessageAsync(message);

                        Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessageWithDuplicateDetection)} - Payment ID: {payment.PaymentId}");
                    }
                    else
                    {
                        await sender.SendMessageAsync(message);

                        Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessageWithDuplicateDetection)} - Payment ID: {payment.PaymentId}");

                        await sender.SendMessageAsync(message);

                        Console.WriteLine($"Message Sent for {nameof(SendComplexObjectMessageWithDuplicateDetection)} - Payment ID: {payment.PaymentId}");
                    }
                }
            }

            Console.ReadLine();

            await managementClient.DeleteQueueAsync(queueName);
        }