Esempio n. 1
0
        static async Task SendMessage()
        {
            var message = new Message(Encoding.UTF8.GetBytes("Hi from service bus"));
            await queueClient.SendAsync(message);

            await queueClient.CloseAsync();
        }
        async Task SendAndReceiveWithWebSocketsTest()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                var tcs         = new TaskCompletionSource <Message>(TaskCreationOptions.RunContinuationsAsynchronously);
                var queueClient = new QueueClient(TestUtility.WebSocketsNamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete);

                try
                {
                    var random         = new Random();
                    var contentAsBytes = new byte[8];
                    random.NextBytes(contentAsBytes);

                    queueClient.RegisterMessageHandler((message, token) =>
                    {
                        tcs.TrySetResult(message);
                        return(Task.CompletedTask);
                    },
                                                       exceptionReceivedArgs =>
                    {
                        tcs.TrySetException(exceptionReceivedArgs.Exception);
                        return(Task.CompletedTask);
                    });

                    await queueClient.SendAsync(new Message(contentAsBytes));

                    var receivedMessage = await tcs.Task.WithTimeout(Timeout);
                    Assert.Equal(contentAsBytes, receivedMessage.Body);
                }
                finally
                {
                    await queueClient.CloseAsync();
                }
            });
        }
Esempio n. 3
0
        private async Task WriteQueueMessage(string connectionString, string queueName, string message)
        {
            QueueClient queueClient = new QueueClient(connectionString, queueName);
            await queueClient.SendAsync(new Message(Encoding.UTF8.GetBytes(message)));

            await queueClient.CloseAsync();
        }
        public static async Task WriteQueueMessage(string connectionString, string queueName, TestPoco obj, string sessionId = null)
        {
            var serializer = new DataContractSerializer(typeof(TestPoco));

            byte[] payload = null;
            using (var memoryStream = new MemoryStream(10))
            {
                var xmlDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(memoryStream, null, null, false);
                serializer.WriteObject(xmlDictionaryWriter, obj);
                xmlDictionaryWriter.Flush();
                memoryStream.Flush();
                memoryStream.Position = 0;
                payload = memoryStream.ToArray();
            }

            QueueClient queueClient = new QueueClient(connectionString, queueName);
            Message     messageObj  = new Message(payload);

            if (!string.IsNullOrEmpty(sessionId))
            {
                messageObj.SessionId = sessionId;
            }
            await queueClient.SendAsync(messageObj);

            await queueClient.CloseAsync();
        }
Esempio n. 5
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            string endpoint      = _settings.ServiceBusNamespace + ".servicebus.windows.net";
            string queueName     = _settings.ServiceBusQueueName;
            var    tokenProvider = new ManagedIdentityServiceBusTokenProvider(_settings.ManagedIdentityTenantId);
            var    queueClient   = new QueueClient(endpoint, queueName, tokenProvider, TransportType.Amqp, ReceiveMode.PeekLock);

            try
            {
                var messageHandlerOptions = new MessageHandlerOptions(HandleException)
                {
                    AutoComplete = true
                };
                queueClient.RegisterMessageHandler(HandleMessage, messageHandlerOptions);
                await Task.Delay(-1, cancellationToken);
            }
            catch (UnauthorizedException e)
            {
                // Log and exit
            }
            finally
            {
                await queueClient.CloseAsync();
            }
        }
Esempio n. 6
0
        public void SendMessageAsync(string message)
        {
            var sendMessage = new Message((Encoding.UTF8.GetBytes(message)));

            queueClient.SendAsync(sendMessage).Wait();
            queueClient.CloseAsync().Wait();
        }
        async Task DeadLetterFireEvents()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                this.queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock);
                await TestUtility.SendMessagesAsync(this.queueClient.InnerSender, 1);
                var messages = await TestUtility.ReceiveMessagesAsync(this.queueClient.InnerReceiver, 1);

                this.listener.Enable((name, queue, arg) => name.Contains("DeadLetter"));
                await TestUtility.DeadLetterMessagesAsync(this.queueClient.InnerReceiver, messages);
                this.listener.Disable();

                QueueClient deadLetterQueueClient = null;
                try
                {
                    deadLetterQueueClient = new QueueClient(TestUtility.NamespaceConnectionString,
                                                            EntityNameHelper.FormatDeadLetterPath(this.queueClient.QueueName), ReceiveMode.ReceiveAndDelete);
                    await TestUtility.ReceiveMessagesAsync(deadLetterQueueClient.InnerReceiver, 1);
                }
                finally
                {
                    deadLetterQueueClient?.CloseAsync().Wait(TimeSpan.FromSeconds(maxWaitSec));
                }

                Assert.True(this.events.TryDequeue(out var deadLetterStart));
                AssertDeadLetterStart(queueName, deadLetterStart.eventName, deadLetterStart.payload, deadLetterStart.activity, null);

                Assert.True(this.events.TryDequeue(out var deadLetterStop));
                AssertDeadLetterStop(queueName, deadLetterStop.eventName, deadLetterStop.payload, deadLetterStop.activity,
                                     deadLetterStart.activity);

                Assert.True(this.events.IsEmpty);
            });
        }
