예제 #1
0
파일: MqManager.cs 프로젝트: IcyExile/CRQ
 public IMessageSender GetMessageSender(QueueProperties properties)
 {
     return new MessageSender
     {
         Properties = properties
     };
 }
예제 #2
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);
        }
예제 #3
0
        public async Task GetQueueRuntimeInfo()
        {
            var queueName  = nameof(GetQueueRuntimeInfo).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8);
            var mgmtClient = CreateClient();

            await using var sbClient = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);

            QueueProperties queue = await mgmtClient.CreateQueueAsync(queueName);

            queue = await mgmtClient.GetQueueAsync(queueName);

            // Changing Last Updated Time
            queue.AutoDeleteOnIdle = TimeSpan.FromMinutes(100);
            QueueProperties updatedQueue = await mgmtClient.UpdateQueueAsync(queue);

            // Populating 1 active message, 1 dead letter message and 1 scheduled message
            // Changing Last Accessed Time

            ServiceBusSender sender = sbClient.CreateSender(queueName);
            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "1"
            });

            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "2"
            });

            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "3", ScheduledEnqueueTime = DateTime.UtcNow.AddDays(1)
            });

            ServiceBusReceiver        receiver = sbClient.CreateReceiver(queueName);
            ServiceBusReceivedMessage msg      = await receiver.ReceiveMessageAsync();

            await receiver.DeadLetterMessageAsync(msg);

            List <QueueRuntimeProperties> runtimeInfoList = new List <QueueRuntimeProperties>();

            await foreach (QueueRuntimeProperties queueRuntimeInfo in mgmtClient.GetQueuesRuntimePropertiesAsync())
            {
                runtimeInfoList.Add(queueRuntimeInfo);
            }
            runtimeInfoList = runtimeInfoList.Where(e => e.Name.StartsWith(nameof(GetQueueRuntimeInfo).ToLower())).ToList();
            Assert.True(runtimeInfoList.Count == 1, $"Expected 1 queue but {runtimeInfoList.Count} queues returned");
            QueueRuntimeProperties runtimeInfo = runtimeInfoList.First();

            Assert.NotNull(runtimeInfo);

            Assert.AreEqual(queueName, runtimeInfo.Name);
            Assert.True(runtimeInfo.CreatedAt < runtimeInfo.UpdatedAt);
            Assert.True(runtimeInfo.UpdatedAt < runtimeInfo.AccessedAt);
            Assert.AreEqual(1, runtimeInfo.ActiveMessageCount);
            Assert.AreEqual(1, runtimeInfo.DeadLetterMessageCount);
            Assert.AreEqual(1, runtimeInfo.ScheduledMessageCount);
            Assert.AreEqual(3, runtimeInfo.TotalMessageCount);
            Assert.True(runtimeInfo.SizeInBytes > 0);

            QueueRuntimeProperties singleRuntimeInfo = await mgmtClient.GetQueueRuntimePropertiesAsync(runtimeInfo.Name);

            Assert.AreEqual(runtimeInfo.AccessedAt, singleRuntimeInfo.AccessedAt);
            Assert.AreEqual(runtimeInfo.CreatedAt, singleRuntimeInfo.CreatedAt);
            Assert.AreEqual(runtimeInfo.UpdatedAt, singleRuntimeInfo.UpdatedAt);
            Assert.AreEqual(runtimeInfo.TotalMessageCount, singleRuntimeInfo.TotalMessageCount);
            Assert.AreEqual(runtimeInfo.ActiveMessageCount, singleRuntimeInfo.ActiveMessageCount);
            Assert.AreEqual(runtimeInfo.DeadLetterMessageCount, singleRuntimeInfo.DeadLetterMessageCount);
            Assert.AreEqual(runtimeInfo.ScheduledMessageCount, singleRuntimeInfo.ScheduledMessageCount);
            Assert.AreEqual(runtimeInfo.SizeInBytes, singleRuntimeInfo.SizeInBytes);

            await mgmtClient.DeleteQueueAsync(queueName);
        }
