public async Task Start()
        {
            // Check queue existence.
            var manager = NamespaceManager.CreateFromConnectionString(this.connectionString);

            if (!manager.QueueExists(this.queueName))
            {
                try
                {
                    var queueDescription = new QueueDescription(this.queueName);

                    // Set the maximum delivery count for messages. A message is automatically deadlettered after this number of deliveries.  Default value is 10.
                    queueDescription.MaxDeliveryCount = 3;

                    await manager.CreateQueueAsync(queueDescription);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    Trace.TraceWarning(
                        "MessagingEntityAlreadyExistsException Creating Queue - Queue likely already exists for path: {0}", this.queueName);
                }
                catch (MessagingException ex)
                {
                    var webException = ex.InnerException as WebException;
                    if (webException != null)
                    {
                        var response = webException.Response as HttpWebResponse;

                        // It's likely the conflicting operation being performed by the service bus is another queue create operation
                        // If we don't have a web response with status code 'Conflict' it's another exception
                        if (response == null || response.StatusCode != HttpStatusCode.Conflict)
                        {
                            throw;
                        }

                        Trace.TraceWarning("MessagingException HttpStatusCode.Conflict - Queue likely already exists or is being created or deleted for path: {0}", this.queueName);
                    }
                }
            }

            // Create the queue client. By default, the PeekLock method is used.
            this.client = QueueClient.CreateFromConnectionString(this.connectionString, this.queueName);
        }
Example #2
0
        private static void CriticalNotificationMonitor(
            AzureServiceBusConfig serviceBusConfig,
            string iotHubConnectionString,
            string deviceId,
            CancellationToken token)
        {
            var client = QueueClient.CreateFromConnectionString(serviceBusConfig.ConnectionString,
                                                                serviceBusConfig.QueueName);

            var serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);

            client.OnMessage(async message =>
            {
                var status = (Status)Enum.Parse(
                    typeof(Status),
                    (string)message.Properties[MessageProperty.Status.ToString("G")]);

                switch (status)
                {
                case Status.Pending:
                    // Send message to accept state change.
                    Console.WriteLine();
                    var m = new CloudToDeviceMethod(DeviceMethods.AcceptDesiredProperties.ToString("G"),
                                                    TimeSpan.FromSeconds(30));
                    var result = await serviceClient.InvokeDeviceMethodAsync(deviceId, m, token);
                    $"Device responded with result code: {result.Status} and message: {result.GetPayloadAsJson()}"
                    .LogMessage(ConsoleColor.Green);

                    break;

                case Status.Rejected:
                    var body = new StreamReader(message.GetBody <Stream>()).ReadToEnd();
                    $"Setting value was rejected by the device: '{deviceId}' with message: '{body}'. Please enter a new legal value: "
                    .LogMessage(ConsoleColor.Red);
                    break;

                case Status.Accepted:
                case Status.PreconditionFailed:
                default:
                    throw new ArgumentException();
                }
            });
        }
Example #3
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }

            // Initialize the connection to Service Bus Queue
            Client    = QueueClient.CreateFromConnectionString(connectionString, QueueName);
            IsStopped = false;
            return(base.OnStart());
        }
Example #4
0
        public ActionResult Index()
        {
            Task task = Task.Run(() =>
            {
                QueueClient client = QueueClient.CreateFromConnectionString(connectionString, queueName, ReceiveMode.ReceiveAndDelete);

                client.OnMessage(message =>
                {
                    Stream stream       = message.GetBody <Stream>();
                    StreamReader reader = new StreamReader(stream, Encoding.ASCII);
                    string s            = reader.ReadToEnd();
                    _hubContext.Clients.All.ioTHubNotification(s);
                });
            });

            task.Wait();

            return(View());
        }
