예제 #1
0
        public override void Run()
        {
            // Retrieve Settings from App.Config
            string servicePath      = ConfigurationManager.AppSettings["ServicePath"];
            string serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"];
            string issuerName       = ConfigurationManager.AppSettings["IssuerName"];
            string issuerSecret     = ConfigurationManager.AppSettings["IssuerSecret"];

            // Construct a Service Bus URI
            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath);

            // Create a Behavior for the Credentials
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

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


            // Create the Service Host
            host = new ServiceHost(typeof(EchoService), uri);
            ContractDescription contractDescription = ContractDescription.GetContract(typeof(IEchoContract), typeof(EchoService));
            ServiceEndpoint     serviceEndPoint     = new ServiceEndpoint(contractDescription);

            serviceEndPoint.Address = new EndpointAddress(uri);
            serviceEndPoint.Binding = new NetTcpRelayBinding();
            serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);
            host.Description.Endpoints.Add(serviceEndPoint);

            // Open the Host
            host.Open();

            while (true)
            {
                //Do Nothing
            }
        }
예제 #2
0
        /// <summary>
        /// Setup the host up and running in the console application.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Configuration keys
            string issuerSecret           = ConfigurationManager.AppSettings[Consts.ServiceBusSecretKey];
            string serviceNamespaceDomain = ConfigurationManager.AppSettings[Consts.ServiceBusNamespaceKey];

            // Here's our custom service receiving messages from the cloud
            ServiceHost sh = new ServiceHost(typeof(SiteRequestService));

            // Let's add only service end point to service bus, you could add also local end point, if needed. Keep it simple for this one.
            sh.AddServiceEndpoint(
                typeof(ISiteRequest), new NetTcpRelayBinding(),
                ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "solver"))
            .Behaviors.Add(new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider("owner", issuerSecret)
            });
            sh.Open();

            // Just to keep it hanging in the service... could be hosted for example as windows service for better handling
            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();

            // Enter pressed, let's close up
            sh.Close();
        }
예제 #3
0
        /// <summary>
        /// Create the namespace manager which gives
        /// you access to management operations.
        /// </summary>
        /// <returns></returns>
        public static NamespaceManager CreateNamespaceManager()
        {
            var uri = ServiceBusEnvironment.CreateServiceUri("sb", Namespace, string.Empty);
            var tP  = TokenProvider.CreateSharedSecretTokenProvider(IssuerName, IssuerKey);

            return(new NamespaceManager(uri, tP));
        }
예제 #4
0
        private void StartBus()
        {
            if (started)
            {
                return;
            }

            endpointConfig = cfgMgr.GetEndpointConfig(Username, Password);
            if (endpointConfig.Error)
            {
                throw new ApplicationException(endpointConfig.ErrorMessage);
            }
            sh       = new ServiceHost(typeof(OrderService));
            endpoint = sh.AddServiceEndpoint(
                typeof(IOrderService),
                new NetTcpRelayBinding(),
                ServiceBusEnvironment.CreateServiceUri("sb", endpointConfig.ServiceBusNamespace, "order"));

            endpoint.Behaviors.Add(new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(
                    endpointConfig.Issuer,
                    endpointConfig.SecretKey)
            });
            sh.Open();
            started = true;
        }