예제 #4
0
 private QueueScope(ServiceBusAdministrationClient adminClient, string queueName, QueueProperties properties)
 {
     _adminClient = adminClient;
     QueueName    = queueName;
     _properties  = properties;
 }
예제 #5
0
        public object Deserialize(QueueProperties queueProps, Type type, byte[] data)
        {
            var deserializer = GetOrCreateDynamic(type);

            return(AsyncHelper.RunSync(async() => await deserializer.DeserializeAsync(queueProps.QueueName, data)));
        }
예제 #6
0
파일: QueueAgent.cs 프로젝트: nistec/MQueue
 /// <summary>
 /// ctor.
 /// </summary>
 /// <param name="prop"></param>
 public QueueAgent(QueueProperties prop)
     : base(prop)
 {
     m_Perform = new QueuePerformanceCounter(this, QueueAgentType.Queue, this.QueueName);
 }
예제 #7
0
        public async Task BasicQueueCrudOperations()
        {
            var queueName = nameof(BasicQueueCrudOperations).ToLower() + Guid.NewGuid().ToString("D").Substring(0, 8);
            var client    = new ServiceBusManagementClient(TestEnvironment.ServiceBusConnectionString);

            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         = 2048,
                RequiresDuplicateDetection = true,
                RequiresSession            = false,
                UserMetadata               = nameof(BasicQueueCrudOperations),
                Status = EntityStatus.Disabled
            };

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

            QueueProperties createdQueue = await client.CreateQueueAsync(queueOptions);

            Assert.AreEqual(queueOptions, new CreateQueueOptions(createdQueue));

            QueueProperties getQueue = await client.GetQueueAsync(queueOptions.Name);

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

            Assert.AreEqual(getQueue, updatedQueue);
            bool isExists = await client.QueueExistsAsync(queueName);

            Assert.True(isExists);

            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(ServiceBusException.FailureReason.MessagingEntityNotFound));

            isExists = await client.QueueExistsAsync(queueName);

            Assert.False(isExists);
        }
 public object Deserialize(QueueProperties queueProps, Type type, byte[] data)
 {
     using (var stream = new MemoryStream(data))
         using (var reader = new StreamReader(stream, Encoding.UTF8))
             return(_serializer.Deserialize(reader, type));
 }