Example #5
0
        public void Purge()
        {
            try {
                var q = QueueClient.CreateFromConnectionString(_connectionStr, Main.Path, ReceiveMode.ReceiveAndDelete);

                int max = 0xFFFF;

                // DH: Seems as the returned count varies on the size of the message content, returning usually around 150 msgs
                IEnumerable <BrokeredMessage> msgs = null;
                do
                {
                    msgs = q.ReceiveBatch(max);
                } while(msgs.Count() > 0);
            } catch (Exception e) {
                _log.Trace("Failed to Purge messages from queue, " + Main.Path);
            }

            //while( q.ReceiveBatch(max).Count() == max ) { }
        }
Example #6
0
        static void Main()
        {
            var connectionString = "Endpoint=sb://servicebus-gps.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=JntuuS514ao9BrDtaTsx/q0GL305KrjRcdI4/8fi7nI=";
            var queueName        = "GirishQueue";

            Console.WriteLine("web job 1 started at " + DateTime.Now.ToString());
            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            BrokeredMessage message     = client.Receive();
            string          messageBody = message.GetBody <string>();

            Console.WriteLine($"Message received: {messageBody}");
            SendEmail(messageBody);
            message.Complete();
            //var credentials = new StorageCredentials("servicebus-gps", "JntuuS514ao9BrDtaTsx/q0GL305KrjRcdI4/8fi7nI=");

            //var storageAccount = new CloudStorageAccount(credentials, true);

            //// Create a new client
            //CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            //// Retrieve a reference to a queue
            //CloudQueue queue = queueClient.GetQueueReference("GirishQueue");

            //foreach (CloudQueueMessage message in queue.GetMessages(20, TimeSpan.FromMinutes(5)))
            //{
            //    // Reading content from message
            //    Console.WriteLine(message.AsString);

            //    // Process all messages in less than 5 minutes, deleting each message after processing.
            //    queue.DeleteMessage(message);
            //}

            //client.OnMessage(message =>
            //{
            //    string msg = message.GetBody<String>();
            //   Console.WriteLine(String.Format("Message body 6: {0}", msg));
            //    //Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
            //    Program pgm = new Program();
            //   pgm.SendEmail(msg);
            //});
        }
        public void Execute(SetEventActionTrigger setEventActionTrigger, EventActionContext context)
        {
            try
            {
                var namespaceManager = NamespaceManager.CreateFromConnectionString(this.ConnectionString);

                if (!namespaceManager.QueueExists(this.QueuePath))
                {
                    namespaceManager.CreateQueue(this.QueuePath);
                }

                var client = QueueClient.CreateFromConnectionString(this.ConnectionString, this.QueuePath);

                // Configure the callback options
                var options = new OnMessageOptions {
                    AutoComplete = false, AutoRenewTimeout = TimeSpan.FromMinutes(1)
                };

                // Callback to handle received messages
                client.OnMessage(
                    message =>
                {
                    try
                    {
                        // Remove message from queue
                        this.DataContext = message.GetBody <byte[]>();
                        message.Complete();
                        setEventActionTrigger(this, context);
                    }
                    catch (Exception)
                    {
                        // Indicates a problem, unlock message in queue
                        message.Abandon();
                    }
                },
                    options);
            }
            catch (Exception)
            {
                // ignored
            }
        }
