Esempio n. 1
0
        static void Main(string[] args)
        {
            string sbConnectionString = "Endpoint=sb://miniproject.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=tGkzmzkJl5PqEBSAQxiWA92Dt0wV9HSBOh7QS6k4OGo=";
            string sbQueName          = "recharge";

            try
            {
                queueClient = new Microsoft.Azure.ServiceBus.QueueClient(sbConnectionString, sbQueName);


                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. 2
0
        public static void Run([QueueTrigger("myqueue-items", Connection = "quequeconnection")] string myQueueItem, ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
            dynamic json = JsonConvert.DeserializeObject <Sample>(myQueueItem);
            int     id;



            //Int32.TryParse(json.id, out id);
            //Shardinghelper obj = new Shardinghelper();
            //obj.AddShard(id);


            const string connectionString = "Endpoint=sb://servicebus347.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=5tDP6HC7kthwV7+bOzdhE+PxRERAHu0AmleGJxgK2lU=";


            const string queueName = "myqueue-items";
            ServiceBusConnectionStringBuilder objconnection = new ServiceBusConnectionStringBuilder(connectionString);
            var _client = new Microsoft.Azure.ServiceBus.QueueClient(connectionString, queueName);

            string Message = "I'm in Azure Service Bus Queue";

            Microsoft.Azure.ServiceBus.Message message = new Microsoft.Azure.ServiceBus.Message(Encoding.UTF8.GetBytes(Message));
            _client.SendAsync(message);
        }
Esempio n. 3
0
        public async Task SendAsync <TMessage>(TMessage message) where TMessage : IBusQueueMessage
        {
            var client = new Microsoft.Azure.ServiceBus.QueueClient(new ServiceBusConnectionStringBuilder(_connectionString)
            {
                EntityPath = message.QueueName
            });

            var serviceBusMessage = _messageFactory.CreateMessage(message);

            await client.SendAsync(serviceBusMessage);

            await client.CloseAsync();
        }
        public async Task UpdateStockAsync(ProductInStockUpdateStockCommand command)
        {
            var queueClient = new Microsoft.Azure.ServiceBus.QueueClient(_connectionString, "order-stock-update");

            // Serialize message
            string body    = JsonSerializer.Serialize(command);
            var    message = new Message(Encoding.UTF8.GetBytes(body));

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

            // Close
            await queueClient.CloseAsync();
        }
Esempio n. 5
0
        /// <inheritdoc />
        public async Task SendAsync <TMessage>(TMessage message) where TMessage : IBusQueueMessage
        {
            if (string.IsNullOrEmpty(message.QueueName))
            {
                throw new ApplicationException("Queue name is mandatory");
            }

            var client = new Microsoft.Azure.ServiceBus.QueueClient(new ServiceBusConnectionStringBuilder(_connectionString)
            {
                EntityPath = message.QueueName
            });

            var serviceBusMessage = _messageFactory.CreateMessage(message);

            await client.SendAsync(serviceBusMessage);

            await client.CloseAsync();
        }
Esempio n. 6
0
        public static async Task Run([ServiceBusTrigger("paymentprocessedtopic", "UpdateOrder", AccessRights.Listen,
                                                        Connection = "ServiceBusConnectionString")] string topicMessage, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrEmpty(topicMessage))
                {
                    throw new Exception("ServiceBus topic message is null or empty.");
                }

                var order = JsonConvert.DeserializeObject <Order>(topicMessage);
                order.UpdatedDate = DateTime.UtcNow;

                await UpdateOrderStatus(order);

                if (order.RequiresResponse)
                {
                    var orderResponse = new OrderResponse()
                    {
                        OrderId = order.Id,
                        Status  = order.Status
                    };

                    var message = new Message();
                    message.Body      = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(orderResponse));
                    message.MessageId = Guid.NewGuid().ToString();
                    message.SessionId = order.Id.ToString();

                    var queueClient = new Microsoft.Azure.ServiceBus.QueueClient(Environment.GetEnvironmentVariable("ServiceBusConnectionString"), order.Id.ToString());
                    await queueClient.SendAsync(message);
                }
            }
            catch (Exception ex)
            {
                log.Error($"UpdateOrderPaymentProcessed function failed. Exception: {ex.Message}");
            }

            log.Info($"UpdateOrderPaymentProcessed function finished execution: {topicMessage}");
        }
