public ServiceBusTopicHelper Publish <T>(T message, Action <BrokeredMessage> callback = null)
        {
            SetupServiceBusEnvironment();
            var topicName   = string.Format("Topic_{0}", typeof(T).Name);
            var topicClient = _messagingFactory.CreateTopicClient(topicName);

            try
            {
                var m = new BrokeredMessage(message);
                if (callback != null)
                {
                    callback(m);
                }
                topicClient.Send(m);
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                topicClient.Close();
            }

            return(this);
        }
예제 #2
0
        private async static Task TopicClientTest()
        {
            // Create TopicClient object
            var topicClient = messagingFactory.CreateTopicClient(TopicName);

            // Test TopicClient.SendBatchAsync: if the batch size is greater than the max batch size
            // the method throws a  MessageSizeExceededException
            try
            {
                PrintMessage(CallingTopicClientSendBatchAsync);
                await topicClient.SendBatchAsync(CreateBrokeredMessageBatch());

                PrintMessage(TopicClientSendBatchAsyncCalled);
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }

            try
            {
                // Send the batch using the SendPartitionedBatchAsync method
                PrintMessage(CallingTopicClientSendPartitionedBatchAsync);
                await topicClient.SendPartitionedBatchAsync(CreateBrokeredMessageBatch(), true);

                PrintMessage(TopicClientSendPartitionedBatchAsyncCalled);
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
        }
예제 #3
0
        public void Publish(Message message, string topicPath)
        {
            var client = _messagingFactory.CreateTopicClient(topicPath);
            var sender = client.MessagingFactory.CreateMessageSender(client.Path);

            sender.Send(Map(message));
        }
예제 #4
0
        public TopicClient CreateTopicClient(string nsName, string topicName, string keyName, string key)
        {
            string           cs = _csp.GetConnectionString(nsName, keyName, key);
            MessagingFactory mf = MessagingFactory.CreateFromConnectionString(cs);

            return(mf.CreateTopicClient(topicName));
        }
예제 #5
0
        static void Main(string[] args)
        {
            var topicClient = factory.CreateTopicClient(TopicName);

            CreateMultipleSubscriptions(topicClient);
            Console.ReadLine();
        }
예제 #6
0
        public async Task Open()
        {
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString);
            TokenProvider    tokenProvider    = namespaceManager.Settings.TokenProvider;

            var topicDescription = new TopicDescription(_topicName);

            topicDescription.EnableExpress           = true;
            topicDescription.EnableBatchedOperations = true;

            if (!await namespaceManager.TopicExistsAsync(_topicName))
            {
                topicDescription = namespaceManager.CreateTopic(topicDescription);
            }

            if (!await namespaceManager.SubscriptionExistsAsync(topicDescription.Path, "express"))
            {
                var sd = new SubscriptionDescription(topicDescription.Path, "express");
                await namespaceManager.CreateSubscriptionAsync(sd);
            }

            var settings = new MessagingFactorySettings
            {
                TokenProvider         = tokenProvider,
                TransportType         = TransportType.Amqp,
                AmqpTransportSettings = new Microsoft.ServiceBus.Messaging.Amqp.AmqpTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromMilliseconds(50),
                }
            };

            _factory = await MessagingFactory.CreateAsync(namespaceManager.Address, settings);

            _topicClient = _factory.CreateTopicClient(topicDescription.Path);
        }
예제 #7
0
        public async void Init(MessageReceived messageReceivedHandler) {
            this.random = new Random();

            //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;
            
            // Tcp mode does not work when I run in a VM (VirtualBox) and the host 
            // is using a wireless connection. Hard coding to Http.
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            this.factory = MessagingFactory.CreateFromConnectionString(connectionString);
            this.namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.TopicExists(topicName)) {
                namespaceManager.CreateTopic(topicName);
            }

            this.subscriptionName = Guid.NewGuid().ToString();

            // Not needed really, it's a GUID...
            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName)) {
                namespaceManager.CreateSubscription(topicName, subscriptionName);
            }

            this.topicClient = factory.CreateTopicClient(topicName);

            this.subClient = factory.CreateSubscriptionClient(topicName, subscriptionName);

            while (true) {
                await ReceiveMessageTaskAsync(messageReceivedHandler);
            }
        }