Esempio n. 8
0
        static async Task SendPizzaOrderListAsBatchAsync()
        {
            WriteLine("SendPizzaOrderListAsBatchAsync", ConsoleColor.Cyan);

            var pizzaOrderList = GetPizzaOrderList();
            var client         = new QueueClient(Settings.ConnectionString, Settings.QueueName);

            var watch       = Stopwatch.StartNew();
            var messageList = new List <Message>();

            foreach (var pizzaOrder in pizzaOrderList)
            {
                var jsonPizzaOrder = JsonConvert.SerializeObject(pizzaOrder);
                var message        = new Message(Encoding.UTF8.GetBytes(jsonPizzaOrder))
                {
                    Label       = "PizzaOrder",
                    ContentType = "application/json"
                };
                messageList.Add(message);
            }


            WriteLine("Sending...", ConsoleColor.Yellow);
            await client.SendAsync(messageList);

            // Always close the client!
            await client.CloseAsync();



            WriteLine($"Sent { pizzaOrderList.Count } orders! - Time: { watch.ElapsedMilliseconds } milliseconds, that's { pizzaOrderList.Count / watch.Elapsed.TotalSeconds } messages per second.", ConsoleColor.Green);
            Console.WriteLine();
            Console.WriteLine();
        }
Esempio n. 9
0
        async Task UpdatingPrefetchCountOnQueueClientUpdatesTheReceiverPrefetchCount()
        {
            string queueName   = TestConstants.NonPartitionedQueueName;
            var    queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete);

            try
            {
                Assert.Equal(0, queueClient.PrefetchCount);

                queueClient.PrefetchCount = 2;
                Assert.Equal(2, queueClient.PrefetchCount);

                // Message receiver should be created with latest prefetch count (lazy load).
                Assert.Equal(2, queueClient.InnerReceiver.PrefetchCount);

                queueClient.PrefetchCount = 3;
                Assert.Equal(3, queueClient.PrefetchCount);

                // Already created message receiver should have its prefetch value updated.
                Assert.Equal(3, queueClient.InnerReceiver.PrefetchCount);
            }
            finally
            {
                await queueClient.CloseAsync();
            }
        }
Esempio n. 10
0
 static async Task CloseQueueClient()
 {
     if (_queueClient != null && _queueClient.OwnsConnection)
     {
         await _queueClient.CloseAsync();
     }
 }
Esempio n. 11
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            // var azureServiceTokenProvider = new AzureServiceTokenProvider();
            //azureServiceTokenProvider.
            //string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
            //// OR
            //var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            try
            {
                var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
                var queueClient   = new QueueClient("sb://asb-msitest-asos3.servicebus.windows.net", "myqueue", tokenProvider, TransportType.Amqp);

                var message = new Message(Encoding.UTF8.GetBytes("My message"));
                await queueClient.SendAsync(message);

                await queueClient.CloseAsync();

                return((IActionResult) new OkObjectResult("Message sent"));
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString(), ex);
                return((IActionResult) new BadRequestObjectResult(ex.ToString()));
            }
        }
        static void Main(string[] args)
        {
            string sbConnectionString = "Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMj/4U21IBI=";
            string sbQueueName        = "Recharge";

            try
            {
                queueClient = new QueueClient(sbConnectionString, sbQueueName);

                var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentCalls = 1,
                    AutoComplete       = false
                };
                queueClient.RegisterMessageHandler(ReceiveMessagesAsync, messageHandlerOptions);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadKey();
                queueClient.CloseAsync();
            }
        }
Esempio n. 13
0
 private static async Task MainAsync()
 {
     queueClient = new QueueClient(serviceBusConnectionString, queueName);
     RegisterOnMessageHandlerAndReceiveMessages();
     Console.ReadKey();
     await queueClient.CloseAsync();
 }