Example #8
0
        private static void SendMessage()
        {
            QueueClient client = QueueClient.CreateFromConnectionString(connectionString, queueName);
            //Client.Send(new BrokeredMessage());
            //Create message, passing a string message for the body
            BrokeredMessage message = new BrokeredMessage("This is the body");

            // Set some additional custom app-specific properties
            message.Label = "This is the label - " + DateTime.UtcNow.ToString();
            message.Properties["TestProperty"] = "TestValue";

            bool messageSent = false;

            // Send message to the queue

            while (!messageSent)
            {
                try
                {
                    Console.WriteLine("Trying to send message...");
                    client.Send(message); // a SendAsync() is also available.
                    messageSent = true;
                }
                catch (MessagingException e)
                {
                    if (!e.IsTransient)
                    {
                        Console.WriteLine("None transient error sending message.");
                        Console.WriteLine(e.Message);
                        throw;
                    }
                    else
                    {
                        Console.WriteLine("Transient error sending message.");
                        Console.WriteLine(e.Message);
                        Console.WriteLine("Will retry sending again in 2 seconds");
                        Thread.Sleep(2000);
                    }
                }
            }
            Console.WriteLine(string.Format("Message sent: Id = {0}, Label = {1}, Body = {2}", message.MessageId, message.Label, message.GetBody <string>()));
        }
        static void Main(string[] args)
        {
            var conn = ConfigurationManager.AppSettings["conexion"];

            var cl = QueueClient.CreateFromConnectionString(conn, "incidencias");

            while (true)
            {
                var msg = cl.Receive();


                if (msg != null)
                {
                    Console.WriteLine("Mensaje:");
                    Console.WriteLine("Incidencia {0} fecha {1}", msg.Properties["incidencia"], msg.Properties["fecha"]);

                    msg.Complete();
                }
            }
        }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AzureCommandBus" /> class.
 /// </summary>
 /// <param name="requestQueueConnectionString">The connection string as shown in the Azure management web</param>
 /// <param name="requestQueueName">Queue which queries are sent over. i.e. the queue that this class is going to read from. Name as specified in the Azure management web.</param>
 /// <param name="replyConnectionString"></param>
 /// <param name="replyQueueName">Queue which query results are sent back on. i.e. the queue that this class is going to send responses on. Name as specified in the Azure management web. Dialogs must have been activated for this queue.</param>
 /// <param name="container"></param>
 /// <remarks>
 /// <para>Dialogs must have been configured for the result queue. See class documentation.</para>
 /// <para>It's recommended that the queue timeouts are low (couple of seconds) if the clients are web users. Otherwise you'll get a lot of work done without anyone using the result (as web users can have gone to another page instead).</para>
 /// </remarks>
 /// <exception cref="System.ArgumentNullException">
 /// requestQueueConnectionString
 /// or
 /// queueName
 /// </exception>
 public AzureQueryBusListener(string requestQueueConnectionString, string requestQueueName, string replyConnectionString, string replyQueueName, IContainer container)
 {
     _container = container;
     if (requestQueueConnectionString == null)
     {
         throw new ArgumentNullException("requestQueueConnectionString");
     }
     if (requestQueueName == null)
     {
         throw new ArgumentNullException("requestQueueName");
     }
     if (replyQueueName == null)
     {
         throw new ArgumentNullException("replyQueueName");
     }
     _responseQueue      = QueueClient.CreateFromConnectionString(replyConnectionString, replyQueueName);
     _requestQueue       = QueueClient.CreateFromConnectionString(requestQueueConnectionString, requestQueueName);
     _queryHandlerMethod = GetType().GetMethod("InvokeHandler", BindingFlags.NonPublic | BindingFlags.Instance);
     SuccessTask         = childContainer => { };
 }
Example #11
0
        public async Task Send()
        {
            QueueClient sendClient = QueueClient.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey], Helpers.BasicQueueName);

            byte[] messageData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Helpers.GetModels()));

            BrokeredMessage message = new BrokeredMessage(new MemoryStream(messageData), true)
            {
                ContentType = "application/json",
                Label       = "dynamic data",
                TimeToLive  = TimeSpan.FromMinutes(20),
            };

            message.Properties.Add("MyCustomSetting", "Setting value");

            await sendClient.SendAsync(message);

            message = message.Clone();
            await sendClient.SendAsync(message);
        }