예제 #8
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();
        }
예제 #9
0
        static void Main(string[] args)
        {
            string sbConnectionString =
                "YOURSERVICEBUSCONNECTIONSTRING";

            string topicName = "VideoUploaded";

            var namespaceManager = NamespaceManager.CreateFromConnectionString(sbConnectionString);

            TopicDescription topicDescription = null;

            if (!namespaceManager.TopicExists(topicName))
            {
                topicDescription = namespaceManager.CreateTopic(topicName);
            }
            else
            {
                topicDescription = namespaceManager.GetTopic(topicName);
            }

            MessagingFactory factory     = MessagingFactory.CreateFromConnectionString(sbConnectionString);
            TopicClient      topicClient = factory.CreateTopicClient(topicDescription.Path);

            while (true)
            {
                Console.WriteLine("Message à envoyer:");
                string value = Console.ReadLine();
                topicClient.Send(new BrokeredMessage(value));
            }
        }
예제 #10
0
        private void Form1_Load(object sender, EventArgs e)

        {
            // default is 2, for throughput optimization, lets bump it up.
            ServicePointManager.DefaultConnectionLimit = 12;

            // another optimization, saves one round trip per msg by skipping the "I have some thing for you, is that ok?" handshake
            ServicePointManager.Expect100Continue = false;

            // Create Namespace Manager and messaging factory
            Uri serviceAddress = ServiceBusEnvironment.CreateServiceUri("sb", Config.serviceNamespace, string.Empty);

            nsManager      = new NamespaceManager(serviceAddress, TokenProvider.CreateSharedSecretTokenProvider(Config.issuerName, Config.issuerSecret));
            messageFactory = MessagingFactory.Create(serviceAddress, TokenProvider.CreateSharedSecretTokenProvider(Config.issuerName, Config.issuerSecret));

            // set up the topic with batched operations, and time to live of 10 minutes. Subscriptions will not delete the message, since multiple clients are accessing the message
            // it will expire on its own after 10 minutes.
            topicDescription = new TopicDescription(topicName)
            {
                DefaultMessageTimeToLive = TimeSpan.FromMinutes(10), Path = topicName, EnableBatchedOperations = true
            };
            if (!nsManager.TopicExists(topicDescription.Path))
            {
                nsManager.CreateTopic(topicDescription);
            }

            // create client
            eventTopic = messageFactory.CreateTopicClient(topicName);
        }
예제 #11
0
 public HeaterCommunication()
 {
     var topicNameSend = "businessrulestofieldgateway";
     _topicNameReceive = "fieldgatewaytobusinessrules";
     _namespaceMgr = NamespaceManager.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));
     _factory = MessagingFactory.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));
     _client = _factory.CreateTopicClient(topicNameSend);
 }
        public async Task <TopicClient> CreateFor <T>()
        {
            var topic = await _topicRepository.Get <T>();

            return(_messagingFactory.CreateTopicClient(topic.Path));

            //.ContinueWith(x => _messagingFactory.CreateTopicClient(x.Result.Path));
        }
예제 #13
0
        public Topic(string connectionStringName, string name)
            : base(connectionStringName)
        {
            Name = name;
            CreateTopicTransient(name);

            Client = MessagingFactory.CreateTopicClient(name);
        }
예제 #14
0
        public static TopicClient CreateTopicClient(string topicPath)
        {
            TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);

            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty);
            MessagingFactory messagingFactory = MessagingFactory.Create(uri, tokenProvider);

            return(messagingFactory.CreateTopicClient(topicPath));
        }
