Ejemplo n.º 1
0
        private MessagingFactory CreateFactory(IEnumerable <Uri> endpoints, IEnumerable <Uri> stsEndpoints, string operationTimeout, string issuerName, string issuerKey, string sasKeyName, string sasKey, string windowsDomain, string windowsUser, SecureString windowsPassword, string oauthDomain, string oauthUser, SecureString oauthPassword, string transportType)
        {
            MessagingFactory messagingFactory;

            try
            {
                MessagingFactorySettings messagingFactorySetting = new MessagingFactorySettings();
                if (!string.IsNullOrWhiteSpace(transportType))
                {
                    messagingFactorySetting.TransportType = (Microsoft.ServiceBus.Messaging.TransportType)Enum.Parse(typeof(Microsoft.ServiceBus.Messaging.TransportType), transportType);
                }
                messagingFactorySetting.TokenProvider = KeyValueConfigurationManager.CreateTokenProvider(stsEndpoints, issuerName, issuerKey, sasKeyName, sasKey, windowsDomain, windowsUser, windowsPassword, oauthDomain, oauthUser, oauthPassword);
                if (!string.IsNullOrEmpty(operationTimeout))
                {
                    messagingFactorySetting.OperationTimeout = TimeSpan.Parse(operationTimeout, CultureInfo.CurrentCulture);
                }
                messagingFactory = MessagingFactory.Create(endpoints, messagingFactorySetting);
            }
            catch (ArgumentException argumentException1)
            {
                ArgumentException argumentException = argumentException1;
                throw new ConfigurationErrorsException(SRClient.AppSettingsCreateFactoryWithInvalidConnectionString(argumentException.Message), argumentException);
            }
            catch (UriFormatException uriFormatException1)
            {
                UriFormatException uriFormatException = uriFormatException1;
                throw new ConfigurationErrorsException(SRClient.AppSettingsCreateFactoryWithInvalidConnectionString(uriFormatException.Message), uriFormatException);
            }
            return(messagingFactory);
        }
Ejemplo n.º 2
0
        public string Get()
        {
            try
            {
                // create a parameter object for the messaging factory that configures
                // the MSI token provider for Service Bus and use of the AMQP protocol:
                MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
                {
                    TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience),
                    TransportType = TransportType.Amqp
                };

                // create the messaging factory using the namespace endpoint name supplied by the user
                MessagingFactory messagingFactory = MessagingFactory.Create($"sb://gordsbus.servicebus.windows.net/",
                                                                            messagingFactorySettings);

                // create a queue client using the queue name supplied by the user
                QueueClient queueClient = messagingFactory.CreateQueueClient("fabrictraffic");
                queueClient.Send(new BrokeredMessage(Encoding.UTF8.GetBytes("Api hit")));

                queueClient.Close();
                messagingFactory.Close();

                return("All good");
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Ejemplo n.º 3
0
        protected void btnReceive_Click(object sender, EventArgs e)
        {
            // create a parameter object for the messaging factory that configures
            // the MSI token provider for Service Bus and use of the AMQP protocol:
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience),
                TransportType = TransportType.Amqp
            };

            // TODO - Remove after backend is patched with the AuthComponent open fix
            // https://github.com/Azure/azure-service-bus/issues/136
            messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false;

            // create the messaging factory using the namespace endpoint name supplied by the user
            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}/",
                                                                        messagingFactorySettings);

            // create a queue client using the queue name supplied by the user
            QueueClient queueClient = messagingFactory.CreateQueueClient(txtQueueName.Text, ReceiveMode.ReceiveAndDelete);
            // request a readily available message (with a very short wait)
            BrokeredMessage msg = queueClient.Receive(TimeSpan.FromSeconds(1));

            if (msg != null)
            {
                // if we got a message, show its contents.
                txtReceivedData.Text += $"Seq#:{msg.SequenceNumber} data:{Encoding.UTF8.GetString(msg.GetBody<byte[]>())}{Environment.NewLine}";
            }
            queueClient.Close();
            messagingFactory.Close();
        }
        public async Task Send100SyncMessages_WhenHandlerThrowsException_DeadLetters()
        {
#pragma warning disable 4014
            Task.Run(async() =>
#pragma warning restore 4014
            {
                for (int i = 0; i < 100; i++)
                {
                    await this.sender.Send(new Message {
                        Bar = i
                    });
                }
            });

            await this.context.Wait(handlerCalls : 50);

            this.context.HandlerCalls.Should().BeInvoked(ntimes: 50);

            // Wait a bit in order to let the bus deadletter
            await Task.Delay(10000);

            MessageReceiver deadLetterReceiver = await MessagingFactory.Create()
                                                 .CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(ReceiverEndpointName), ReceiveMode.ReceiveAndDelete);

            IEnumerable <BrokeredMessage> deadLetteredMessages = await deadLetterReceiver.ReceiveBatchAsync(50);

            deadLetteredMessages.Should().HaveCount(50)
            .And.OnlyContain(b => b.DeliveryCount == 10);
        }