Esempio n. 14
0
 public void Close()
 {
     if (_queueClient != null)
     {
         _queueClient.CloseAsync();
     }
 }
Esempio n. 15
0
        static async Task SendControlMessageAsync()
        {
            WriteLine("SendControlMessageAsync", ConsoleColor.Cyan);

            // Create a message with no body.
            var message = new Message()
            {
                Label = "Control"
            };

            // Add some properties to the property collection
            message.UserProperties.Add("SystemId", 1462);
            message.UserProperties.Add("Command", "Pending Restart");
            message.UserProperties.Add("ActionTime", DateTime.UtcNow.AddHours(2));

            // Send the message
            var client = new QueueClient(Settings.ConnectionString, Settings.QueueName);

            Write("Sending control message...", ConsoleColor.Green);
            await client.SendAsync(message);

            WriteLine("Done!", ConsoleColor.Green);
            Console.WriteLine();
            await client.CloseAsync();
        }
Esempio n. 16
0
        public async Task SendMessage(string connectionString, string queueName, AzureMessage message)
        {
            var client = new QueueClient(connectionString, queueName);
            await client.SendAsync(message);

            await client.CloseAsync();
        }
Esempio n. 17
0
        static async Task SendPizzaOrderAsync()
        {
            WriteLine("SendPizzaOrderAsync", ConsoleColor.Cyan);

            var order = new PizzaOrder()
            {
                CustomerName = "Alan Smith",
                Type         = "Hawaiian",
                Size         = "Large"
            };

            // Serialize the order object
            var jsonPizzaOrder = JsonConvert.SerializeObject(order);

            // Create a Message
            var message = new Message(Encoding.UTF8.GetBytes(jsonPizzaOrder))
            {
                Label       = "PizzaOrder",
                ContentType = "application/json"
            };


            // Send the message...
            var client = new QueueClient(Settings.ConnectionString, Settings.QueueName);

            Write("Sending order...", ConsoleColor.Green);
            await client.SendAsync(message);

            WriteLine("Done!", ConsoleColor.Green);
            Console.WriteLine();
            await client.CloseAsync();
        }
Esempio n. 18
0
            public async Task MessageWithMaxMessageSizeShouldWorkAsExpected()
            {
                var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, ReceiveMode.PeekLock);

                try
                {
                    var maxMessageSize = (256 * 1024) - 58;     // 58 bytes is the default serialization hit.
                    var maxPayload     = Encoding.ASCII.GetBytes(new string('a', maxMessageSize));
                    var maxSizeMessage = new Message(maxPayload);

                    await queueClient.SendAsync(maxSizeMessage);

                    var receivedMaxSizeMessage = await queueClient.InnerReceiver.ReceiveAsync();

                    await queueClient.CompleteAsync(receivedMaxSizeMessage.SystemProperties.LockToken);

                    Assert.Equal(maxPayload, receivedMaxSizeMessage.Body);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                finally
                {
                    await queueClient.CloseAsync();
                }
            }
Esempio n. 19
0
        static async Task SendTextStringAsMessagesAsync(string text)
        {
            WriteLine("SendTextStringAsMessagesAsync", ConsoleColor.Cyan);

            // Create a client
            var client = new QueueClient(Settings.ConnectionString, Settings.QueueName);

            Write("Sending:", ConsoleColor.Green);


            foreach (var letter in text.ToCharArray())
            {
                // Create an empty message and set the label.
                var message = new Message();
                message.Label = letter.ToString();


                // Send the message
                await client.SendAsync(message);

                Write(message.Label, ConsoleColor.Green);
            }


            Console.WriteLine();
            Console.WriteLine();

            // Always close the client
            await client.CloseAsync();
        }