예제 #15
0
        public HeaterCommunication()
        {
            var topicNameSend = "businessrulestofieldgateway";

            _topicNameReceive = "fieldgatewaytobusinessrules";
            _namespaceMgr     = NamespaceManager.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));
            _factory          = MessagingFactory.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"));
            _client           = _factory.CreateTopicClient(topicNameSend);
        }
        static void Main(string[] args)
        {
            // The connection string for the RootManageSharedAccessKey can be accessed from the Azure portal
            // by selecting the SB namespace and clicking on "Connection Information"
            Console.Write("Enter your connection string for the RootManageSharedAccessKey for your Service Bus namespace: ");
            nsConnectionString = Console.ReadLine();

            ///////////////////////////////////////////////////////////////////////////////////////
            // Create a topic with a SAS Listen rule and an associated subscription
            ///////////////////////////////////////////////////////////////////////////////////////
            NamespaceManager nm = NamespaceManager.CreateFromConnectionString(nsConnectionString);

            contosoTListenRule = new SharedAccessAuthorizationRule("contosoTListenKey",
                                                                   SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                   new[] { AccessRights.Listen });
            TopicDescription td = new TopicDescription(topicPath);

            td.Authorization.Add(contosoTListenRule);
            nm.CreateTopic(td);
            nm.CreateSubscription(topicPath, subscriptionName);

            ///////////////////////////////////////////////////////////////////////////////////////
            // Send a message to the topic
            // Note that this uses the connection string for RootManageSharedAccessKey
            // configured on the namespace root
            ///////////////////////////////////////////////////////////////////////////////////////
            MessagingFactory sendMF      = MessagingFactory.CreateFromConnectionString(nsConnectionString);
            TopicClient      tc          = sendMF.CreateTopicClient(topicPath);
            BrokeredMessage  sentMessage = CreateHelloMessage();

            tc.Send(sentMessage);
            Console.WriteLine("Sent Hello message to topic: ID={0}, Body={1}.", sentMessage.MessageId, sentMessage.GetBody <string>());

            ///////////////////////////////////////////////////////////////////////////////////////
            // Generate a SAS token scoped to a subscription using the SAS rule with
            // a Listen right configured on the Topic & TTL of 1 day
            ///////////////////////////////////////////////////////////////////////////////////////
            ServiceBusConnectionStringBuilder csBuilder = new ServiceBusConnectionStringBuilder(nsConnectionString);
            IEnumerable <Uri> endpoints         = csBuilder.Endpoints;
            string            subscriptionUri   = endpoints.First <Uri>().ToString() + topicPath + "/subscriptions/" + subscriptionName;
            string            subscriptionToken = SASTokenGenerator.GetSASToken(subscriptionUri,
                                                                                contosoTListenRule.KeyName, contosoTListenRule.PrimaryKey, TimeSpan.FromDays(1));

            ///////////////////////////////////////////////////////////////////////////////////////
            // Use the SAS token scoped to a subscription to receive the messages
            ///////////////////////////////////////////////////////////////////////////////////////
            MessagingFactory   listenMF        = MessagingFactory.Create(endpoints, new StaticSASTokenProvider(subscriptionToken));
            SubscriptionClient sc              = listenMF.CreateSubscriptionClient(topicPath, subscriptionName);
            BrokeredMessage    receivedMessage = sc.Receive(TimeSpan.FromSeconds(10));

            Console.WriteLine("Received message from subscription: ID = {0}, Body = {1}.", receivedMessage.MessageId, receivedMessage.GetBody <string>());

            ///////////////////////////////////////////////////////////////////////////////////////
            // Clean-up
            ///////////////////////////////////////////////////////////////////////////////////////
            nm.DeleteTopic(topicPath);
        }
        private void CreateAssetIfNotExists(string topicName)
        {
            if (!_namespaceManager.TopicExists(topicName))
            {
                _namespaceManager.CreateTopic(topicName);
            }

            _topicClient = _messagingFactory.CreateTopicClient(topicName);
        }
        public async static Task <TopicClient> EnsureTopicAsync(this MessagingFactory factory, TopicDescription topicDescription)
        {
            await new NamespaceManager(factory.Address, factory.GetSettings().TokenProvider)
            .TryCreateEntity(
                mgr => TopicCreateAsync(mgr, topicDescription),
                mgr => TopicShouldExistAsync(mgr, topicDescription)).ConfigureAwait(false);

            return(factory.CreateTopicClient(topicDescription.Path));
        }