예제 #5
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);
        }
        private static ChannelFactory <T> CreateServiceBusClientChannelFactory <T>(string serviceNamespace, string servicePath, string issuerName, string issuerSecret, Binding binding)
        {
            Guard.ArgumentNotNullOrEmptyString(serviceNamespace, "serviceNamespace");
            Guard.ArgumentNotNullOrEmptyString(servicePath, "servicePath");
            Guard.ArgumentNotNullOrEmptyString(issuerName, "issuerName");
            Guard.ArgumentNotNullOrEmptyString(issuerSecret, "issuerSecret");
            Guard.ArgumentNotNull(binding, "binding");

            var callToken = TraceManager.DebugComponent.TraceIn(serviceNamespace, servicePath, binding.Name);

            var address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath);
            var credentialsBehaviour = new TransportClientEndpointBehavior()
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret)
            };
            var endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), binding, new EndpointAddress(address));

            endpoint.Behaviors.Add(credentialsBehaviour);

            // Apply default endpoint configuration.
            ServiceEndpointConfiguration.ConfigureDefaults(endpoint);

            ChannelFactory <T> clientChannelFactory = new ChannelFactory <T>(endpoint);

            TraceManager.DebugComponent.TraceOut(callToken, endpoint.Address.Uri);

            return(clientChannelFactory);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("CloudTrace Console");
            Console.WriteLine("Connecting ...");

            //Retrieve Settings from App.Config
            string servicePath      = ConfigurationManager.AppSettings["CloudTraceServicePath"];
            string serviceNamespace = ConfigurationManager.AppSettings["CloudTraceServiceNamespace"];
            string issuerName       = ConfigurationManager.AppSettings["CloudTraceIssuerName"];
            string issuerSecret     = ConfigurationManager.AppSettings["CloudTraceIssuerSecret"];

            //Construct a Service Bus URI
            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath);

            //Create a Behavior for the Credentials
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

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

            //Create the Service Host
            ServiceHost     host            = new ServiceHost(typeof(TraceService), uri);
            ServiceEndpoint serviceEndPoint = host.AddServiceEndpoint(typeof(ITraceContract), new NetEventRelayBinding(), String.Empty);

            serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);

            //Open the Host
            host.Open();
            Console.WriteLine("Connected To: " + uri.ToString());
            Console.WriteLine("Hit [Enter] to exit");

            //Wait Until the Enter Key is Pressed and Close the Host
            Console.ReadLine();
            host.Close();
        }
예제 #8
0
        static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "PingService");

            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

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

            ServiceHost host = new ServiceHost(typeof(PingService), address);

            foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }

            host.Open();

            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();

            host.Close();
        }
        static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();

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

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "HelloService");

            ServiceHost host = new ServiceHost(typeof(HelloService), address);

            host.Description.Endpoints[0].Behaviors.Add(relayCredentials);
            host.Open();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            host.Close();
        }
        public Consumer()
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            // Configure queue settings.
            this.queueDescription = new QueueDescription(MyQueuePath);
            // Setting Max Size and TTL for demonstration purpose
            // but can be changed per user discretion to suite their system needs.
            // Refer service bus documentation to understand the limitations.
            // Setting Queue max size to 1GB where as default Max Size is 5GB.
            this.queueDescription.MaxSizeInMegabytes = 1024;
            // Setting message TTL to 5 days where as default TTL is 14 days.
            this.queueDescription.DefaultMessageTimeToLive = TimeSpan.FromDays(5);

            // Create management credentials.
            this.credential = new TransportClientEndpointBehavior()
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret)
            };

            // Create the URI for the queue.
            this.namespaceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, String.Empty);
            Console.WriteLine("Service Bus Namespace Uri address '{0}'", this.namespaceUri.AbsoluteUri);
        }
예제 #11
0
        void EnsureOpen()
        {
            lock (this.openMutex)
            {
                if (!this.isOpen)
                {
                    var messagingServiceUri  = ServiceBusEnvironment.CreateServiceUri("sb", this.serviceBusNamespace, string.Empty);
                    var managementServiceUri = ServiceBusEnvironment.CreateServiceUri("https", this.serviceBusNamespace, string.Empty);
                    var tokenProvider        = TokenProvider.CreateSharedSecretTokenProvider(this.serviceBusAccount, this.serviceBusAccountKey);
                    this.namespaceManager = new NamespaceManager(managementServiceUri, tokenProvider);
                    for (var i = 0; i < this.NumberOfTopics; i++)
                    {
                        this.EnsurePartitionTopicSubscription(tokenProvider, messagingServiceUri, i);
                    }

                    for (var topicNumber = 0; topicNumber < this.NumberOfTopics; topicNumber++)
                    {
                        try
                        {
                            subscriptionClients[topicNumber].BeginReceive(this.DoneReceivingFromSubscription, new object[] { subscriptionClients[topicNumber], topicNumber });
                        }
                        catch (Exception e)
                        {
                            Trace.TraceError
                                ("Error attempting to receive from subscription '{0}/{1}' with {2}",
                                subscriptionClients[topicNumber].TopicPath,
                                subscriptionClients[topicNumber].Name,
                                e.ToString());
                            throw;
                        }
                    }
                    this.isOpen = true;
                }
            }
        }
