public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            string testConnection = "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=abc123=";

            _messagingFactory = MessagingFactory.CreateFromConnectionString(testConnection);
            OnMessageOptions messageOptions = new OnMessageOptions();

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageOptions);

            ServiceBusConfiguration config = new ServiceBusConfiguration
            {
                MessageOptions = messageOptions
            };

            _mockMessagingProvider   = new Mock <MessagingProvider>(MockBehavior.Strict, config);
            config.MessagingProvider = _mockMessagingProvider.Object;

            _mockMessagingProvider.Setup(p => p.CreateMessageProcessor(_entityPath))
            .Returns(_mockMessageProcessor.Object);

            ServiceBusTriggerExecutor triggerExecutor = new ServiceBusTriggerExecutor(_mockExecutor.Object);

            _listener = new ServiceBusListener(_messagingFactory, _entityPath, triggerExecutor, config);
        }
Beispiel #2
0
        public async Task ReceiveDataFromCloud()
        {
            startingDateTimeUtc = DateTime.UtcNow - TimeSpan.FromHours(24);

            factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            client   = factory.CreateEventHubClient(eventHubEntity);
            group    = client.GetDefaultConsumerGroup();
            receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);

            try
            {
                while (true)
                {
                    EventData data = receiver.Receive();

                    if (data != null)
                    {
                        var receiveddata = Encoding.UTF8.GetString(data.GetBytes());

                        Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), receiveddata);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception {0}", ex);
            }

            receiver.Close();
            client.Close();
            factory.Close();
        }
        public MessagesController()
        {
            var cs      = ConfigurationManager.ConnectionStrings["AzureServiceBus"].ConnectionString;
            var factory = MessagingFactory.CreateFromConnectionString(cs);

            _subscriptionManager = new MessageQueueSubscriptionManager(factory);
        }
Beispiel #4
0
        public OfflineProcessingService(IApplicationSettings settings)
        {
            var messagingFactory = MessagingFactory.CreateFromConnectionString(settings.JobMessagesConnectionString);

            _queueClient = messagingFactory.CreateQueueClient(ApplicationSettings.JobMessagesQueue);
            _topicClient = messagingFactory.CreateTopicClient(ApplicationSettings.ConfirmationTopic);
        }
        public void GenerateMessages()
        {
            if (DeviceSendingDetails.RedirectToLocalFile == false)
            {
                var connectionString =
                    String.Format(
                        "Endpoint=sb://{0}.servicebus.windows.net/;SharedAccessKeyName={1};SharedAccessKey={2};TransportType=Amqp",
                        EventHubConnectionDetails.ServiceBusNamespace,
                        EventHubConnectionDetails.SasPolicyName,
                        EventHubConnectionDetails.SasPolicyKey);

                var factory = MessagingFactory.CreateFromConnectionString(connectionString);
                EventHubClient = factory.CreateEventHubClient(EventHubConnectionDetails.EventHubName);
            }

            if (DeviceSendingDetails.RedirectToLocalFile)
            {
                Console.WriteLine("Redirecting messages to file {0}", DeviceSendingDetails.RedirectFileName);
            }

            var startTime = DateTime.UtcNow;

            for (var i = 0; i < DeviceSendingDetails.IterationSeconds; i++)
            {
                SendDeviceEventStream();
                Console.WriteLine("Messages fired onto the eventhub!");

                Thread.Sleep(DeviceSendingDetails.MillisecondDelay);
            }

            var duration = DateTime.UtcNow - startTime;

            Console.WriteLine("Total Time (ms) : {0}", duration.TotalMilliseconds);
        }
Beispiel #6
0
        public void Scenario10_QueueRequestResponse(string queue, string replyTo)
        {
            WorkerThread receiverThread = new WorkerThread(this.Scenario11_QueueReceiver);

            receiverThread.Start(queue);

            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            MessageSender sender = factory.CreateMessageSender(queue);

            MemoryStream    stream  = new MemoryStream(Encoding.UTF8.GetBytes("Request"));
            BrokeredMessage message = new BrokeredMessage(stream);

            message.MessageId          = Guid.NewGuid().ToString();
            message.ReplyTo            = replyTo;
            message.Properties["time"] = DateTime.UtcNow;

            sender.Send(message);

            MessageReceiver receiver = factory.CreateMessageReceiver(replyTo);

            BrokeredMessage response = receiver.Receive();

            response.Complete();

            sender.Close();
            receiver.Close();
            factory.Close();
        }