Ejemplo n.º 5
0
        public static void RetrieveMessageFromDeadLetterForSubscription()
        {
            var receiverFactory = MessagingFactory.Create(
                "sb://<NS>.servicebus.windows.net/",
                new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", ""),
                NetMessagingTransportSettings = { BatchFlushInterval = new TimeSpan(0, 0, 0) }
            });

            string data = SubscriptionClient.FormatDeadLetterPath("mrkartopic", "mrkarsub1");

            var receiver = receiverFactory.CreateMessageReceiver(data);

            receiver.OnMessageAsync(
                async message =>
            {
                var body = message.GetBody <Stream>();

                lock (Console.Out)
                {
                    Console.WriteLine("Message ID :" + message.MessageId);
                }

                await message.CompleteAsync();
            },
                new OnMessageOptions {
                AutoComplete = false, MaxConcurrentCalls = 1
            });
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TopicSender"/> class,
        /// automatically creating the given topic if it does not exist.
        /// </summary>
        protected TopicSender(ServiceBusSettings settings, string topic, RetryStrategy retryStrategy)
        {
            this.settings = settings;
            this.topic    = topic;

            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            this.serviceUri    = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);

            // TODO: This could be injected.
            this.retryPolicy           = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            this.retryPolicy.Retrying +=
                (s, e) =>
            {
                var handler = this.Retrying;
                if (handler != null)
                {
                    handler(this, EventArgs.Empty);
                }

                Trace.TraceWarning("An error occurred in attempt number {1} to send a message: {0}", e.LastException.Message, e.CurrentRetryCount);
            };

            var factory = MessagingFactory.Create(this.serviceUri, this.tokenProvider);

            this.topicClient = factory.CreateTopicClient(this.topic);
        }
Ejemplo n.º 7
0
        private static void CreateQueueToRead()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;

            if (_namespaceManager.QueueExists("categoryqueue"))
            {
                MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider);

                QueueClient catsQueueClient = factory.CreateQueueClient("categoryqueue");

                Console.WriteLine("Receiving the Messages from the Queue....");
                BrokeredMessage message;
                int             ctr = 1;
                while ((message = catsQueueClient.Receive(new TimeSpan(hours: 0, minutes: 1, seconds: 5))) != null)
                {
                    Console.WriteLine($"Message Received, Sequance: {message.SequenceNumber}, MessageID: {message.MessageId},\nCat: {message.Properties[(ctr++).ToString()]}");
                    message.Complete();
                    Console.WriteLine("Processing Message (sleeping).....");
                    Thread.Sleep(1000);
                }
                factory.Close();
                catsQueueClient.Close();
                _namespaceManager.DeleteQueue("categoryqueue");
                Console.WriteLine("Finished getting all the data from the queue, Press any key to exit");
            }
        }
        static void SendMessage()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;

            if (!_namespaceManager.TopicExists("DataCollectionTopic"))
            {
                _namespaceManager.CreateTopic("DataCollectionTopic");

                if (!_namespaceManager.SubscriptionExists("DataCollectionTopic", "Inventory"))
                {
                    _namespaceManager.CreateSubscription("DataCollectionTopic", "Inventory");
                }
                if (!_namespaceManager.SubscriptionExists("DataCollectionTopic", "Dashboard"))
                {
                    _namespaceManager.CreateSubscription("DataCollectionTopic", "Dashboard");
                }

                MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider);

                BrokeredMessage message = new BrokeredMessage();//can pass a user defined class too
                message.Label = "SalesReport";
                message.Properties["StoreName"] = "Nike";
                message.Properties["MachineID"] = "POS1";

                BrokeredMessage message1 = new BrokeredMessage();//can pass a user defined class too
                message1.Label = "SalesRep";
                message1.Properties["StoreName"] = "Addidas";
                message1.Properties["MachineID"] = "POS3";

                MessageSender sender = factory.CreateMessageSender("DataCollectionTopic");
                sender.Send(message);
                sender.Send(message1);
                Console.WriteLine("Message Sent Succefully");
            }
        }