Esempio n. 20
0
        public static async Task Main()
        {
            Random   random   = new Random();
            Customer customer = new Customer();

            string[] first_name = { "Liam", "Emma", "Adler", "Anderson", "Beckett", "Brady", "Carson", "Carter" };
            string[] city       = { "Campbell", "Orchard Park", "Fairport", "Buffalo", "Monroe", "Port Washington", "Monsey" };
            string[] state      = { "NY", "CA", "TX" };
            try
            {
                IQueueClient queueClient = new QueueClient(connectionString, "customers");
                for (int i = 1; i > 0; i++)
                {
                    customer.first_name = first_name[random.Next(0, 8)];
                    customer.last_name  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random.Next(0, 25)].ToString();
                    customer.phone      = "9" + random.Next(000000000, 999999999);
                    customer.email      = "abcdefghijklmnopqrstuvwxyz"[random.Next(0, 25)].ToString() + "abcdefghijklmnopqrstuvwxyz"[random.Next(0, 25)].ToString() + "abcdefghijklmnopqrstuvwxyz"[random.Next(0, 25)].ToString() + "@gmail.com";
                    customer.street     = "#Site " + random.Next(2, 100) + "," + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[random.Next(0, 30)].ToString() + " Block," + random.Next(1, 20) + " Sector";
                    customer.city       = city[random.Next(0, 6)];
                    customer.state      = state[random.Next(0, 2)];
                    customer.zip_code   = "" + random.Next(10000, 99999);
                    Message message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(customer)));
                    await queueClient.SendAsync(message);

                    System.Threading.Thread.Sleep(2000);
                }
                await queueClient.CloseAsync();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception : " + exception.Message);
            }
        }
Esempio n. 21
0
        public async Task SendMessagesAsync(IList <string> messages)
        {
            QueueClient client = null;

            try
            {
                foreach (var message in messages)
                {
                    await _client.SendAsync(new Message(Encoding.UTF8.GetBytes(message)));

                    _logger.Information($"[Message sent]: {message}");
                }

                _logger.Information("Finished sending messages");
            }
            catch (Exception ex)
            {
                _logger.Error($"Exception: {ex.GetType().FullName} | " +
                              $"Message: {ex.Message}");
            }
            finally
            {
                if (client is not null)
                {
                    await client.CloseAsync();

                    _logger.Information("Azure Service Bus closed!");
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Send message to queue in Service Bus.
        /// </summary>
        /// <param name="connectionString">The connection string of Service Bus.</param>
        /// <param name="queueName">The name of a queue in Service Bus.</param>
        /// <param name="jsonData">The JSON string of a message.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task SendMessagesAsync(string connectionString, string queueName, string jsonData)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException(MessageConstants.NullOrEmptyMessage, nameof(connectionString));
            }

            if (string.IsNullOrEmpty(queueName))
            {
                throw new ArgumentException(MessageConstants.NullOrEmptyMessage, nameof(queueName));
            }

            if (string.IsNullOrEmpty(jsonData))
            {
                throw new ArgumentException(MessageConstants.NullOrEmptyMessage, nameof(jsonData));
            }

            var    sender = new QueueClient(connectionString, queueName);;// new MessageSender(connectionString, queueName);
            string label  = MessageConstants.BuildMessageLabel;


            var message = new Message(Encoding.UTF8.GetBytes(jsonData))
            {
                ContentType = MessageConstants.ContentType,
                Label       = label,
                MessageId   = Guid.NewGuid().ToString(),
                TimeToLive  = TimeSpan.FromMinutes(100),
            };

            await sender.SendAsync(message);

            // close the connection.
            await sender.CloseAsync();
        }
        public static async Task <string> Run([ActivityTrigger] ServiceBusJobProperties sbJobProperties, TraceWriter log)
        {
            QueueClient queueClient = new QueueClient(sbJobProperties.ConnectionString, sbJobProperties.Queue);

            int secondsPerBatch           = Convert.ToInt16(Environment.GetEnvironmentVariable("secondsPerBatch"));
            int messagesInBatch           = sbJobProperties.Frequency * secondsPerBatch;
            IEnumerable <string> messages = Messages.CreateMessages(messagesInBatch, sbJobProperties.MessageScheme);

            try
            {
                var sbMessages = (List <Message>)messages.Select(m => new Message()
                {
                    Body        = Encoding.UTF8.GetBytes(m),
                    ContentType = "text/plain"
                }
                                                                 );

                await queueClient.SendAsync(sbMessages);

                await queueClient.CloseAsync();
            }
            catch (Exception exception)
            {
                log.Info($"Exception: {exception.Message}");
            }

            log.Info($"sent batch of {messages.Count()} messages");
            return($"finished sending {messages.Count()} to {sbJobProperties.Queue}!");
        }
        public async static Task EnqueueMessageAsync(String connectionString, String queueName, Object data)
        {
            // Prepare the queue variable
            QueueClient queueClient = null;

            try
            {
                // Open the queue
                queueClient = new QueueClient(connectionString, queueName);

                // Prepare the message
                var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)));

                // Send the message to the queue.
                await queueClient.SendAsync(message);
            }
            finally
            {
                // Release the queue in case of need
                if (queueClient != null && !queueClient.IsClosedOrClosing)
                {
                    // Close the queue
                    await queueClient.CloseAsync();
                }
            }
        }