Beispiel #7
0
        public void Scenario12_TopicSend(string topic, string subscription1, string subscription2)
        {
            WorkerThread sub1Thread = new WorkerThread(this.Scenario13_SubscriptionReceiver);

            sub1Thread.Start(new Scenarios.TopicSub()
            {
                Topic = topic, Sub = subscription1
            });

            WorkerThread sub2Thread = new WorkerThread(this.Scenario13_SubscriptionReceiver);

            sub2Thread.Start(new Scenarios.TopicSub()
            {
                Topic = topic, Sub = subscription2
            });

            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            TopicClient client = factory.CreateTopicClient(topic);

            MemoryStream    stream  = new MemoryStream(Encoding.UTF8.GetBytes("Body"));
            BrokeredMessage message = new BrokeredMessage(stream);

            message.Properties["time"] = DateTime.UtcNow;

            client.Send(message);

            client.Close();
            factory.Close();
        }
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var configurationPackage       = Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
            var serviceBusConnectionString = configurationPackage.Settings.Sections["ConnectionString"]
                                             .Parameters["SFTestServiceBus"].Value;

            var factory   = MessagingFactory.CreateFromConnectionString(serviceBusConnectionString);
            var subClient = factory.CreateSubscriptionClient("temperature", "temperature-writer");

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                IEnumerable <BrokeredMessage> messages = await subClient.ReceiveBatchAsync(20);

                if (messages.Any())
                {
                    foreach (var message in messages)
                    {
                        // var st = message.GetBody<Stream>();
                    }
                }

                ServiceEventSource.Current.ServiceMessage(Context, messages.Count().ToString());
                await Task.Delay(1000, cancellationToken);
            }
        }