Ejemplo n.º 9
0
        public async Task Run(string namespaceAddress, string queueName, string receiveToken)
        {
            var receiverFactory = MessagingFactory.Create(
                namespaceAddress,
                new MessagingFactorySettings
            {
                TransportType = TransportType.Amqp,
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(receiveToken)
            });

            try
            {
                var receiver = receiverFactory.CreateMessageReceiver(queueName, ReceiveMode.PeekLock);
                try
                {
                    var responder = new RequestReplyResponder(
                        new Uri(namespaceAddress),
                        receiver,
                        async m =>
                    {
                        Console.WriteLine("Got {0}", m.Label);
                        switch (m.Label)
                        {
                        case "requestA":
                            return(new BrokeredMessage
                            {
                                Label = "responseA"
                            });

                        case "requestB":
                            return(new BrokeredMessage
                            {
                                Label = "responseB"
                            });

                        default:
                            await m.DeadLetterAsync("Unknown", "Unknown Message");
                            return(null);
                        }
                    });
                    var cts = new CancellationTokenSource();

                    var runTask = responder.Run(cts.Token);

                    Console.WriteLine("Press ENTER to stop processing requests.");
                    Console.ReadLine();
                    cts.Cancel();

                    await runTask;
                }
                finally
                {
                    receiver.Close();
                }
            }
            finally
            {
                receiverFactory.Close();
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            var messageCount = 0;
            var sw           = new Stopwatch();

            Console.WriteLine("How many messages should I put in the queue?");
            if (!int.TryParse(Console.ReadLine(), out messageCount))
            {
                return;
            }

            var namespaceMngr = NamespaceManager.CreateFromConnectionString(connectionString);
            var mfs           = new MessagingFactorySettings();

            mfs.TokenProvider = namespaceMngr.Settings.TokenProvider;
            mfs.NetMessagingTransportSettings.BatchFlushInterval = batchFlushInterval;
            var tasks = new Task[messageCount];

            sw.Start();
            var mf = MessagingFactory.Create(namespaceMngr.Address, mfs);

            Parallel.For(0, messageCount, (i) =>
            {
                var client  = mf.CreateQueueClient(queueName);
                var message = new BrokeredMessage($"This is the #{i} test message!");

                Console.WriteLine(String.Format($"Message id {message.MessageId} sent ({i})."));
                tasks[i] = client.SendAsync(message);
            });
            Task.WhenAll(tasks);

            Console.WriteLine($"{messageCount} messages successfully sent in {sw.ElapsedMilliseconds / 1000} seconds!{Environment.NewLine}Press ENTER to exit the program.");
            Console.ReadLine();
        }
Ejemplo n.º 11
0
 public WindowsServiceBusMessageReceiver(string queueName, string connectionString, int preFetch = 10)
 {
     _namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
     _messagingFactory = MessagingFactory.Create(_namespaceManager.Address, _namespaceManager.Settings.TokenProvider);
     _client           = QueueClient.CreateFromConnectionString(connectionString, queueName);
     PrefetchCount     = preFetch;
 }
        public EventHubsDataPusher(DataPusherConfiguration configuration, IDatasourceRecordSerializer recordSerializer)
        {
            _recordSerializer = recordSerializer;

            _processorCount  = Environment.ProcessorCount;
            _eventHubClients = new List <EventHubClient>(_processorCount);

            var factory = MessagingFactory.Create(
                "sb://" + configuration.EventHubNamespace + ".servicebus.windows.net/",
                new MessagingFactorySettings
            {
                TokenProvider =
                    TokenProvider.CreateSharedAccessSignatureTokenProvider(configuration.EventHubSharedAccessKeyName,
                                                                           configuration.EventHubSharedAccessKey),
                TransportType         = TransportType.Amqp,
                AmqpTransportSettings = new AmqpTransportSettings()
            });

            for (var i = 0; i < _processorCount; i++)
            {
                var newConnnection = factory.CreateEventHubClient(configuration.EventHubPath);

                _eventHubClients.Add(newConnnection);
            }

            Log.DebugFormat("Initialized {0} Event Hub clients", _processorCount);
        }
Ejemplo n.º 13
0
        public static async Task SendPatchMessageAsync(Models.ContactDetails contactDetails, Guid customerId, string reqUrl)
        {
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, AccessKey);
            var messagingFactory = MessagingFactory.Create(BaseAddress, tokenProvider);
            var sender           = messagingFactory.CreateMessageSender(QueueName);
            var messageModel     = new
            {
                TitleMessage     = "Contact Details record modification for {" + customerId + "} at " + DateTime.UtcNow,
                CustomerGuid     = customerId,
                LastModifiedDate = contactDetails.LastModifiedDate,
                URL                = reqUrl,
                IsNewCustomer      = false,
                TouchpointId       = contactDetails.LastModifiedTouchpointId,
                FirstName          = contactDetails.FirstName,
                LastName           = contactDetails.LastName,
                ChangeEmailAddress = contactDetails.ChangeEmailAddress ?? null,
                IsDigitalAccount   = contactDetails.IsDigitalAccount ?? null,
                NewEmail           = contactDetails.NewEmail,
                CurrentEmail       = contactDetails.CurrentEmail,
                contactDetails.IdentityStoreId
            };

            var msg = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageModel))))
            {
                ContentType = "application/json",
                MessageId   = customerId + " " + DateTime.UtcNow
            };

            //msg.ForcePersistence = true; Required when we save message to cosmos
            await sender.SendAsync(msg);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscriptionReceiver"/> class,
        /// automatically creating the topic and subscription if they don't exist.
        /// </summary>
        public SubscriptionReceiver(MessagingSettings settings, string topic, string subscription)
        {
            this.settings     = settings;
            this.subscription = subscription;

            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            this.serviceUri    = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);

            var messagingFactory = MessagingFactory.Create(this.serviceUri, tokenProvider);

            this.client = messagingFactory.CreateSubscriptionClient(topic, subscription);

            var manager = new NamespaceManager(this.serviceUri, this.tokenProvider);

            try
            {
                manager.CreateTopic(
                    new TopicDescription(topic)
                {
                    RequiresDuplicateDetection          = true,
                    DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(30)
                });
            }
            catch (MessagingEntityAlreadyExistsException)
            { }

            try
            {
                manager.CreateSubscription(topic, subscription);
            }
            catch (MessagingEntityAlreadyExistsException)
            { }
        }