예제 #9
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            #region Creating Objects
            QueueProperties queue = await ServiceBusObjects.GetQueueAsync(ConnectionString, QueueName);

            if (queue == null)
            {
                queue = await ServiceBusObjects.CreateQueueAsync(ConnectionString, QueueName);
            }

            QueueProperties sessionQueue = await ServiceBusObjects.GetQueueAsync(ConnectionString, SessionQueueName);

            if (sessionQueue == null)
            {
                sessionQueue = await ServiceBusObjects.CreateQueueAsync(ConnectionString, SessionQueueName, true);
            }

            TopicProperties topic = await ServiceBusObjects.GetTopicAsync(TopicName, ConnectionString);

            if (topic == null)
            {
                topic = await ServiceBusObjects.CreateTopicAsync(TopicName, ConnectionString);
            }

            SubscriptionProperties subscription = await ServiceBusObjects.GetSubscriptionAsync(TopicName, ConnectionString, SubscriptionName);

            if (subscription == null)
            {
                subscription = await ServiceBusObjects.CreateSubscriptionAsync(TopicName, ConnectionString, SubscriptionName);
            }

            #endregion

            #region Sending and Receiving Messages
            int count = 0;

            //sending messages
            await SendAndReceiveMessage.SendMessageAsync(ConnectionString, QueueName, $"Message {count++}");

            await SendAndReceiveMessage.SendMessageBatchAsync(ConnectionString, QueueName, new System.Collections.Generic.List <string> {
                $"Message {count++}", $"Message {count++}", $"Message {count++}", $"Message {count++}"
            });

            await SendAndReceiveMessage.SendMessageSafeBatchAsync(ConnectionString, QueueName, new System.Collections.Generic.List <string> {
                $"Message {count++}", $"Message {count++}", $"Message {count++}", $"Message {count++}"
            });

            long firstScheduledMessageNumber = await SendAndReceiveMessage.SendScheduledMessageAsync(ConnectionString, QueueName, $"Message {count++}", new DateTimeOffset(DateTime.Now.AddMinutes(10)));

            long secondScheduledMessageNumber = await SendAndReceiveMessage.SendScheduledMessageAsync(ConnectionString, QueueName, $"Message {count++}", new DateTimeOffset(DateTime.Now.AddMinutes(10)));

            await SendAndReceiveMessage.CancelScheduledMessageAsync(ConnectionString, QueueName, firstScheduledMessageNumber);

            long deferredMessageNumber = await SendAndReceiveMessage.DeferMessageAsync(ConnectionString, QueueName);

            Console.WriteLine((await SendAndReceiveMessage.GetDeferredMessageAsync(ConnectionString, QueueName, deferredMessageNumber)).Body);
            await SendAndReceiveMessage.DeadLetterMessageAsync(ConnectionString, QueueName);

            Console.WriteLine((await SendAndReceiveMessage.GetDeadLetterMessageAsync(ConnectionString, QueueName)).Body);
            Console.WriteLine((await SendAndReceiveMessage.GetMessageAsync(ConnectionString, QueueName)).Body);
            await SendAndReceiveMessage.CompleteOrAbandonMessageAsync(ConnectionString, QueueName, false);

            await SendAndReceiveMessage.CompleteOrAbandonMessageAsync(ConnectionString, QueueName, true);

            #endregion

            #region Sending and Receiving Session Messages
            await SendAndReceiveMessage.SendSessionMessageAsync(ConnectionString, SessionQueueName, $"Message {count++}", "session id 1");

            Console.WriteLine((await SendAndReceiveMessage.GetMessageFromSessionAsync(ConnectionString, SessionQueueName, "session id 1")).Body);
            #endregion

            #region Messages Processor
            await Processor.RunProcessor(ConnectionString, QueueName, new TimeSpan(0, 0, 10));

            #endregion

            #region Session Processor
            await SessionProcessor.RunSessionProcessor(ConnectionString, SessionQueueName, new TimeSpan(0, 0, 10));

            #endregion
        }
예제 #10
0
        public static async Task <QueueProperties> UpdateQueueAsync(string connectionString, QueueProperties queue)
        {
            var client = new ServiceBusAdministrationClient(connectionString);

            queue.UserMetadata = "other metadata";
            return(await client.UpdateQueueAsync(queue));
        }