Example #12
0
        static void Main(string[] args)
        {
            //var conn = ConfigurationManager.AppSettings["connectionString"];
            var conn = "Endpoint=sb://demo444.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=58A9PGyNb5Qayh8zkYxAj0cDtAKKjlRcyvoyqJSr8do=";

            var cl = QueueClient.CreateFromConnectionString(conn, "incidencias");

            while (true)
            {
                var msg = cl.Receive();

                if (msg != null)
                {
                    Console.WriteLine("Mensaje: ");
                    Console.WriteLine("Incidencia {0} fecha {1}", msg.Properties["incidencia"], msg.Properties["fecha"]);

                    msg.Complete();
                }
            }
        }
        /// <summary>
        /// Read All messages from Queue and Put it in the List of OrderMaster
        /// </summary>
        /// <returns></returns>
        public List <OrderMaster> GetOrdersFromQueue()
        {
            QueueClient qClient = QueueClient.CreateFromConnectionString(connStr, "orderqueue", ReceiveMode.PeekLock);
            //BrokeredMessage message = qClient.Receive();



            var messages = qClient.ReceiveBatch(1);

            List <OrderMaster> Orders = new List <OrderMaster>();


            foreach (var item in messages)
            {
                Orders.Add(item.GetBody <OrderMaster>());
                item.Complete(); //Remove Message from queue
            }

            return(Orders);
        }
Example #14
0
        static void Main(string[] args)
        {
            string connectionString = "Endpoint=sb://thegreenbus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=9os+TCEaZ/AjUXk3ZWJoAw944CJrcFIBOyCdLgX1XR8=";
            string queueName        = "queuedemo";

            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            client.OnMessage(message =>
            {
                var json = message.GetBody <string>();
                var m    = JsonConvert.DeserializeObject <TheGreenBusMessage>(json);

                Console.WriteLine(string.Format("Message: {0}", m.Value));
                //Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
                //Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
            });

            Console.WriteLine("Press ENTER to exit program");
            Console.ReadLine();
        }
Example #15
0
        public async Task Run(string queueName, string connectionString)
        {
            Console.WriteLine("Press any key to exit the scenario");

            this.receiveClient = QueueClient.CreateFromConnectionString(connectionString, queueName, ReceiveMode.PeekLock);
            this.InitializeReceiver();

            this.sendClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
            var sendTask = this.SendMessagesAsync();

            Console.ReadKey();

            // shut down the receiver, which will stop the OnMessageAsync loop
            await this.receiveClient.CloseAsync();

            // wait for send work to complete if required
            await sendTask;

            await this.sendClient.CloseAsync();
        }
Example #16
0
        private static void SendServiceRequest(ServiceRequest sr)
        {
            var queueClient = QueueClient.CreateFromConnectionString(_connectionString, _queueName);


            var message = new BrokeredMessage(sr)
            {
                Label = "Service Request"
            };

            message.Properties.Add("Time", DateTime.UtcNow);

            Console.WriteLine("Message Size > " + message.Size);
            Console.WriteLine("Sending Data Message ...");
            queueClient.Send(message);
            Console.WriteLine("Done!");

            queueClient.Close();
            Console.WriteLine("Message Size > " + message.Size);
        }
Example #17
0
        protected void SendQueueMessage <T>(T message)
        {
            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }

            // Initialize the connection to Service Bus Queue
            var client = QueueClient.CreateFromConnectionString(connectionString, QueueName);

            // Create message, with the message body being automatically serialized
            BrokeredMessage brokeredMessage = new BrokeredMessage(message);

            brokeredMessage.Properties["messageType"] = message.GetType().AssemblyQualifiedName;
            client.Send(brokeredMessage);
        }
Example #18
0
        static void Main(string[] args)
        {
            var connectionString = "Endpoint=sb://hellodt.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=MReq3gs9m14ChDiIccuUejQAlD3ATzonuvyeUKeuQnk=";
            var queueName        = "queue1";

            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            // Send a message to the queue
            // var message = new BrokeredMessage("This is a test message!");
            // client.Send(message);

            // Receive a Message from the queue
            client.OnMessage(message =>
            {
                Console.WriteLine(String.Format("Message body: {0}", message.GetBody <String>()));
                Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
            });

            Console.ReadKey();
        }