Esempio n. 7
0
        public static async Task GenerateForecastServiceBusActivity([ActivityTrigger] string details)
        {
            // Deserialize the forecast details so that we can determine which partion
            // key and queue to work with.
            var messageDetails = JsonConvert.DeserializeObject <ForecastMessageDetails>(details);

            // Get a reference to the table that will contain all the coordinates.
            var storageAccount = CloudStorageAccount.Parse(StorageConnectionString);
            var tableClient    = storageAccount.CreateCloudTableClient();
            var table          = tableClient.GetTableReference("datapoints");
            await table.CreateIfNotExistsAsync();

            // Get a reference to the service bus queue that we will send the messages to.
            var queueClient = new Microsoft.Azure.ServiceBus.QueueClient(ServiceBusConnectionString, messageDetails.QueueName);

            // Get the coordinates from the table and add each one as a separate message
            // to the service bus queue.
            var coordinates = await GetCoordinatesFromStorage(messageDetails.PartitionKey, table);

            var messagesToSend = new List <Message>();

            foreach (var c in coordinates)
            {
                var forecastRequest = new List <Coordinates> {
                    new Coordinates {
                        Latitude = c.Latitude, Longitude = c.Longitude
                    }
                };
                var serializedMessage = JsonConvert.SerializeObject(forecastRequest);
                var message           = new Message(Encoding.UTF8.GetBytes(serializedMessage));
                messagesToSend.Add(message);
            }

            // Service bus allows you to add messages in a batch.
            await queueClient.SendAsync(messagesToSend);
        }
Esempio n. 8
0
        //--- 1
        public QueueWriter(IQueueConfig queueConfig)
        {
            #region AzureServiceBusAMQP CreateConnection
            /// <summary>
            /// Attempt to connect with a valid connection string
            /// </summary>

            /// <param name="UserName">AppSettings.Get("mq.user")</param>
            /// <param name="Password">AppSettings.Get("mq.pass")</param>
            /// <param name="RequestedHeartbeat">30</param>
            /// <param name="Handle<BrokerUnreachableException>()"></param>
            /// <param name="Retry(tries)">5</param>
            /// <returns></returns>

            try
            {
                connectionString = queueConfig.PrimaryConnectionString;
                password         = queueConfig.Password;
                userName         = queueConfig.UserName;



                queueName    = queueConfig.QueueName;
                queueNameNew = queueConfig.QueueNameNew;
                queueNameDel = queueConfig.QueueNameDel;


                Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", userName, string.Empty);

                // Create management credentials
                //---TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasKeyName, sasKeyValue);
                //---Microsoft.ServiceBus.TokenProvider tokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider(nameKey, password);
                Microsoft.ServiceBus.TokenProvider credentials   = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", password);
                Microsoft.ServiceBus.TokenProvider tokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", password);
                NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider);

                // Create if not exists new one
                if (namespaceManager.QueueExists(queueName))
                {
                    queueClient = new Microsoft.Azure.ServiceBus.QueueClient(connectionString, queueName, Microsoft.Azure.ServiceBus.ReceiveMode.PeekLock);
                    Debug.WriteLine($"{DateTime.Now.TimeOfDay} : Queue opened successfully.", queueConfig.QueueName);

                    //IQueueClient queueClient = new Microsoft.Azure.ServiceBus.QueueClient(connectionString, queueConfig.QueueName, Microsoft.Azure.ServiceBus.ReceiveMode.PeekLock);
                    //Debug.WriteLine(" Queue opened successfully.", queueConfig.QueueName);
                }
                else
                {
                    //namespaceManager.CreateQueue(queueNameNew);
                    // Configure queue settings.

                    var queueDescription = new QueueDescription(queueNameNew);
                    queueDescription.MaxSizeInMegabytes = 1024;
                    // Setting message TTL to 7 days where as default TTL is 14 days.
                    queueDescription.DefaultMessageTimeToLive = TimeSpan.FromDays(7);
                    //--- https://stackoverflow.com/questions/44720880/cant-create-queue
                    namespaceManager.CreateQueue(new QueueDescription(queueNameNew)
                    {
                        DefaultMessageTimeToLive = TimeSpan.FromDays(7),
                        LockDuration             = TimeSpan.FromSeconds(30),
                        EnablePartitioning       = true,
                        AutoDeleteOnIdle         = TimeSpan.FromDays(1),
                        MaxSizeInMegabytes       = 1024
                    });

                    Debug.WriteLine($"{DateTime.Now.TimeOfDay} : Queue Created successfully. ", queueNameNew);
                }

                //--- ReceiveMessagesAsync().GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                logger.Error($"Tries happened {maxTrials} times. Throwing the exception.{ex}");
                throw;
            }
            #endregion
        }