예제 #19
0
        private TopicClient CreateTopicClient(string topicName)
        {
            var td = new TopicDescription(topicName);

            if (!_namespaceManager.TopicExists(topicName))
            {
                _namespaceManager.CreateTopic(td);
            }
            return(_messageFactory.CreateTopicClient(topicName));
        }
        public TopicClient CreateTopicClient(string nsName, string topicName, string keyName, string key)
        {
            Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri("sb", nsName, string.Empty);

            TokenProvider tp = GetTokenProvider(keyName, key);

            MessagingFactory mf = MessagingFactory.Create(runtimeUri, tp);

            return(mf.CreateTopicClient(topicName));
        }
 /// <summary>
 /// Asynchronously create a new message sender.
 /// </summary>
 public static Task <AzureServiceBus.MessageSender> TryCreateMessageSender(
     [NotNull] this MessagingFactory mf,
     [NotNull] AzureServiceBus.TopicDescription description)
 {
     return(Task.Factory.StartNew(() =>
     {
         TopicClient s = mf.CreateTopicClient(description.Path);
         return new MessageSenderImpl(s) as AzureServiceBus.MessageSender;
     }));
 }
예제 #22
0
        public Topic(string connectionStringName, string pairedConnectionStringName, string name)
            : base(connectionStringName)
        {
            Name = name;

            CreatePairedNamespaceManager(pairedConnectionStringName);
            CreateTopicTransient(name);

            Client = MessagingFactory.CreateTopicClient(name);
        }
예제 #23
0
        public HorseNotification()
        {
            namespaceManager = NamespaceManager.Create();


            DeleteTopicsAndSubscriptions(namespaceManager);
            CreateTopicsAndSubscriptions(namespaceManager);

            MessagingFactory factory = MessagingFactory.Create();

            myTopicClient = factory.CreateTopicClient(topicDescription.Path);
        }
예제 #24
0
        async Task SendMessagesToTopicAsync(MessagingFactory messagingFactory)
        {
            // Create client for the topic.
            var topicClient = messagingFactory.CreateTopicClient(TopicName);

            // Create a message sender from the topic client.

            Console.WriteLine("\nSending orders to topic.");

            // Now we can start sending orders.
            await Task.WhenAll(
                SendOrder(topicClient, new Order()),
                SendOrder(topicClient, new Order {
                Color = "blue", Quantity = 5, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "red", Quantity = 10, Priority = "high"
            }),
                SendOrder(topicClient, new Order {
                Color = "yellow", Quantity = 5, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "blue", Quantity = 10, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "blue", Quantity = 5, Priority = "high"
            }),
                SendOrder(topicClient, new Order {
                Color = "blue", Quantity = 10, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "red", Quantity = 5, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "red", Quantity = 10, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "red", Quantity = 5, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "yellow", Quantity = 10, Priority = "high"
            }),
                SendOrder(topicClient, new Order {
                Color = "yellow", Quantity = 5, Priority = "low"
            }),
                SendOrder(topicClient, new Order {
                Color = "yellow", Quantity = 10, Priority = "low"
            })
                );

            Console.WriteLine("All messages sent.");
        }
예제 #25
0
        private static void ServiceTopicSend()
        {
            var topicName  = "topicdemo";
            var connection = "Endpoint=sb://<yournamespacehere>.servicebus.windows.net/;SharedAccessKeyName=Sender;SharedAccessKey=<yourkeyhere>;TransportType=Amqp";

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection);

            TopicClient topic = factory.CreateTopicClient(topicName);

            for (var i = 0; i < 100; i++)
            {
                Console.WriteLine(i);
                topic.Send(new BrokeredMessage("topic message" + i));
            }
        }