Example #19
0
        /**
         *  Metodo per inviare degli oggetti Al service Bus: gli elementi della lista non vengono parsizzati con Json ma vengono
         *   direttamente trasformati nel Brokered Message
         * */
        public static async Task SendMessagesAsync(List <T> daInviare)
        {
            QueueClient client = QueueClient.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"], ConfigurationManager.AppSettings["QueueName"]);

            try
            {
                foreach (var x in daInviare)
                {
                    var message = new BrokeredMessage(x);
                    Console.WriteLine($"Sending message: {x.GetType()} , objInviare.campo: {x.ToString()}");
                    await client.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
                await client.CloseAsync();
            }
            await client.CloseAsync();
        }
        public async Task SendMessagesAsync(T messageObject)
        {
            try
            {
                queueClient = QueueClient.CreateFromConnectionString(_serviceBusSetting.ConnectionString, _serviceBusSetting.QueueName);

                MemoryStream    stream  = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageObject)));
                BrokeredMessage message = new BrokeredMessage(stream);
                message.Properties["time"] = DateTime.UtcNow;

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

                queueClient.Close();
            }
            catch (Exception exception)
            {
                throw new ErrorException(ErrorMessage.ERR008, exception.InnerException);
            }
        }
Example #21
0
        private static void NSBStuff()
        {
            ///
            QueueClient queue = QueueClient.CreateFromConnectionString("Endpoint=sb://dan-elvis-local.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=9PgKDcOIyqCKBbmK3tS43Ak74NtslUBx/HQ7Th8fAIE=", QueueClient.FormatDeadLetterPath("eid.elvis"));


            IEnumerable <BrokeredMessage> messages = null;

            while ((messages = queue.PeekBatch(messageCount: 1000)).Any())
            {
                foreach (var message in messages)
                {
                    Console.WriteLine("MessageId: {0}", message.MessageId);
                    foreach (var item in message.Properties)
                    {
                        Console.WriteLine("\t{0} : {1}", item.Key, item.Value);
                    }
                }
            }
        }
Example #22
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="AzureCommandBus" /> class.
        /// </summary>
        /// <param name="requestQueueConnectionString">The connection string as shown in the Azure management web</param>
        /// <param name="requestQueueName">
        ///     Queue which queries are sent over. Name as you've configured it in the Azure management
        ///     web.
        /// </param>
        /// <param name="resultQueueName">
        ///     Queue which query results are sent back on. Name as you've configured it in the Azure
        ///     management web. Dialogs must have been activated for this queue.
        /// </param>
        /// <remarks>
        ///     <para>Dialogs must have been configured for the result queue. See class documentation.</para>
        ///     <para>
        ///         It's recommended that the queue timeouts are low (couple of seconds) if the clients are web users. Otherwise
        ///         you'll get a lot of work done without anyone using the result (as web users can have gone to another page
        ///         instead).
        ///     </para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">
        ///     requestQueueConnectionString
        ///     or
        ///     queueName
        /// </exception>
        public AzureQueryBus(string requestQueueConnectionString, string requestQueueName,
                             string replyQueueConnectionString, string resultQueueName)
        {
            if (requestQueueConnectionString == null)
            {
                throw new ArgumentNullException("requestQueueConnectionString");
            }
            if (requestQueueName == null)
            {
                throw new ArgumentNullException("requestQueueName");
            }
            if (resultQueueName == null)
            {
                throw new ArgumentNullException("resultQueueName");
            }

            _sendQueueClient = QueueClient.CreateFromConnectionString(requestQueueConnectionString, requestQueueName);
            _readQueueClient = QueueClient.CreateFromConnectionString(replyQueueConnectionString, resultQueueName);
            _sessionId       = Guid.NewGuid().ToString();
        }
Example #23
0
        public override bool OnStart()
        {
            _host = new SeekUHostConfiguration <SeekUDemoDependencyResolver>();

            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // Create the queue if it does not exist already
            var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }

            // Initialize the connection to Service Bus Queue
            _client = QueueClient.CreateFromConnectionString(connectionString, QueueName);
            return(base.OnStart());
        }