Beispiel #9
0
        void InitializeReceiver(string connectionString, string queueName, CancellationToken ct)
        {
            try
            {
                var receiverFactory = MessagingFactory.CreateFromConnectionString(connectionString);

                ct.Register(() => receiverFactory.Close());

                var client = receiverFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock);

                // This approach has not been ported to the new .NET Core implemenetation yet
                // https://github.com/Azure/azure-service-bus/issues/131
                // TODO: Follow up on this

                client.RegisterSessionHandler(
                    typeof(SessionHandler),
                    new SessionHandlerOptions
                {
                    MessageWaitTimeout    = TimeSpan.FromSeconds(1),
                    MaxConcurrentSessions = 1,
                    AutoComplete          = false
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public async Task RunOneMessageEmulationAsync(string scenarioName, CancellationToken token)
        {
            Logger.SimulationStarted(_hostName, scenarioName);

            var produceMessagesForScenario = SimulationScenarios.GetScenarioByName(scenarioName);

            var messagingFactory = MessagingFactory
                                   .CreateFromConnectionString(_simulatorConfiguration.EventHubConnectionString);

            var messageSender = new MessageSender(
                messagingFactory: messagingFactory,
                config: _simulatorConfiguration,
                serializer: Serializer.ToJsonUTF8,
                telemetryPublisher: _instrumentationPublisher
                );

            try
            {
                var scenario = produceMessagesForScenario();
                var car      = new Car("Single Message Car", scenario, messageSender.SendAsync);
                await car.RunOneMessageSimulationAsync(token);
            }
            finally
            {
                messagingFactory.Close();
            }

            Logger.SimulationEnded(_hostName);
        }
        public static MessagingFactory CreateMessagingFactory(string connectionString)
        {
            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);

            factory.RetryPolicy = RetryPolicy.Default;
            return(factory);
        }
Beispiel #12
0
        public async Task Run(string connectionString)
        {
            Console.WriteLine("\nSending messages\n");

            var messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
            var topicSender      = await messagingFactory.CreateMessageSenderAsync("AutoForwardSourceTopic");

            await topicSender.SendAsync(CreateMessage("M1"));

            var queueSender = await messagingFactory.CreateMessageSenderAsync("AutoForwardTargetQueue");

            await queueSender.SendAsync(CreateMessage("M1"));

            var targetQueueReceiver = messagingFactory.CreateQueueClient("AutoForwardTargetQueue");

            for (int i = 0; i < 2; i++)
            {
                var message = await targetQueueReceiver.ReceiveAsync(TimeSpan.FromSeconds(10));

                if (message != null)
                {
                    await this.PrintReceivedMessage(message);

                    await message.CompleteAsync();
                }
                else
                {
                    throw new Exception("Expected message not received.");
                }
            }
            await targetQueueReceiver.CloseAsync();

            messagingFactory.Close();
        }
Beispiel #13
0
        /// <summary>
        /// Constructs an uploader object.
        /// </summary>
        /// <param name="eventHubConnectionString">The Azure Stream Analytics connection string.</param>
        /// <param name="batchConfig">Optional; The batching configuration to used when uploading data.</param>
        /// <param name="developmentMode">If true, enables additional logging and disables batching.</param>
        public EventUploaderASA
        (
            string eventHubConnectionString,
            BatchingConfiguration batchConfig = null,
            bool developmentMode = false
        )
            : base(batchConfig, developmentMode)
        {
            this.connectionString = eventHubConnectionString;

            var builder = new ServiceBusConnectionStringBuilder(this.connectionString)
            {
                TransportType = TransportType.Amqp,
            };

            var eventHubInputName = builder.EntityPath;

            builder.EntityPath = null;

            if (this.batchConfig.ReUseTcpConnection)
            {
                this.client = EventHubClient.CreateFromConnectionString(builder.ToString(), eventHubInputName);
            }
            else
            {
                var factory = MessagingFactory.CreateFromConnectionString(builder.ToString());
                this.client = factory.CreateEventHubClient(eventHubInputName);
            }
        }
Beispiel #14
0
        static async Task MainAsync()
        {
            var factory = MessagingFactory.CreateFromConnectionString(connectionString);
            //create a receiver on the queue
            var receiver = await factory.CreateMessageReceiverAsync(queueName);

            //create a sender on the queue
            var sender = await factory.CreateMessageSenderAsync(queueName);

            //start message pump to listen for message on the queue
            receiver.OnMessageAsync(async receivedMessage =>
            {
                //trace out the MessageId property of received message
                Console.WriteLine("Receiving message - {0}", receivedMessage.MessageId);
                await receivedMessage.CompleteAsync();
            }, new OnMessageOptions()
            {
                AutoComplete = false
            });

            //send 3 message to the queue
            Console.WriteLine("Sending Message 1");
            await sender.SendAsync(new BrokeredMessage("Hello World!") { MessageId = "deadbeef-dead-beef-dead-beef00000075" });

            Console.WriteLine("Sending Message 2");
            await sender.SendAsync(new BrokeredMessage("Hello World!") { MessageId = "deadbeef-dead-beef-dead-beef00000075" });

            Console.WriteLine("Sending Message 3");
            await sender.SendAsync(new BrokeredMessage("Hello World!") { MessageId = "deadbeef-dead-beef-dead-beef00000075" });

            await Task.WhenAny(
                Task.Run(() => Console.ReadKey()),
                Task.Delay(TimeSpan.FromSeconds(30))
                );
        }
Beispiel #15
0
        static async Task Receive(string connectionString)
        {
            var receiverMessagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
            var receiver = await receiverMessagingFactory.CreateMessageReceiverAsync(DupdetectQueueName, ReceiveMode.PeekLock);

            // Receive messages from queue
            var receivedMessageId = "";

            Console.WriteLine("\n\tWaiting for messages from {0} ...", DupdetectQueueName);
            while (true)
            {
                var receivedMessage = await receiver.ReceiveAsync(TimeSpan.FromSeconds(10));

                if (receivedMessage == null)
                {
                    break;
                }
                Console.WriteLine("\t<= Received a message with messageId {0}", receivedMessage.MessageId);
                await receivedMessage.CompleteAsync();

                if (receivedMessageId.Equals(receivedMessage.MessageId, StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("\t\tRECEIVED a DUPLICATE MESSAGE");
                }

                receivedMessageId = receivedMessage.MessageId;
            }

            Console.WriteLine("\tDone receiving messages from {0}", DupdetectQueueName);

            await receiver.CloseAsync();
        }
Beispiel #16
0
        public ServiceBusConnection(ServiceBusScaleoutConfiguration configuration, TraceSource traceSource)
        {
            _trace            = traceSource;
            _connectionString = configuration.BuildConnectionString();

            try
            {
                _namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);
                _factory          = MessagingFactory.CreateFromConnectionString(_connectionString);

                if (configuration.RetryPolicy != null)
                {
                    _factory.RetryPolicy = configuration.RetryPolicy;
                }
                else
                {
                    _factory.RetryPolicy = RetryExponential.Default;
                }
            }
            catch (ConfigurationErrorsException)
            {
                _trace.TraceError("The configured Service Bus connection string contains an invalid property. Check the exception details for more information.");
                throw;
            }

            _backoffTime             = configuration.BackoffTime;
            _idleSubscriptionTimeout = configuration.IdleSubscriptionTimeout;
            _configuration           = configuration;
        }
Beispiel #17
0
        public AzureSBQSender(string connectionString, string queueName, int numberOfSenders)
        {
            NumberOfSenders = numberOfSenders;

            var connBuilder      = new ServiceBusConnectionStringBuilder(connectionString);
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

            // Create queue.
            if (!namespaceManager.QueueExists(queueName))
            {
                namespaceManager.CreateQueue(queueName);
            }

            // Create messaging factories, senders and receivers.
            _messagingFactory = new MessagingFactory[NumberOfSenders];
            Sender            = new MessageSender[NumberOfSenders];

            // Create senders.
            var factoryIndex = 0;

            for (var i = 0; i < NumberOfSenders; i++)
            {
                _messagingFactory[factoryIndex] = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
                Sender[i] = _messagingFactory[factoryIndex++].CreateMessageSender(queueName);
            }
        }
        public ServiceBusWrapper(IConfiguration configuration, Logger logger)
        {
            this.logger = logger;
            var messagingFactory = MessagingFactory.CreateFromConnectionString(configuration.ServicebusConnection());

            messageSender = messagingFactory.CreateMessageSender(configuration.Queue());
        }
Beispiel #19
0
        private void Scenario11_QueueReceiver(object obj)
        {
            string queue = (string)obj;

            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            QueueClient client = factory.CreateQueueClient(queue);

            while (true)
            {
                BrokeredMessage request = client.Receive();
                request.Complete();

                MessageSender sender = factory.CreateMessageSender(request.ReplyTo);

                MemoryStream    stream   = new MemoryStream(Encoding.UTF8.GetBytes("Response"));
                BrokeredMessage response = new BrokeredMessage(stream);
                response.CorrelationId      = request.MessageId;
                response.Properties["time"] = DateTime.UtcNow;

                sender.Send(response);

                sender.Close();
            }
        }
Beispiel #20
0
        static async Task AsyncMain()
        {
            MessagingFactory fact = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings["ConnectionString"]);

            var sender = fact.CreateMessageSender("destinationQueue", "queue2");

            var receiver = fact.CreateMessageReceiver("queue2", ReceiveMode.PeekLock);

            BrokeredMessage msg;
            BrokeredMessage recMsg;

            var i = 0;

            while (i < 5000)
            {
                recMsg = await receiver.ReceiveAsync();

                msg = new BrokeredMessage();

                if (recMsg != null)
                {
                    using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        msg.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddMinutes(6);

                        await recMsg.CompleteAsync();

                        await sender.SendAsync(msg);

                        scope.Complete();
                        i++;
                    }
                }
            }
        }