예제 #26
0
        public void PublishMessageOfStockItem()
        {
            //arrange
            var stockItem            = new StockItem("ABC", 1, "FCLondon", "DHL");
            var stockMessagerService = new StockMessagerService(sender);
            var topicClient          = factory.CreateTopicClient("stocklevels");
            var subscriptionClient   = factory.CreateSubscriptionClient(topicClient.Path, "GBWarehouseStockLevels");

            stockMessagerService.SendMessageAsync(stockItem).Wait();
            var message      = subscriptionClient.Receive();
            var streamReader = new StreamReader(message.GetBody <Stream>());
            var result       = JsonConvert.DeserializeObject <StockItem>(streamReader.ReadToEnd());

            //assert
            Assert.That(result.Sku.Equals("ABC"));
        }
예제 #27
0
        private void SubmitJob(Job job)
        {
            // Create a TopicClient for Job Topic.
            JobTopicClient = Factory.CreateTopicClient(TopicPath);

            var message = new BrokeredMessage(job);

            // Promote properties.
            message.Properties.Add("JobType", job.JobType.ToString());

            // Set the CorrelationId to the region.
            message.CorrelationId = job.JobType.ToString();

            // Send the message.
            JobTopicClient.Send(message);
        }
        public async Task Send()
        {
            MessagingFactory factory     = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey]);
            TopicClient      topicClient = factory.CreateTopicClient(Helpers.BasicTopicName);

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

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

            await topicClient.SendAsync(message);
        }
예제 #29
0
        public void Publish <T_message>(T_message message)
        {
            var messageType = typeof(T_message);
            var metadata    = _configuration.MessageDefinitions.FirstOrDefault(md => md.MessageType == messageType && md.MessageAction == Core.MessageAction.Event);

            if (metadata != null)
            {
                //CreateTopic(metadata.QueueName);
                var             body            = _serialiser.Serialise(message);
                BrokeredMessage brokeredMessage = new BrokeredMessage(body);

                var         destination = GetDestinationName(metadata.QueueName, true);
                TopicClient topicClient = _messageFactory.CreateTopicClient(destination);
                topicClient.Send(brokeredMessage);
            }
        }
예제 #30
0
        internal static void ConfigureServiceHUB()
        {
            if (AppConfiguration.Settings.ServiceBUSConenctionString != string.Empty)
            {
                try
                {
                    ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder(AppConfiguration.Settings.ServiceBUSConenctionString);

                    MessagingFactory messageFactory   = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
                    NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

                    string QueueName = AppConfiguration.Settings.ServiceBUSQueueName;

                    if (!namespaceManager.TopicExists(QueueName))
                    {
                        namespaceManager.CreateTopic(QueueName);
                    }

                    NSBQClient = messageFactory.CreateTopicClient(QueueName);
                }
                catch (Exception ex)
                {
                    AppLogging.Instance.Error("Error: Connecting to ServiceBus ", ex);
                }
            }
            if (AppConfiguration.Settings.NotificationHubServerConenctionString != string.Empty)
            {
                try
                {
                    ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder(AppConfiguration.Settings.NotificationHubServerConenctionString);
                    MessagingFactory messageFactory   = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
                    NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

                    string NotificationHubName = AppConfiguration.Settings.NotificationHubName;

                    //if (namespaceManager.NotificationHubExists(NotificationHubName))
                    //{

                    NNHClient = NotificationHubClient.CreateClientFromConnectionString(connBuilder.ToString(), AppConfiguration.Settings.NotificationHubName);
                    //}
                }
                catch (Exception ex)
                {
                    AppLogging.Instance.Error("Error: Connecting to NotificationHub ", ex);
                }
            }
        }