Esempio n. 9
0
 public static QueueClient Create(ServiceBusEntityConnection entityConnection)
 {
     return(QueueClient.Create(entityConnection, ReceiveMode.PeekLock));
 }
Esempio n. 10
0
 public static QueueClient Create(ServiceBusNamespaceConnection namespaceConnection, string entityPath)
 {
     return(QueueClient.Create(namespaceConnection, entityPath, ReceiveMode.PeekLock));
 }
Esempio n. 11
0
        static void Main(string[] args)
        {
            string sbConnectionString = "Endpoint=sb://miniproject.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=tGkzmzkJl5PqEBSAQxiWA92Dt0wV9HSBOh7QS6k4OGo=";
            string sbQueName          = "recharge";
            string messageBody        = string.Empty;

            do
            {
                try
                {
                    Console.WriteLine("----------------------------------------------------");
                    Console.WriteLine("Mobile Recharge information");
                    Console.WriteLine("----------------------------------------------------");
                    Console.WriteLine("Mobile operator list");
                    Console.WriteLine("1. Greemen phone");
                    Console.WriteLine("2. Aktel");
                    Console.WriteLine("3. Banglalink");
                    Console.WriteLine("4. Citycell");
                    Console.WriteLine("----------------------------------------------------");

                    Console.WriteLine("Choose the operator to recharge:");
                    string mobileOperator = Console.ReadLine();
                    Console.WriteLine("Recharge amount:");
                    string amount = Console.ReadLine();
                    Console.WriteLine("Enter mobile number");
                    string moileNo = Console.ReadLine();
                    Console.WriteLine("----------------------------------------------------");

                    switch (mobileOperator)
                    {
                    case "1":
                        mobileOperator = "Greemen phone";
                        break;

                    case "2":
                        mobileOperator = "Aktel";
                        break;

                    case "3":
                        mobileOperator = "Banglalink";
                        break;

                    case "4":
                        mobileOperator = "Citycell";
                        break;

                    default:
                        break;
                    }

                    messageBody = "Operator Name:" + mobileOperator + "\n Phone No:" + moileNo + "\n Amount:" + amount;
                    queueClient = new Microsoft.Azure.ServiceBus.QueueClient(sbConnectionString, sbQueName);

                    var message = new Microsoft.Azure.ServiceBus.Message(Encoding.UTF8.GetBytes(messageBody));
                    Console.WriteLine($"Message Added in Queue: {messageBody}");
                    queueClient.SendAsync(message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    Console.ReadKey();
                    queueClient.CloseAsync();
                }
                Console.WriteLine("Do you want to send more message: y/n");
                s = Console.ReadLine().ToString();
                Console.ReadKey();
            }while (s == "y");
        }
Esempio n. 12
0
 public ServiceBusQueueService(AzureServiceBus.QueueClient queueClient)
 {
     _queueClient = queueClient;
 }