Beispiel #21
0
        public void Scenario4_EventHubSendToPublisherWithToken(string sbnamespace, string eventHubEntity, string publisher, string sharedAccessKeyName, string sharedAccessKey)
        {
            string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                sharedAccessKeyName,
                sharedAccessKey,
                new TimeSpan(0, 20, 0));

            string connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                token);

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);

            EventHubClient client = factory.CreateEventHubClient(eventHubEntity);

            EventHubSender sender = client.CreateSender(publisher);

            EventData data = new EventData(Encoding.UTF8.GetBytes("Body"));

            data.Properties["time"] = DateTime.UtcNow;

            sender.Send(data);

            sender.Close();
            client.Close();
            factory.Close();
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            const string QueueName        = "sbmQueue1";
            string       connectionString =
                CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            string msg = "This is a message from sender.";

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

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

            MessagingFactory factory =
                MessagingFactory.CreateFromConnectionString(connectionString);

            QueueClient     myQueueClient = factory.CreateQueueClient(QueueName);
            BrokeredMessage bsm           = new BrokeredMessage(msg);

            myQueueClient.Send(bsm);

            Console.ReadLine();
        }
Beispiel #23
0
        protected override async Task OnOpenAsync()
        {
            Extensions.For(0, this.Settings.SenderCount, (i) => this.Factories.Add(MessagingFactory.CreateFromConnectionString(this.ConnectionString)));
            var senderPath = this.Settings.EntityType == EntityType.Topic ? this.Settings.TopicPath : this.Settings.QueuePath;

            for (int i = 0; i < this.Settings.SenderCount; i++)
            {
                var factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);
                factory.RetryPolicy = RetryPolicy.NoRetry;
                this.Factories.Add(factory);
                var sender = factory.CreateMessageSender(senderPath);
                sender.RetryPolicy = RetryPolicy.NoRetry;
                this.senders.Add(sender);
            }

            await this.senders.First().SendAsync(new BrokeredMessage());

            await this.senders.ParallelForEachAsync(async (sender, senderIndex) =>
            {
                await sender.SendAsync(new BrokeredMessage()
                {
                    TimeToLive = TimeSpan.FromMilliseconds(1)
                });
            });
        }