예제 #31
0
        public TopicWorker(string connectionString, string topicName)
        {
            Logger.Debug("Starting LongRunningJob");
            _connectionString = connectionString;
            _topicName        = topicName;

            Logger.Debug("Using Topic {0}", _topicName);
            Logger.Debug("Using ConnectionString {0} from the AppSetting: {1}", _connectionString, _connectionString);

            Logger.Debug("Creating MessagingFactory");
            MessagingFactory messageFactory = MessagingFactory.CreateFromConnectionString(_connectionString);

            Logger.Debug("Creating CreateTopicClient");
            _myTopicClient = messageFactory.CreateTopicClient(_topicName);

            Logger.Debug("Creating CreateTopicClient");
            _mySubscriptionClient = messageFactory.CreateSubscriptionClient(_topicName, _topicName);
        }
예제 #32
0
        public async Task <ActionResult> Index(VideoModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var cloudStorageAccount = CloudStorageAccount.Parse(_azureStorageConnectionString);
            var cloudBlobClient     = cloudStorageAccount.CreateCloudBlobClient();
            var container           = cloudBlobClient.GetContainerReference("uploads");
            await container.CreateIfNotExistsAsync();

            var blob = container.GetBlockBlobReference(System.IO.Path.GetFileName(model.File.FileName));
            await blob.UploadFromStreamAsync(model.File.InputStream);

            var newVideo = new BackOffice.Common.Video
            {
                Description  = model.Description,
                Id           = model.Id,
                OriginalUrl  = blob.Uri.ToString(),
                Title        = model.Name,
                UploadedDate = DateTime.UtcNow
            };

            NamespaceManager nsMgr = NamespaceManager.CreateFromConnectionString(_azureServiceBusConnectionString);
            TopicDescription topic = null;

            if (!(await nsMgr.TopicExistsAsync("NewMediaUploaded")))
            {
                topic = await nsMgr.CreateTopicAsync("NewMediaUploaded");
            }
            else
            {
                topic = await nsMgr.GetTopicAsync("NewMediaUploaded");
            }

            MessagingFactory factory     = MessagingFactory.CreateFromConnectionString(_azureServiceBusConnectionString);
            TopicClient      topicClient = factory.CreateTopicClient(topic.Path);

            await topicClient.SendAsync(new BrokeredMessage(newVideo));

            return(RedirectToAction("Index", "Home"));
        }
예제 #33
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, int maxNumberRetry, RetryStrategy retryStrategy)
        {
            this.settings = settings;
            this.topic = topic;

            this.retryStrategy = retryStrategy;
            this.maxNumberRetry = maxNumberRetry;

            this.messagingFactory = MessagingFactory.CreateFromConnectionString(settings.ConnectionString);
            this.topicClient = messagingFactory.CreateTopicClient(this.topic);

            this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(this.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);
            };
        }
        public async Task SetupAsync(Type[] allMessageTypes, Type[] recievingMessageTypes)
        {
            _logger.Debug("Starting the setup of AzureServicebusTransport...");

            _namespaceManager = NamespaceManager.CreateFromConnectionString(_configuration.GetConnectionString());
            _messagingFactory = MessagingFactory.CreateFromConnectionString(_configuration.GetConnectionString());

            _messageTypes = allMessageTypes;

            var sendCommandTypes = _messageTypes
                .Where(t => typeof (IBusCommand)
                    .IsAssignableFrom(t));

            var sendEventTypes = _messageTypes
                .Where(t => typeof(IBusEvent)
                    .IsAssignableFrom(t));

            var recieveCommandTypes = recievingMessageTypes
                .Where(t => typeof(IBusCommand)
                    .IsAssignableFrom(t));

            var recieveEventTypes = recievingMessageTypes
                .Where(t => typeof(IBusEvent)
                    .IsAssignableFrom(t));

            if (_configuration.GetEnableTopicAndQueueCreation())
            {
                foreach (var type in sendCommandTypes)
                {
                    var path = PathFactory.QueuePathFor(type);
                    if (!_namespaceManager.QueueExists(path))
                        await _namespaceManager.CreateQueueAsync(path);

                    var client = _messagingFactory.CreateQueueClient(path);
                    client.PrefetchCount = 10; //todo;: in config?

                    var eventDrivenMessagingOptions = new OnMessageOptions
                    {
                        AutoComplete = true, //todo: in config?
                        MaxConcurrentCalls = 10 //todo: in config?
                    };
                    eventDrivenMessagingOptions.ExceptionReceived += OnExceptionReceived;
                    client.OnMessageAsync(OnMessageRecieved, eventDrivenMessagingOptions);

                    if (!_queues.TryAdd(type, client))
                    {
                        _logger.Error("Could not add the queue with type: {0}", type.FullName);
                    }
                }
                foreach (var type in sendEventTypes)
                {
                    var path = PathFactory.TopicPathFor(type);
                    if (!_namespaceManager.TopicExists(path))
                        _namespaceManager.CreateTopic(path);

                    var client = _messagingFactory.CreateTopicClient(path);

                    if (!_topics.TryAdd(type, client))
                    {
                        _logger.Error("Could not add the topic with type: {0}", type.FullName);
                    }


                }
            }

            _logger.Debug("Setup of AzureServicebusTransport completed!");

            throw new NotImplementedException();
        }