예제 #11
0
        internal static void RunSamples()
        {
            StorageAccountInfo account = null;

            try
            {
                string sampleGuid = (Guid.NewGuid()).ToString("N");
                string name       = "queue" + sampleGuid;
                string name2      = "queue2" + sampleGuid;
                string prefix     = "prefix" + sampleGuid;
                bool   exists     = false;
                bool   res        = false;

                Console.WriteLine("Create queue " + name);
                account = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
                QueueStorage queueService = QueueStorage.Create(account);
                queueService.RetryPolicy = RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100));
                MessageQueue q = queueService.GetQueue(name);
                res = q.CreateQueue(out exists);
                if (!exists && res)
                {
                    Console.WriteLine("Queue " + name + " successfully created.");
                }

                Console.WriteLine("Get all the queues in an account.");
                IEnumerable <MessageQueue> queues = queueService.ListQueues();
                foreach (MessageQueue qu in queues)
                {
                    Console.WriteLine(qu.Name);
                }

                Console.WriteLine("Create a number of queues and show continuation listing. This can take a while...");
                int numListSample = 60;
                for (int j = 0; j < numListSample; j++)
                {
                    q = queueService.GetQueue(prefix + (Guid.NewGuid()).ToString("N").Substring(0, 10));
                    q.CreateQueue();
                }
                queues = queueService.ListQueues();
                List <MessageQueue> l = new List <MessageQueue>(queues);
                Console.WriteLine("The following queues are available:");
                foreach (MessageQueue qu in l)
                {
                    Console.WriteLine(qu.Name);
                }

                Console.WriteLine("Find all queues with a given prefix...");
                queues = queueService.ListQueues(prefix);
                l      = new List <MessageQueue>(queues);
                Console.WriteLine("Queues with the prefix " + prefix);
                foreach (MessageQueue qu in l)
                {
                    Console.WriteLine(qu.Name);
                }

                Console.WriteLine("Delete all queues with the prefix " + prefix);
                foreach (MessageQueue qu in queues)
                {
                    Console.WriteLine("Delete queue" + qu.Name);
                    qu.Clear();
                    qu.DeleteQueue();
                }

                q = queueService.GetQueue(name);
                if (!q.DoesQueueExist())
                {
                    Console.WriteLine("Queue '{0}' does not exist");
                }

                Console.WriteLine("Delete queue " + name);
                q.Clear();
                q.DeleteQueue();

                Console.WriteLine("Get queue properties.");
                q   = queueService.GetQueue(name2);
                res = q.CreateQueue(out exists);
                if (!exists && res)
                {
                    Console.WriteLine("Queue " + name + " successfully created.");
                }
                QueueProperties props = new QueueProperties();
                props          = q.GetProperties();
                props.Metadata = new NameValueCollection();
                props.Metadata.Add("meta-sample1", "sample1");
                props.Metadata.Add("meta-sample2", "sample2");
                q.SetProperties(props);
                props = null;
                props = q.GetProperties();
                Console.WriteLine("Queue properties: " + props.Metadata["meta-sample1"] + " " + props.Metadata["meta-sample2"]);

                Console.WriteLine("Put message into the queue.");
                if (q.PutMessage(new Message("<sample>sample message</sample>")))
                {
                    Console.WriteLine("Message successfully put into queue.");
                }
                Console.WriteLine("Get message from the queue.");
                Message msg = q.GetMessage();
                Console.WriteLine(msg.ContentAsString());

                Console.WriteLine("Clear all messages from a queue.");
                for (int i = 0; i < 10; i++)
                {
                    q.PutMessage(new Message("<sample>" + i + "</sample>"));
                }
                q.Clear();

                Console.WriteLine("Delete a single message.");
                for (int i = 0; i < 10; i++)
                {
                    q.PutMessage(new Message("<sample>" + i + "</sample>"));
                }
                Message msg1 = q.GetMessage();
                q.DeleteMessage(msg1);
                q.Clear();

                Console.WriteLine("Automatic reception of messages.");
                q.MessageReceived += MessageReceived;
                q.PollInterval     = 500;
                q.StartReceiving();
                for (int i = 0; i < 10; i++)
                {
                    q.PutMessage(new Message("<samplemessage>" + i + "</samplemessage>"));
                    System.Threading.Thread.Sleep(1000);
                }
                q.StopReceiving();
                q.Clear();
                q.DeleteQueue();

                Console.WriteLine("Queue samples finished successfully.");
            }
            catch (System.Net.WebException we)
            {
                Console.WriteLine("Network error: " + we.Message);
                if (we.Status == System.Net.WebExceptionStatus.ConnectFailure)
                {
                    Console.WriteLine("Please check if the queue storage service is running at " + account.BaseUri.ToString());
                    Console.WriteLine("Detailed information on how to run the development storage tool " +
                                      "locally can be found in the readme file that comes with this sample.");
                }
            }
            catch (StorageException se)
            {
                Console.WriteLine("Storage service error: " + se.Message);
            }
        }