예제 #12
0
        static void SetServiceBusCredentials(IEnumerable <ServiceEndpoint> endpoints, string issuer, string secret)
        {
            TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();
            TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer, secret);

            SetServiceBusCredentials(endpoints, tokenProvider);
        }
예제 #13
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);
        }
예제 #14
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();
        }
        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));
        }
예제 #16
0
        private static TokenProvider CreateTokenProvider(IEnumerable <Uri> stsEndpoints, string issuerName, string issuerKey, string sharedAccessKeyName, string sharedAccessKey, string windowsDomain, string windowsUser, SecureString windowsPassword, string oauthDomain, string oauthUser, SecureString oauthPassword)
        {
            if (!string.IsNullOrWhiteSpace(sharedAccessKey))
            {
                return(TokenProvider.CreateSharedAccessSignatureTokenProvider(sharedAccessKeyName, sharedAccessKey));
            }
            if (!string.IsNullOrWhiteSpace(issuerName))
            {
                if (stsEndpoints == null || !stsEndpoints.Any <Uri>())
                {
                    return(TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey));
                }
                return(TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey, stsEndpoints.First <Uri>()));
            }
            bool flag  = (stsEndpoints == null ? false : stsEndpoints.Any <Uri>());
            bool flag1 = (string.IsNullOrWhiteSpace(windowsUser) || windowsPassword == null ? false : windowsPassword.Length > 0);
            bool flag2 = (string.IsNullOrWhiteSpace(oauthUser) || oauthPassword == null ? false : oauthPassword.Length > 0);

            if (!flag)
            {
                return(null);
            }
            if (flag2)
            {
                return(TokenProvider.CreateOAuthTokenProvider(stsEndpoints, (string.IsNullOrWhiteSpace(oauthDomain) ? new NetworkCredential(oauthUser, oauthPassword) : new NetworkCredential(oauthUser, oauthPassword, oauthDomain))));
            }
            if (!flag1)
            {
                return(TokenProvider.CreateWindowsTokenProvider(stsEndpoints));
            }
            return(TokenProvider.CreateWindowsTokenProvider(stsEndpoints, (string.IsNullOrWhiteSpace(windowsDomain) ? new NetworkCredential(windowsUser, windowsPassword) : new NetworkCredential(windowsUser, windowsPassword, windowsDomain))));
        }
예제 #17
0
        public void Initialize()
        {
            var retryStrategy    = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy      = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

            this.settings.Topics.AsParallel().ForAll(topic =>
            {
                retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic));
                topic.Subscriptions.AsParallel().ForAll(subscription =>
                {
                    retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription));
                    retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, topic, subscription));
                });
            });

            // Execute migration support actions only after all the previous ones have been completed.
            foreach (var topic in this.settings.Topics)
            {
                foreach (var action in topic.MigrationSupport)
                {
                    retryPolicy.ExecuteAction(() => UpdateSubscriptionIfExists(namespaceManager, topic, action));
                }
            }

            this.initialized = true;
        }