Beispiel #24
0
        private async Task PublishToQueueAsync <T>(IEnumerable <T> events)
            where T : IEvent
        {
            var serviceBusConnectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var serviceBusQueue            = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.EventQueue");

            var factory       = MessagingFactory.CreateFromConnectionString(serviceBusConnectionString);
            var messageSender = factory.CreateMessageSender(serviceBusQueue);

            var tasks = new List <Task>();

            foreach (var @event in events)
            {
                var message = new BrokeredMessage();
                var json    = JsonConvert.SerializeObject(@event);

                message.Properties.Add("json", json);
                message.Properties.Add("type", @event.GetType().AssemblyQualifiedName);

                tasks.Add(messageSender.SendAsync(message));
            }

            await Task.WhenAll(tasks);

            messageSender.Close();
        }
Beispiel #25
0
        private async Task <bool> SendAsync(string partitionKey, LogEventInfo logEvent)
        {
            if (this._messsagingFactory == null)
            {
                this._messsagingFactory = MessagingFactory.CreateFromConnectionString(EventHubConnectionString);
            }

            if (this._eventHubClient == null)
            {
                this._eventHubClient = this._messsagingFactory.CreateEventHubClient(EventHubPath);
            }

            string logMessage = this.Layout.Render(logEvent);

            using (var eventHubData = new EventData(Encoding.UTF8.GetBytes(logMessage))
            {
                PartitionKey = partitionKey
            })
            {
                foreach (var key in logEvent.Properties.Keys)
                {
                    eventHubData.Properties.Add(key.ToString(), logEvent.Properties[key]);
                }

                await _eventHubClient.SendAsync(eventHubData);

                return(true);
            } //end of using
        }     //end of SendAsync
Beispiel #26
0
        public Subscription(int num)
        {
            _subscriptionName = $"subscription{num}";

            // Create namespace client
            NamespaceManager        namespaceClient         = NamespaceManager.CreateFromConnectionString(_connectionString);
            SubscriptionDescription subscriptionDescription = null;

            foreach (var item in namespaceClient.GetSubscriptions(_topicPath))
            {
                if (item.Name == _subscriptionName)
                {
                    subscriptionDescription = item;
                    break;
                }
            }

            if (subscriptionDescription == null)
            {
                subscriptionDescription = namespaceClient.CreateSubscription(_topicPath, _subscriptionName);
            }

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(_connectionString);

            _client = factory.CreateSubscriptionClient(_topicPath, _subscriptionName, ReceiveMode.PeekLock);

            //_client = SubscriptionClient.CreateFromConnectionString(_connectionString, _topicPath, _subscriptionName, ReceiveMode.PeekLock);
        }