Esempio n. 25
0
        public override async Task JobTask()
        {
            var _serviceBus = new QueueClient(ConfigurationManager.AppSettings["AzureSBConnString"], ConfigurationManager.AppSettings["AzureSBQueueName"]);
            await _serviceBus.SendAsync(new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new GenericMessage(MessageCategory.DominanceTracker, "Updated")))));

            await _serviceBus.CloseAsync();
        }
        async Task OnSessionTestAsync(string queueName, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete)
        {
            TestUtility.Log($"Queue: {queueName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}");
            var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, mode);

            try
            {
                SessionHandlerOptions handlerOptions =
                    new SessionHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentSessions = maxConcurrentCalls,
                    MessageWaitTimeout    = TimeSpan.FromSeconds(5),
                    AutoComplete          = autoComplete
                };

                TestSessionHandler testSessionHandler = new TestSessionHandler(
                    queueClient.ReceiveMode,
                    handlerOptions,
                    queueClient.InnerSender,
                    queueClient.SessionPumpHost);

                // Send messages to Session first
                await testSessionHandler.SendSessionMessages();

                // Register handler
                testSessionHandler.RegisterSessionHandler(handlerOptions);

                // Verify messages were received.
                await testSessionHandler.VerifyRun();
            }
            finally
            {
                await queueClient.CloseAsync();
            }
        }
        public async Task SendMessagesAsync(string messageToSend, string sessionId)
        {
            try
            {
                var queueClient = new QueueClient(ServiceBusConnectionString, QueueName);


                var message = new Message(Encoding.UTF8.GetBytes(messageToSend));
                message.SessionId = sessionId;


                // Write the body of the message to the console.
                Console.WriteLine($"Sending message: {messageToSend}");

                // Send the message to the queue.
                await queueClient.SendAsync(message);

                await queueClient.CloseAsync();
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
                throw;
            }
        }
Esempio n. 28
0
        static async Task Init()
        {
            List <Message> messages = new List <Message>();
            Random         rand     = new Random();

            Console.WriteLine("[*].......Preparing messages");
            for (int i = 1; i <= 5; i++)
            {
                var trxDetail = new TransactionDetail
                {
                    Id                  = Guid.NewGuid(),
                    AccountName         = $"Acc-{rand.Next(1000, 10000)}-{rand.Next(1000, 10000)}-{rand.Next(1000, 10000)}-{rand.Next(1000, 10000)}",
                    AccountNumber       = Guid.NewGuid().ToString(),
                    Amount              = rand.Next(1000, 100000),
                    TargetAccountNumber = $"Acc-{rand.Next(1000, 10000)}-{rand.Next(1000, 10000)}-{rand.Next(1000, 10000)}-{rand.Next(1000, 10000)}",
                    TransactionDate     = DateTime.Now
                };
                byte[] serializedBytes = Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(trxDetail)
                    );

                Message message = new Message(serializedBytes)
                {
                    MessageId = trxDetail.Id.ToString()
                };
                messages.Add(message);
            }
            Console.WriteLine("[*].......Sending messages");
            await _queueClient.SendAsync(messages);

            Console.WriteLine("[*].......Messages sent");
            Console.ReadLine();
            await _queueClient.CloseAsync();
        }
Esempio n. 29
0
        public void Send(string recieverQueue, Message message)
        {
            IQueueClient queueClient = new QueueClient(config.GetConnectionString("AzureServiceBus"), recieverQueue);

            queueClient.SendAsync(message);
            queueClient.CloseAsync();
        }
Esempio n. 30
0
        public static async Task <IActionResult> HandleStatusChange(StateChange data)
        {
            Console.WriteLine(data);
            try
            {
                var res = await Client.GetTransferByIdAsync(data.Resource.Id);

                Console.WriteLine(res);

                var msg = new Notification {
                    Amount = res.SourceValue
                };

                var sb = new QueueClient(Env.EmailBusConnectionString, Env.EmailBusName);

                await sb.SendAsync(new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg))));

                await sb.CloseAsync();

                return(new OkResult());
            }
            catch (ApiException e)
            {
                Debug.Print("Exception when calling DefaultApi.GetTransferById: " + e.Message);
                Debug.Print("Status Code: " + e.ErrorCode);
                Debug.Print(e.StackTrace);
                return(new OkResult());
            }
        }