예제 #18
0
        static void Main(string[] args)
        {
            Console.Write("Initialising the Service Bus from Config ");

            TransportClientEndpointBehavior sharedSecretServicebusCredential = new TransportClientEndpointBehavior();

            sharedSecretServicebusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(
                ConfigurationSettings.AppSettings["IssuerName"],
                ConfigurationSettings.AppSettings["IssuerSecret"]);

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationSettings.AppSettings["ServiceNamespace"], "DriverService");

            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
            ServiceHost       host = new ServiceHost(typeof(DriverService), address);
            IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(serviceRegistrySettings);
                endpoint.Behaviors.Add(sharedSecretServicebusCredential);
            }

            host.Open();
            Console.WriteLine("Service address: {0}", address);
            Console.WriteLine("Press any key to stop");
            Console.ReadLine();

            host.Close();
        }
 public static void CreateTopic(this ServiceBusSettings settings, string topic)
 {
     new NamespaceManager(
         ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
         TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
     .CreateTopic(topic);
 }
        public static NamespaceManager GetServiceBusNamespaceClient(SessionState sessionState)
        {
            if (serviceBusNamespaceClient != null)
            {
                return(serviceBusNamespaceClient);
            }

            if (string.IsNullOrEmpty(Context.issuerSecret) || string.IsNullOrEmpty(Context.issuerName) || string.IsNullOrEmpty(Context.serviceBusNamespace))
            {
                ReadVariables(sessionState);
            }

            if (string.IsNullOrEmpty(issuerSecret) || string.IsNullOrEmpty(issuerName) || string.IsNullOrEmpty(serviceBusNamespace))
            {
                throw new ArgumentException("Use Set-Credentials commandlet to set you ACS creds before attempting to navigate your namespace, you can alternatively modify " +
                                            "powershell config at %SystemRoot%\\WindowsPowerShell\\v1.0\\powershell.exe.config and add to the appSettings the following keys" +
                                            "\n\n<add key=\"IssuerName\" value=\"YourIssuerName\"/>" +
                                            "\n<add key=\"IssuerSecret\" value=\"YourIssuerSecret\"/>" +
                                            "\n<add key=\"Namespace\" value=\"YourNamespace\"/>");
            }

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

            return(new NamespaceManager(ServiceBusEnvironment.CreateServiceUri("https", serviceBusNamespace, String.Empty), credentials));
        }
        static void Main(string[] args)
        {
            try
            {
                TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(ServiceIdentity2, ServiceIdentityKey2);
                Uri           serviceUri  = ServiceBusEnvironment.CreateServiceUri("sb", ServiceBusNamespace, string.Empty);

                // Send messages to the queue with the QueueClient user
                Send(serviceUri, credentials);

                // Listen to the queue with the owner user
                credentials = TokenProvider.CreateSharedSecretTokenProvider(ServiceIdentityName1, ServiceIdentityKey1);
                Receive(serviceUri, credentials);

                // Listen to the queue with the QueueClient user - should throw an unauthorized exception
                credentials = TokenProvider.CreateSharedSecretTokenProvider(ServiceIdentity2, ServiceIdentityKey2);
                Receive(serviceUri, credentials);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();
        }
예제 #22
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)
            { }
        }
예제 #23
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);
        }
        public static MessageReceiver CreateMessageReceiver(this ServiceBusSettings settings, string topic, string subscription)
        {
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);

            return(messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(topic, subscription)));
        }
        public static SubscriptionClient CreateSubscriptionClient(this ServiceBusSettings settings, string topic, string subscription, ReceiveMode mode = ReceiveMode.PeekLock)
        {
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);

            return(messagingFactory.CreateSubscriptionClient(topic, subscription, mode));
        }
        public static TopicClient CreateTopicClient(this ServiceBusSettings settings, string topic)
        {
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider);

            return(messagingFactory.CreateTopicClient(topic));
        }
예제 #27
0
        public static void VerifyBuffer(string bufferAddress, string issuer, string secret)
        {
            TransportClientEndpointBehavior creds = new TransportClientEndpointBehavior();

            creds.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer, secret);

            VerifyBuffer(bufferAddress, creds);
        }
예제 #28
0
        private NamespaceManager GetNamespaceManager(string ns, string issuer, string secret,
                                                     string scheme = SCHEME_SERVICE_BUS, string path = null)
        {
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(issuer, secret);
            var namespaceAddress = ServiceBusEnvironment.CreateServiceUri(scheme, ns, path ?? string.Empty);

            return(new NamespaceManager(namespaceAddress, tokenProvider));
        }
 public TransportClientEndpointBehavior GetTransportBehavior()
 {
     return(new TransportClientEndpointBehavior
     {
         TokenProvider =
             TokenProvider.CreateSharedSecretTokenProvider(IssuerName, IssuerSecret)
     });
 }
 public static void TryDeleteSubscription(this ServiceBusSettings settings, string topic, string subscription)
 {
     try {
         new NamespaceManager(
             ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath),
             TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey))
         .DeleteSubscription(topic, subscription);
     } catch { }
 }