Ejemplo n.º 15
0
        public override Task ExecuteAsync()
        {
            TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(IssuerName, IssuerSecret);

            MessagingFactory factory       = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty), credentials);
            QueueClient      myQueueClient = factory.CreateQueueClient(QueueName);

            //Get the message from the queue
            BrokeredMessage message;

            while ((message = myQueueClient.Receive(new TimeSpan(0, 0, 5))) != null)
            {
                RemoteExecutionContext ex = message.GetBody <RemoteExecutionContext>();

                Entity pushNotification = (Entity)ex.InputParameters["Target"];

                //Make sure Recipient is populated
                var ownerId = pushNotification.GetAttributeValue <EntityReference>("lat_recipient").Id.ToString();
                var subject = pushNotification.GetAttributeValue <string>("lat_message");

                SendNotificationAsync(subject, ownerId);
                message.Complete();
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 16
0
        private void btnQueue_Click(object sender, EventArgs e)
        {
            var serviceNamespace = "msswit2013relay";
            var issuerName       = "owner";
            var issuerSecret     = "IqyIwa7gNjBO89HT+3Vd1CcoBbyibvcv6Hd92J+FtPg=";

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

            TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            MessagingFactory factory = MessagingFactory.Create(uri, tokenProvider);

            var msg = new ServiceBusTestMessage
            {
                Password = tbPass.Text
            };

            BrokeredMessage sbMessage = new BrokeredMessage(msg);

            sbMessage.Label = "test message";
            sbMessage.Properties["login"] = tbLogin.Text;

            MessageSender messageSender = factory.CreateMessageSender("MyTopic");

            messageSender.Send(sbMessage);
        }
Ejemplo n.º 17
0
        public static async Task SendPostMessageAsync(Models.Address address, string reqUrl)
        {
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, AccessKey);
            var messagingFactory = MessagingFactory.Create(BaseAddress, tokenProvider);
            var sender           = messagingFactory.CreateMessageSender(QueueName);

            var messageModel = new MessageModel()
            {
                TitleMessage     = "New Address record {" + address.AddressId + "} added for {" + address.CustomerId + "} at " + DateTime.UtcNow,
                CustomerGuid     = address.CustomerId,
                LastModifiedDate = address.LastModifiedDate,
                URL           = reqUrl + "/" + address.AddressId,
                IsNewCustomer = false,
                TouchpointId  = address.LastModifiedTouchpointId
            };

            var msg = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageModel))))
            {
                ContentType = "application/json",
                MessageId   = address.CustomerId + " " + DateTime.UtcNow
            };

            //msg.ForcePersistence = true; Required when we save message to cosmos
            await sender.SendAsync(msg);
        }