Beispiel #27
0
        // Delete the first published message from service bus subscription
        public void RemoveFirstPublishedMessage(string ServiceBusConnectionString, string TopicName, string SubscriptionName)
        {
            // Create service Bus namespace manager
            var namespaceManager = NamespaceManager.CreateFromConnectionString(ServiceBusConnectionString);
            // Get subscrition information of the topic
            var subscriptionDesc = namespaceManager.GetSubscription(TopicName, SubscriptionName);
            // Check number of published messages
            long messageCount = subscriptionDesc.MessageCount;

            // Skip removing message if none exists
            if (messageCount != 0)
            {
                // Create service bus messageing factory
                Factory = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString);
                // Create subscription client for the topic
                SubscriptionClient mySubscriptionClient = Factory.CreateSubscriptionClient(TopicName, SubscriptionName);

                // Get first broker message from the subscription.
                // Use Receive function
                BrokeredMessage MessageReceived = mySubscriptionClient.Receive();

                // Use lock token of the received brokered message to mark the message is completed.
                // The message will be removed from the subscription
                mySubscriptionClient.Complete(MessageReceived.LockToken);

                //Clean up
                MessageReceived.Dispose();
                mySubscriptionClient.Close();
            }
        }
Beispiel #28
0
        static async Task Send(string connectionString)
        {
            // Create communication objects to send and receive on the queue
            var senderMessagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
            var sender = await senderMessagingFactory.CreateMessageSenderAsync(DupdetectQueueName);

            string messageId = Guid.NewGuid().ToString();

            // Send messages to queue
            Console.WriteLine("\tSending messages to {0} ...", DupdetectQueueName);
            var message = new BrokeredMessage
            {
                MessageId  = messageId,
                TimeToLive = TimeSpan.FromMinutes(1)
            };
            await sender.SendAsync(message);

            Console.WriteLine("\t=> Sent a message with messageId {0}", message.MessageId);

            var message2 = new BrokeredMessage
            {
                MessageId  = messageId,
                TimeToLive = TimeSpan.FromMinutes(1)
            };
            await sender.SendAsync(message2);

            Console.WriteLine("\t=> Sent a duplicate message with messageId {0}", message.MessageId);
            await sender.CloseAsync();
        }
        private async void ProcessQueuedMessages(SubscriptionClient client)
        {
            try
            {
                MessagingFactory factory                 = MessagingFactory.CreateFromConnectionString(connectionString);
                MessageReceiver  messageReceiver         = factory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(topicPath, subscriptionName));
                IEnumerable <BrokeredMessage> messageSet = messageReceiver.ReceiveBatch(10000);
                Debug.WriteLine("**** Received " + messageSet.Count() + " messages *****");
                foreach (BrokeredMessage message in messageSet)
                {
                    try
                    {
                        await processMessage(message);

                        Debug.WriteLine("**** ProcessQueuedMessages.processMessage completed ****");
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("**** Error ProcessQueuedMessages.processMessage " + e.ToString() + " ****");
                    }
                }
            } catch
            {
                Debug.WriteLine("**** Error ProcessQueuedMessages ****");
            }
        }
Beispiel #30
0
        public void Connect()
        {
            try
            {
                string ServiceBusConnectionString = String.Format(@"Endpoint=sb://{0}.servicebus.windows.net/;SharedAccessKeyName={1};SharedAccessKey={2};",
                                                                  sbConfig.ServiceBusNamespace, sbConfig.SasKeyName, sbConfig.SasKey);

                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString);
                this.subscriptionClient = SubscriptionClient.CreateFromConnectionString(ServiceBusConnectionString, sbConfig.ServiceBusTopic,
                                                                                        sbConfig.ServiceBusSubscription, ReceiveMode.ReceiveAndDelete);

                this.subscriptionClient.OnMessage(this.OnNewMessage);

                if (OnServiceBusConnected != null)
                {
                    OnServiceBusConnected.Invoke(this.subscriptionClient.Name, this.subscriptionClient.TopicPath);
                    this.LogEvent(EventTypeConsts.Info, "Binding done", "Servicebus handler listining for messages.");
                }
                else
                {
                    this.LogEvent(EventTypeConsts.Error, "Error", "OnServiceBusConnected handlers not set");
                }
            }
            catch (Exception ex)
            {
                this.LogEvent(EventTypeConsts.Error, "subscription init error", ex.Message);
            }
        }