Example #24
0
        public void Send <T>(T message, Action <ISendConfiguration> configure) where T : class
        {
            ISendConfiguration configuration = this.Configuration.SendConfiguration();

            configure(configuration);

            string queueName = this.CreateQueueIfNotExists <T>(configuration);

            if (!this.queueClients.ContainsKey(queueName))
            {
                this.queueClients.GetOrAdd(queueName, QueueClient.CreateFromConnectionString(this.Configuration.ConnectionString, queueName));
            }

            QueueClient queueClient = this.queueClients[queueName];

            queueClient.Send(new BrokeredMessage(message)
            {
                MessageId = message.GetHashCode().ToString()
            });
        }
Example #25
0
        static void Main(string[] args)
        {
            var connectionString = "Endpoint=sb://tenservicebus.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=gn517yH+6y9/QM5D8XWVOAXcrJTSztSDOjyn5JZcSUQ=";
            var queueName        = "tenservicebusqueue";

            //var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
            //var message = new BrokeredMessage("This is a test message!");
            //client.Send(message);


            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            client.OnMessage(message =>
            {
                Console.WriteLine(String.Format("Message body: {0}", message.GetBody <String>()));
                Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
            });

            Console.ReadLine();
        }
Example #26
0
        //Send Orders to Azure Service Bus
        private static void SendOrders()
        {
            Console.WriteLine("\nSending message to Azure Service Bus Queue…");
            try
            {
                ShopAppInterface SI = new ShopAppInterface();

                ShopSalesOrder order = SI.GetNAVOrder();

                var client = QueueClient.CreateFromConnectionString(ServiceBusConnectionString, QueueName);

                BrokeredMessage message = new BrokeredMessage(order, new DataContractSerializer(typeof(ShopSalesOrder)));

                client.Send(message);
            }
            catch (Exception ex)
            {
                //Handle exception here...
            }
        }
            public QueueClient GetQueueClient(QueueName queueName)
            {
                Func <object> factory = () =>
                                        QueueClient.CreateFromConnectionString(_connectionString,
                                                                               queueName.TopicName);

                if (_cache)
                {
                    var lazy =
                        _cachedClients.GetOrAdd(
                            queueName.ToString(),
                            (name) =>

                            new Lazy <object>(factory));

                    return((QueueClient)lazy.Value);
                }

                return((QueueClient)factory());
            }
Example #28
0
        public static void testsend()
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");


            QueueClient queue = QueueClient.CreateFromConnectionString(connectionString, "contentitems");

            for (int i = 1; i < 11; i++)
            {
                // Create message, passing a string message for the body.
                BrokeredMessage message = new BrokeredMessage("Test message " + i);

                // Set some addtional custom app-specific properties.
                message.Properties["TestProperty"] = "TestValue " + i;
                message.Properties["id"]           = i;

                // Send message to the queue.
                queue.Send(message);
            }
        }
Example #29
0
        public async Task FlushAsync()
        {
            await ForEachMessageAsyncUsingReceiveAndDeleteMode(async message => await Task.Run(() => { }));


            do
            {
                var deadLetterPath   = QueueClient.FormatDeadLetterPath(Name);
                var deadLetterClient = QueueClient.CreateFromConnectionString(ConnectionString, deadLetterPath,
                                                                              ReceiveMode.ReceiveAndDelete);

                var messages = await deadLetterClient.ReceiveBatchAsync(100, TimeSpan.FromMilliseconds(1000));

                var brokeredMessages = messages as BrokeredMessage[] ?? messages.ToArray();
                if (!brokeredMessages.Any())
                {
                    break;
                }
            } while (true);
        }
Example #30
0
        /// <summary>
        /// This program will connect with a service bus and create a collection in the database.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var connectionString = "Endpoint=sb://netservicequeue.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=lcCq1MYmsRTqzyxvLbjBBGcOAWZrXVyakhvy2UmcpGE=";
            var queueName        = "queuetest2";

            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

            Console.WriteLine("Enter an album name: ");
            var albumname = Console.ReadLine();
            var message   = new BrokeredMessage(albumname);

            Console.WriteLine(String.Format("Message id: {0}", message.MessageId));

            client.Send(message);

            Console.WriteLine("Message successfully sent! Press ENTER to exit program");
            Console.ReadLine();
        }