Ejemplo n.º 18
0
        public static MessagingFactory CreateSenderMessagingFactory(
            NamespaceManager namespaceManager, ServiceBusConnectionStringBuilder sbConnectionStringBuilder, string entityPath, ServiceBusMessageSenderSettings messageSenderSettings)
        {
            MessagingFactory messagingFactory = MessagingFactory.Create(
                namespaceManager.Address.ToString(),
                new MessagingFactorySettings
            {
                TransportType = TransportType.NetMessaging,
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                    sbConnectionStringBuilder.SharedAccessKeyName,
                    sbConnectionStringBuilder.SharedAccessKey,
                    TokenTimeToLive),
                NetMessagingTransportSettings = new NetMessagingTransportSettings()
                {
                    BatchFlushInterval = TimeSpan.FromMilliseconds(messageSenderSettings.BatchFlushIntervalInMilliSecs)
                }
            });

            TraceHelper.Trace(
                TraceEventType.Information,
                "CreateSenderMessagingFactory",
                "Initialized messaging factory with address {0}",
                messagingFactory.Address);

            return(messagingFactory);
        }
Ejemplo n.º 19
0
        void EnsurePartitionTopicSubscription(TokenProvider tokenProvider, Uri messagingServiceUri, int topicNumber)
        {
            var topicName = string.Format("{0}_{1}", this.TopicPathPrefix, topicNumber + 1);

            try
            {
                if (!this.namespaceManager.TopicExists(topicName))
                {
                    this.namespaceManager.CreateTopic(topicName);
                }
                this.messagingFactories.Add(MessagingFactory.Create(messagingServiceUri, tokenProvider));
                this.topicClients.Add(this.messagingFactories[topicNumber].CreateTopicClient(topicName));
                if (!this.namespaceManager.SubscriptionExists(topicName, this.instanceId))
                {
                    this.namespaceManager.CreateSubscription(topicName, this.instanceId);
                }
                var subscriptionClient = this.messagingFactories[topicNumber].CreateSubscriptionClient(topicName, this.instanceId, ReceiveMode.ReceiveAndDelete);
                subscriptionClient.PrefetchCount = 1;
                this.subscriptionClients.Add(subscriptionClient);

                this.caches.Add(new ServiceBusMessageBusCache(topicNumber, this.cacheTtl));
            }
            catch (Exception e)
            {
                Trace.TraceError("Error managing topic '{0}' with {1}", topicName, e.ToString());
                throw;
            }
        }