예제 #35
0
        static void SendMessagesToTopic(MessagingFactory messagingFactory)
        {
            // Create client for the topic.
            TopicClient topicClient = messagingFactory.CreateTopicClient(Program.TopicName);

            // Create a message sender from the topic client.

            Console.WriteLine("\nSending orders to topic.");

            // Now we can start sending orders.
            SendOrder(topicClient, new Order());
            SendOrder(topicClient, new Order() { Color = "blue", Quantity = 5, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "red", Quantity = 10, Priority = "high" });
            SendOrder(topicClient, new Order() { Color = "yellow", Quantity = 5, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "blue", Quantity = 10, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "blue", Quantity = 5, Priority = "high" });
            SendOrder(topicClient, new Order() { Color = "blue", Quantity = 10, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "red", Quantity = 5, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "red", Quantity = 10, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "red", Quantity = 5, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "yellow", Quantity = 10, Priority = "high" });
            SendOrder(topicClient, new Order() { Color = "yellow", Quantity = 5, Priority = "low" });
            SendOrder(topicClient, new Order() { Color = "yellow", Quantity = 10, Priority = "low" });

            Console.WriteLine("All messages sent.");
        }
        async Task SendMessagesToTopicAsync(MessagingFactory messagingFactory)
        {
            // Create client for the topic.
            var topicClient = messagingFactory.CreateTopicClient(TopicName);

            // Create a message sender from the topic client.

            Console.WriteLine("\nSending orders to topic.");

            // Now we can start sending orders.
            await Task.WhenAll(
                SendOrder(topicClient, new Order()),
                SendOrder(topicClient, new Order { Color = "blue", Quantity = 5, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "red", Quantity = 10, Priority = "high" }),
                SendOrder(topicClient, new Order { Color = "yellow", Quantity = 5, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "blue", Quantity = 10, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "blue", Quantity = 5, Priority = "high" }),
                SendOrder(topicClient, new Order { Color = "blue", Quantity = 10, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "red", Quantity = 5, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "red", Quantity = 10, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "red", Quantity = 5, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "yellow", Quantity = 10, Priority = "high" }),
                SendOrder(topicClient, new Order { Color = "yellow", Quantity = 5, Priority = "low" }),
                SendOrder(topicClient, new Order { Color = "yellow", Quantity = 10, Priority = "low" })
                );

            Console.WriteLine("All messages sent.");
        }
 //Criar o TopicClient a partir do uri do serviço, do tokenProvider e do TopicDescription
 private static TopicClient CreateTopicClient(Uri serviceUri, TokenProvider tokenProvider, TopicDescription myTopic, out MessagingFactory factory)
 {
     factory = MessagingFactory.Create(serviceUri, tokenProvider);
     return factory.CreateTopicClient(myTopic.Path);
 }
 public TopicClient Create(string topic, MessagingFactory factory)
 {
     return factory.CreateTopicClient(topic);
 }