Ejemplo n.º 20
0
        public static void Initialize()
        {
            // Using Http to be friendly with outbound firewalls.
            ServiceBusEnvironment.SystemConnectivity.Mode =
                ConnectivityMode.Http;

            // Create the namespace manager which gives you access to
            // management operations.
            var namespaceManager = CreateNamespaceManager();

            //string connString = ConfigurationSettings.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            //QueueClient = QueueClient.CreateFromConnectionString(connString, QueueName);


            // Create the queue if it does not exist already.
            if (!namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.CreateQueue(QueueName);
            }

            // Get a client to the queue.
            var messagingFactory = MessagingFactory.Create(
                namespaceManager.Address,
                namespaceManager.Settings.TokenProvider);

            QueueClient = messagingFactory.CreateQueueClient(
                QueueName);

            if (QueueClient != null)
            {
                RegisterOnMessageHandlerAndReceiveMessages();
            }
        }
Ejemplo n.º 21
0
        public async Task <ActionResult> Queue()
        {
            var result = new List <Account>();

            try
            {
                TokenProvider    tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(DashboardConfig.keyName, DashboardConfig.accessKey);
                MessagingFactory messagingFactory = MessagingFactory.Create(DashboardConfig.baseAddress, tokenProvider);
                var receiver = await messagingFactory.CreateMessageReceiverAsync(DashboardConfig.queueName, ReceiveMode.ReceiveAndDelete);

                while (true)
                {
                    var msg = await receiver.ReceiveAsync(TimeSpan.Zero);

                    if (msg != null)
                    {
                        var serializer = new XmlSerializer(typeof(Account));
                        var objresult  = (Account)serializer.Deserialize(new StreamReader(msg.GetBody <Stream>()));
                        result.Add(objresult);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception)
            {
            }

            return(View(result));
        }
Ejemplo n.º 22
0
        public bool SendMessage(BrokeredMessage message)
        {
            int  trycount = 0;
            bool success  = false;

            while (trycount++ < 10)
            {
                try
                {
                    topic.Send(message);
                    success = true;
                    break;
                }
                catch
                {
                    MessagingFactory factory = MessagingFactory.Create(uri, tP);
                    topic = factory.CreateMessageSender(hubmessagingtopic);
                }
            }

            message.Dispose();

            if (success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 23
0
        public override bool Send(IMessage msg)
        {
            try
            {
                // Create management credentials
                TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", "0cH6A9wTngFOWGpg3jfI8OYd+4FUGSFJWAsid9EHnKE=");
                // Create namespace client
                //NamespaceManager namespaceClient = new NamespaceManager(ServiceBusEnvironment.CreateServiceUri("sb", "hl7test", string.Empty), credentials);

                //QueueDescription myQueue;
                //myQueue = namespaceClient.CreateQueue("NewMessageQueue");
                MessagingFactory factory       = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", "hl7test", string.Empty), credentials);
                QueueClient      myQueueClient = factory.CreateQueueClient("NewMessageQueue");

                //{NHapi.Model.V251.Message.MDM_T01}
                var msgDetail = (msg as NHapi.Model.V251.Message.MDM_T01);
                if (msgDetail != null)
                {
                    var name    = msgDetail.PID.GetPatientName();
                    var content =
                        $"<html><body><p>A new appointment has been scheduled for your patient: {msgDetail.PID.PatientID.IDNumber.Value} <b>{name[0].GivenName} {name[0].FamilyName.Surname}</b><p></body></html>";
                    myQueueClient.Send(new BrokeredMessage(GenerateStreamFromString(content))
                    {
                        CorrelationId = Guid.NewGuid().ToString()
                    });
                }
            }
            catch (IOException)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 24
0
        public static void ReceiveQ()
        {
            Console.WriteLine("In Receive method().");

            TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(QReceiver.IssuerName, QReceiver.IssuerKey);
            Uri           serviceUri  = ServiceBusEnvironment.CreateServiceUri("sb", QReceiver.ServiceNamespace, string.Empty);

            MessagingFactory factory = null;

            factory = MessagingFactory.Create(serviceUri, credentials);

            QueueClient sessionQueueClient = factory.CreateQueueClient(QReceiver.QueueName);

            //Create sessionQueueClient and subscribe to SessionIDs that have a value of "Mike"
            MessageSession  sessionReceiver = sessionQueueClient.AcceptMessageSession("92610", TimeSpan.FromSeconds(60));
            BrokeredMessage receivedMessage;

            while ((receivedMessage = sessionReceiver.Receive(TimeSpan.FromSeconds(60))) != null)
            {
                Console.WriteLine("Received Messages.");
                var data = receivedMessage.GetBody <FireEvent>(new DataContractSerializer(typeof(FireEvent)));
                //Console.WriteLine(String.Format("Customer Name: {0}", data.CustomerName));
                Console.WriteLine("SessionID: {0}", receivedMessage.SessionId);
                //remove message from Topic
                receivedMessage.Complete();
            }

            Console.WriteLine("All received on this session...press enter to exit");
            Console.Read();
        }
Ejemplo n.º 25
0
        public static async Task SendPatchMessageAsync(Models.Transfer transfer, Guid customerId, string reqUrl)
        {
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, AccessKey);
            var messagingFactory = MessagingFactory.Create(BaseAddress, tokenProvider);
            var sender           = messagingFactory.CreateMessageSender(QueueName);
            var messageModel     = new MessageModel
            {
                TitleMessage     = "Transfer record modification for {" + customerId + "} at " + DateTime.UtcNow,
                CustomerGuid     = customerId,
                LastModifiedDate = transfer.LastModifiedDate,
                URL           = reqUrl,
                IsNewCustomer = false,
                TouchpointId  = transfer.LastModifiedTouchpointId
            };

            var msg = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageModel))))
            {
                ContentType = "application/json",
                MessageId   = customerId + " " + DateTime.UtcNow
            };

            await CheckAndCreateSubscription(transfer);

            await sender.SendAsync(msg);
        }
Ejemplo n.º 26
0
        public PublisherService()
        {
            var messageFactory   = MessagingFactory.Create();
            var namespaceManager = NamespaceManager.Create();

            TopicDescription demoTopic;

            ////Only uncomment this when testing creating a fresh topic
            //if (namespaceManager.TopicExists(TopicName))
            //{
            //    namespaceManager.DeleteTopic(TopicName);
            //}

            if (!namespaceManager.TopicExists(TopicName))
            {
                demoTopic = new TopicDescription(TopicName);

                //TODO: Add permissions
                //const string domainUser = "******";
                //AuthorizationRule allowRule = new AllowRule("ServiceBusDefaultNamespace", "role", domainUser,
                //                                            new List<AccessRights> { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });

                //demoTopic.Authorization.Add(allowRule);

                namespaceManager.CreateTopic(demoTopic);
            }
            else
            {
                demoTopic = namespaceManager.GetTopic(TopicName);
            }

            //Create a topic client
            _topicClient = messageFactory.CreateTopicClient(demoTopic.Path);
        }
        public static async Task SendPostMessageAsync(Models.Customer customer, string reqUrl)
        {
            var tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, AccessKey);
            var messagingFactory = MessagingFactory.Create(BaseAddress, tokenProvider);
            var sender           = messagingFactory.CreateMessageSender(QueueName);

            var messageModel = new MessageModel()
            {
                TitleMessage     = "New customer record {" + customer.CustomerId + "} added at " + DateTime.UtcNow,
                CustomerGuid     = customer.CustomerId,
                LastModifiedDate = customer.LastModifiedDate,
                URL           = reqUrl + "/" + customer.CustomerId,
                IsNewCustomer = true,
                TouchpointId  = customer.LastModifiedTouchpointId
            };

            var msg = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageModel))))
            {
                ContentType = "application/json",
                MessageId   = customer.CustomerId + " " + DateTime.UtcNow
            };

            await AutoSubscribeCustomer(customer);

            await sender.SendAsync(msg);
        }
        static void ReceiveMessage()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;

            if (_namespaceManager.TopicExists("DataCollectionTopic"))
            {
                MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider);
                //MessageReceiver receiver = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Inventory");
                MessageReceiver receiver        = factory.CreateMessageReceiver("DataCollectionTopic/subscriptions/Dashboard");
                BrokeredMessage receivedMessage = null;
                try
                {
                    while ((receivedMessage = receiver.Receive()) != null)
                    {
                        ProcessMessage(receivedMessage);
                        receivedMessage.Complete();
                    }
                    factory.Close();
                    _namespaceManager.DeleteSubscription("DataCollectionTopic", "Inventory");
                    // _namespaceManager.DeleteTopic("DataCollectionTopic");
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    receivedMessage.Abandon();
                }
            }
        }
Ejemplo n.º 29
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            // create a parameter object for the messaging factory that configures
            // the MSI token provider for Service Bus and use of the AMQP protocol:
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience),
                TransportType = TransportType.Amqp
            };

            // TODO - Remove after backend is patched with the AuthComponent open fix
            // https://github.com/Azure/azure-service-bus/issues/136
            messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false;

            // create the messaging factory using the namespace endpoint name supplied by the user
            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}/",
                                                                        messagingFactorySettings);

            // create a queue client using the queue name supplied by the user
            QueueClient queueClient = messagingFactory.CreateQueueClient(txtQueueName.Text);

            // send a message using the input text
            queueClient.Send(new BrokeredMessage(Encoding.UTF8.GetBytes(txtData.Text)));

            queueClient.Close();
            messagingFactory.Close();
        }
Ejemplo n.º 30
0
        private static void CreateQueueToRead()
        {
            TokenProvider tokenProvider = _namespaceManager.Settings.TokenProvider;

            if (_namespaceManager.QueueExists("categoryqueue"))
            {
                //Creating the queues with details
                //QueueDescription mnQueue = namespaceManagerClient.CreateQueue("categoryqueue");

                MessagingFactory factory = MessagingFactory.Create(_namespaceManager.Address, tokenProvider);

                //ReceiveAndDelete chances of not clearing the data if it crash before
                //PeekLock, it locks the second message in line and only by calling Complete it moves to the next only then it deletes it of this is default mode
                QueueClient catsQueueClient = factory.CreateQueueClient("categoryqueue");


                Console.WriteLine("Receiving the Messages from the Queue....");
                BrokeredMessage message;
                int             ctr = 1;
                while ((message = catsQueueClient.Receive(new TimeSpan(hours: 0, minutes: 1, seconds: 5))) != null)
                {
                    //Console.WriteLine("Message Received, Sequence: {0}, Cat: {1} and MessageID: {2}", message.SequenceNumber, message.Properties[(ctr++).ToString()], message.MessageId);
                    Console.WriteLine($"Message Received, Sequence: {message.SequenceNumber}, MessageID: {message.MessageId},\nCat: {message.Properties[(ctr++).ToString()]}");
                    message.Complete();
                    Console.WriteLine("Processing Message (sleeping).....");
                    Thread.Sleep(2000);
                }
                factory.Close();
                catsQueueClient.Close();
                _namespaceManager.DeleteQueue("categoryqueue");
                Console.WriteLine("Finished getting all the data from the queue, Press any key to exit");
            }
        }