Example #1
0
        private static void MessageOnly()
        {
            var transportClientEndpointBehavior = new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sendKeyName, sendKeyValue)
            };

            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, _queueName);

            var netMessagingBinding = new NetMessagingBinding
            {
                PrefetchCount = 10,
                TransportSettings = new NetMessagingTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromSeconds(0)
                }
            };

            var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IRequest)),
                                                        netMessagingBinding,
                                                        new EndpointAddress(serviceUri));
            serviceEndpoint.Behaviors.Add(transportClientEndpointBehavior);
            var channelFactory = new ChannelFactory<IRequest>(serviceEndpoint);
            var channel = channelFactory.CreateChannel();
            Console.WriteLine("Press any key to send message...");
            Console.ReadKey();
            channel.SendMessage("Hello from wcf client");
            Console.WriteLine("Message sent");
            Console.ReadKey();
        }
        /// <summary>
        /// Creates a new <see cref="ServiceInstanceListener"/> capable of listening to a queue containing
        /// WCF queued messages for the given <typeparamref name="TServiceContract"/>.
        /// </summary>
        /// <param name="wcfServiceObject">
        /// The WCF service instance to be used for servicing requests. Must be a stateless service. Must not be null.
        /// </param>
        /// <param name="netMessagingBinding">
        /// The binding to be used to listen to the queue. Must not be null.
        /// </param>
        /// <param name="connectionString">
        /// The connection string to be used for connecting to the Azure Service Bus. Must not be null or empty.
        /// </param>
        /// <param name="queueNameProvider">
        /// A <see cref="Func{TResult}"/> returning the name of the queue to be used. If null, the default behavior
        /// will be to use the name of <typeparamref name="TServiceContract"/>.
        /// </param>
        /// <param name="endpointBehaviors">
        /// The <see cref="IEndpointBehavior"/>s that are to be applied to the generated WCF <see cref="ServiceHost"/>
        /// endpoints.
        /// </param>
        /// <typeparam name="TServiceContract">
        /// The interface that bears a <see cref="ServiceContractAttribute"/> and <see cref="OperationContractAttribute"/>s
        /// on its methods to denote it as a ServiceModel (WCF) service.
        /// </typeparam>
        /// <exception cref="ArgumentException">
        /// Thrown if <paramref name="connectionString"/> is null or empty.
        /// </exception>
        /// <returns>
        /// A new <see cref="ServiceInstanceListener"/> configured to listen to an Azure Service Bus for WCF
        /// messages for the given <typeparamref name="TServiceContract"/> service contract. Guaranteed not to
        /// be null.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="wcfServiceObject"/> or <see cref="NetMessagingBinding"/> are null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if the endpoint for the Service Bus queue's containing Azure Service Bus namespace could
        /// not be resolved from the connection string.
        /// </exception>
        public static ServiceInstanceListener CreateQueuedServiceBusListener <TServiceContract>(
            TServiceContract wcfServiceObject,
            NetMessagingBinding netMessagingBinding,
            string connectionString,
            Func <string> queueNameProvider = null,
            params IEndpointBehavior[] endpointBehaviors)
        {
            if (wcfServiceObject == null)
            {
                throw new ArgumentNullException(nameof(wcfServiceObject));
            }

            if (netMessagingBinding == null)
            {
                throw new ArgumentNullException(nameof(netMessagingBinding));
            }

            if (String.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Must not be null or empty", nameof(connectionString));
            }

            return(new ServiceInstanceListener(
                       createCommunicationListener: context => ResolveCommunicationListener(
                           context: context,
                           wcfServiceObject: wcfServiceObject,
                           netMessagingBinding: netMessagingBinding,
                           queueNameProvider: queueNameProvider,
                           connectionStringResolver: c => connectionString,
                           behaviors: endpointBehaviors
                           )
                       ));
        }
Example #3
0
        protected override void OnApplyConfiguration(Binding binding)
        {
            NetMessagingBinding prefetchCount = (NetMessagingBinding)binding;

            prefetchCount.PrefetchCount      = this.PrefetchCount;
            prefetchCount.SessionIdleTimeout = this.SessionIdleTimeout;
            this.TransportSettings.ApplyTo(prefetchCount.TransportSettings);
        }
Example #4
0
        private static void ReceiveMessages()
        {
            // Read messages from queue until queue is empty
            Console.WriteLine("Reading messages from queue {0}...", SampleManager.SessionlessQueueName);
            Console.WriteLine("Receiver Type: Receive and Delete");

            // Create channel listener and channel using NetMessagingBinding
            NetMessagingBinding             messagingBinding = new NetMessagingBinding("messagingBinding");
            EndpointAddress                 address          = SampleManager.GetEndpointAddress(SampleManager.SessionlessQueueName, serviceBusNamespace);
            TransportClientEndpointBehavior securityBehavior = new TransportClientEndpointBehavior();

            securityBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);

            IChannelListener <IInputChannel> inputChannelListener = null;
            IInputChannel inputChannel = null;

            try
            {
                inputChannelListener = messagingBinding.BuildChannelListener <IInputChannel>(address.Uri, securityBehavior);
                inputChannelListener.Open();
                inputChannel = inputChannelListener.AcceptChannel();
                inputChannel.Open();

                while (true)
                {
                    try
                    {
                        // Receive message from queue. If no more messages available, the operation throws a TimeoutException.
                        Message receivedMessage = inputChannel.Receive(receiveMessageTimeout);
                        SampleManager.OutputMessageInfo("Receive", receivedMessage);

                        // Since the message body contains a serialized string one can access it like this:
                        //string soapBody = receivedMessage.GetBody<string>();
                    }
                    catch (TimeoutException)
                    {
                        break;
                    }
                }

                // Close
                inputChannel.Close();
                inputChannelListener.Close();
            }
            catch (Exception)
            {
                if (inputChannel != null)
                {
                    inputChannel.Abort();
                }
                if (inputChannelListener != null)
                {
                    inputChannelListener.Abort();
                }
                throw;
            }
        }
Example #5
0
        protected override void InitializeFrom(Binding binding)
        {
            base.InitializeFrom(binding);
            NetMessagingBinding netMessagingBinding = (NetMessagingBinding)binding;

            this.PrefetchCount      = netMessagingBinding.PrefetchCount;
            this.SessionIdleTimeout = netMessagingBinding.SessionIdleTimeout;
            this.TransportSettings.InitializeFrom(netMessagingBinding.TransportSettings);
        }
        public ServiceQueueResponseBase(NetMessagingBinding binding) : base(binding, ResponseAddress)
        {
            //Grab the creds the host was using
            IServiceBusProperties properties = OperationContext.Current.Host as IServiceBusProperties;

            Debug.Assert(properties != null);

            Tuple <Uri, string> tuple = ServiceBusHelper.ParseUri(ResponseAddress.Uri);

            this.SetServiceBusCredentials(properties.Credential.TokenProvider);

            ServiceBusHelper.VerifyQueue(tuple.Item1, tuple.Item2, properties.Credential.TokenProvider, RequiresSession);
        }
Example #7
0
        private static void MessageWithContext()
        {
            var transportClientEndpointBehavior = new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sendKeyName, sendKeyValue)
            };

            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, _queueName);

            var netMessagingBinding = new NetMessagingBinding
            {
                PrefetchCount = 10,
                TransportSettings = new NetMessagingTransportSettings
                {
                    // this is polling interval
                    BatchFlushInterval = TimeSpan.FromSeconds(0)
                }
            };

            var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IRequest)),
                                                        netMessagingBinding,
                                                        new EndpointAddress(serviceUri));
            serviceEndpoint.Behaviors.Add(transportClientEndpointBehavior);
            var channelFactory = new ChannelFactory<IRequest>(serviceEndpoint);
            var channel = channelFactory.CreateChannel();
            Console.WriteLine("Press any key to send message...");
            Console.ReadKey();

            using (new OperationContextScope((IContextChannel)channel))
            {
                var brokeredMessageProperty = new BrokeredMessageProperty
                {
                    Label = "MyLabel",
                    MessageId = Guid.NewGuid().ToString()
                };
                brokeredMessageProperty.Properties.Add("Author", "Paolo Salvatori");
                brokeredMessageProperty.Properties.Add("Email", "*****@*****.**");
                brokeredMessageProperty.Properties.Add("Country", "Italy");
                brokeredMessageProperty.Properties.Add("Priority", 1);
                OperationContext.Current.OutgoingMessageProperties.Add(BrokeredMessageProperty.Name, brokeredMessageProperty);
                channel.SendMessageWithContext("Hello from wcf client with context");

            }

            Console.WriteLine("Message sent");
            Console.ReadKey();
        }
        /// <summary>
        /// Creates a new <see cref="ServiceInstanceListener"/> capable of listening to a queue containing
        /// WCF queued messages for the given <typeparamref name="TServiceContract"/>.
        /// </summary>
        /// <param name="wcfServiceObject">
        /// The WCF service instance to be used for servicing requests. Must be a stateless service. Must not be null.
        /// </param>
        /// <param name="netMessagingBinding">
        /// The binding to be used to listen to the queue. Must not be null.
        /// </param>
        /// <param name="configPackageName">
        /// The name of the configuration package used to retrieve configuration values. If null, the default
        /// value is "Config".
        /// </param>
        /// <param name="sectionName">
        /// The name of the configuration section used to retrieve configuration values. If null, the default
        /// value is "ServiceBus".
        /// </param>
        /// <param name="listenConnectionStringParameterName">
        /// The name of the configuration value that provides a Service Bus connection string with Listen privileges.
        /// If null, the default is "ListenConnectionString".
        /// </param>
        /// <param name="queueNameProvider">
        /// A <see cref="Func{TResult}"/> returning the name of the queue to be used. If null, the default behavior
        /// will be to use the name of <typeparamref name="TServiceContract"/>.
        /// </param>
        /// <param name="endpointBehaviors">
        /// The <see cref="IEndpointBehavior"/>s that are to be applied to the generated WCF <see cref="ServiceHost"/>
        /// endpoints.
        /// </param>
        /// <typeparam name="TServiceContract">
        /// The interface that bears a <see cref="ServiceContractAttribute"/> and <see cref="OperationContractAttribute"/>s
        /// on its methods to denote it as a ServiceModel (WCF) service.
        /// </typeparam>
        /// <returns>
        /// A new <see cref="ServiceInstanceListener"/> configured to listen to an Azure Service Bus for WCF
        /// messages for the given <typeparamref name="TServiceContract"/> service contract. Guaranteed not to
        /// be null.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="wcfServiceObject"/> or <see cref="NetMessagingBinding"/> are null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if the endpoint for the Service Bus queue's containing Azure Service Bus namespace could
        /// not be resolved from the connection string.
        /// </exception>
        public static ServiceInstanceListener CreateQueuedServiceBusListener <TServiceContract>(
            TServiceContract wcfServiceObject,
            NetMessagingBinding netMessagingBinding,
            string configPackageName = "Config",
            string sectionName       = "ServiceBus",
            string listenConnectionStringParameterName = "ListenConnectionString",
            Func <string> queueNameProvider            = null,
            params IEndpointBehavior[] endpointBehaviors)
        {
            if (wcfServiceObject == null)
            {
                throw new ArgumentNullException(nameof(wcfServiceObject));
            }

            if (netMessagingBinding == null)
            {
                throw new ArgumentNullException(nameof(netMessagingBinding));
            }

            string ResolveConnectionStringFromSFParameters(ServiceContext statelessServiceContext)
            {
                if (statelessServiceContext == null)
                {
                    throw new ArgumentNullException(nameof(statelessServiceContext));
                }

                ConfigurationProperty configurationProperty = statelessServiceContext.CodePackageActivationContext
                                                              .GetConfigurationPackageObject(configPackageName).Settings.Sections[sectionName]
                                                              .Parameters[listenConnectionStringParameterName];

                return(configurationProperty.IsEncrypted
                                               ? new NetworkCredential("junk", configurationProperty.DecryptValue()).Password
                                               : configurationProperty.Value);
            }

            return(new ServiceInstanceListener(
                       createCommunicationListener: context => ResolveCommunicationListener(
                           context: context,
                           wcfServiceObject: wcfServiceObject,
                           netMessagingBinding: netMessagingBinding,
                           queueNameProvider: queueNameProvider,
                           connectionStringResolver: ResolveConnectionStringFromSFParameters,
                           behaviors: endpointBehaviors
                           )
                       ));
        }
Example #9
0
        static void Main(string[] args)
        {
            var transportClientEndpointBehavior = new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(listenKeyName, listenKeyValue)
            };

            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, _queueName);

            // Instantiate the host with the contract and URI.
            var host = new ServiceHost(typeof(RequestService), serviceUri);

            var netMessagingBinding = new NetMessagingBinding
            {
                PrefetchCount = 10,
                TransportSettings = new NetMessagingTransportSettings
                {
                    // this is polling interval
                    BatchFlushInterval = TimeSpan.FromSeconds(0)
                }
            };

            // Add the service endpoints to the service host
            host.AddServiceEndpoint(typeof(IRequest), netMessagingBinding, string.Empty);

            Console.WriteLine("Listening... ");
            Console.Write(" - ");
            Console.WriteLine(host.Description.Endpoints[0].Address.Uri.AbsoluteUri);

            foreach (var endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(transportClientEndpointBehavior);
            }

            host.Open();

            Console.ReadLine();
        }
Example #10
0
        /// <summary>
        /// Creates a new <see cref="QueuedWcfCommunicationClientFactory{TServiceContract}"/> with default parameters
        /// necessary to connect to an Azure Service Bus queue and publish WCF messages.
        /// </summary>
        /// <param name="netMessagingBinding">
        /// The <see cref="NetMessagingBinding"/> to be used to bind to the WCF endpoint. Must not be null.
        /// </param>
        /// <param name="sharedAccessKeyName">
        /// The name of the shared access key to be used to connect. Must not be null or empty.
        /// </param>
        /// <param name="sharedAccessKey">
        /// The value of the shared access key to be used to connect. Must not be null or empty.
        /// </param>
        /// <param name="servicePartitionResolver">
        /// The <see cref="IServicePartitionResolver"/> used to resolve the Service Fabric partition
        /// that contains the target service that's to handle the request.
        /// </param>
        /// <param name="exceptionHandlers">
        /// The handlers to be used for handling exceptions. May be null.
        /// </param>
        /// <typeparam name="TServiceContract">
        /// The type of WCF service contract to be used.
        /// </typeparam>
        /// <returns>
        /// A new <see cref="QueuedWcfCommunicationClientFactory{TServiceContract}"/> instance ready for use to publish
        /// messages via the Service Bus. Guaranteed not to be null.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="netMessagingBinding"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Thrown if any string parameters are null or empty.
        /// </exception>
        public static QueuedWcfCommunicationClientFactory <TServiceContract> CreateCommunicationClientFactory <TServiceContract>(NetMessagingBinding netMessagingBinding, string sharedAccessKeyName, string sharedAccessKey, IServicePartitionResolver servicePartitionResolver, IEnumerable <IExceptionHandler> exceptionHandlers = null) where TServiceContract : class
        {
            if (netMessagingBinding == null)
            {
                throw new ArgumentNullException(nameof(netMessagingBinding));
            }

            if (String.IsNullOrEmpty(sharedAccessKeyName))
            {
                throw new ArgumentException("Must not be null or empty", nameof(sharedAccessKeyName));
            }

            if (String.IsNullOrWhiteSpace(sharedAccessKey))
            {
                throw new ArgumentException("Must not be null or empty", nameof(sharedAccessKey));
            }

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sharedAccessKeyName, sharedAccessKey);

            return(new QueuedWcfCommunicationClientFactory <TServiceContract>(
                       clientBinding: netMessagingBinding,
                       tokenProvider: tokenProvider,
                       servicePartitionResolver: servicePartitionResolver,
                       exceptionHandlers: exceptionHandlers,
                       traceId: null
                       ));
        }
        public void ImportEndpoint(WsdlImporter importer, WsdlEndpointConversionContext context)
        {
            NetMessagingBinding name;

            if (context == null || context.Endpoint.Binding == null)
            {
                throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.ArgumentNull((context == null ? "context" : "context.Endpoint.Binding"));
            }
            BindingElementCollection            bindingElementCollection            = context.Endpoint.Binding.CreateBindingElements();
            NetMessagingTransportBindingElement netMessagingTransportBindingElement = bindingElementCollection.Find <TransportBindingElement>() as NetMessagingTransportBindingElement;

            if (netMessagingTransportBindingElement != null)
            {
                NetMessagingBindingElementImporter.ImportAddress(context);
            }
            if (context.Endpoint.Binding is CustomBinding && netMessagingTransportBindingElement != null && NetMessagingBinding.TryCreate(bindingElementCollection, out name))
            {
                name.Name                = context.Endpoint.Binding.Name;
                name.Namespace           = context.Endpoint.Binding.Namespace;
                context.Endpoint.Binding = name;
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            try
            {
                ParseArgs(args);
                Console.Title = "Message Sender";

                // Get credentials as Endpoint behavior
                TransportClientEndpointBehavior securityBehavior = new TransportClientEndpointBehavior();
                securityBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);

                // Create factory and channel using NetMessagingBinding
                NetMessagingBinding messagingBinding = new NetMessagingBinding("messagingBinding");
                EndpointAddress     address          = SampleManager.GetEndpointAddress(SampleManager.SessionlessQueueName, serviceBusNamespace);

                IChannelFactory <IOutputChannel> messagingChannelFactory = null;
                IOutputChannel messagingOutputChannel = null;
                try
                {
                    messagingChannelFactory = messagingBinding.BuildChannelFactory <IOutputChannel>(securityBehavior);
                    messagingChannelFactory.Open();
                    messagingOutputChannel = messagingChannelFactory.CreateChannel(address);
                    messagingOutputChannel.Open();

                    // Send messages to queue which does not require session
                    Console.WriteLine("Preparing to send messages to {0}...", SampleManager.SessionlessQueueName);
                    Thread.Sleep(3000);

                    SendMessages(messagingOutputChannel, messagingBinding);
                    messagingOutputChannel.Close();
                    messagingChannelFactory.Close();
                }
                catch (Exception)
                {
                    if (messagingOutputChannel != null)
                    {
                        messagingOutputChannel.Abort();
                    }
                    if (messagingChannelFactory != null)
                    {
                        messagingChannelFactory.Abort();
                    }
                    throw;
                }

                // Wait for all receivers to receive message
                Thread.Sleep(TimeSpan.FromSeconds(5.0d));
                Console.Clear();

                // Create factory and channel using custom binding
                CustomBinding customBinding = new CustomBinding("customBinding");
                address = SampleManager.GetEndpointAddress(SampleManager.SessionQueueName, serviceBusNamespace);

                IChannelFactory <IOutputChannel> customChannelFactory = null;
                IOutputChannel customOutputChannel = null;
                try
                {
                    customChannelFactory = customBinding.BuildChannelFactory <IOutputChannel>(securityBehavior);
                    customChannelFactory.Open();
                    customOutputChannel = customChannelFactory.CreateChannel(address);
                    customOutputChannel.Open();

                    // Send messages to queue which requires session
                    Console.Title = "Session MessageSender";
                    Console.WriteLine("Preparing to send messages to {0}...", SampleManager.SessionQueueName);
                    Thread.Sleep(3000);

                    SendMessages(customOutputChannel, customBinding);
                    customOutputChannel.Close();
                    customChannelFactory.Close();
                }
                catch (Exception)
                {
                    if (customOutputChannel != null)
                    {
                        customOutputChannel.Abort();
                    }
                    if (customChannelFactory != null)
                    {
                        customChannelFactory.Abort();
                    }
                    throw;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception Occurred: {0}", exception);
                SampleManager.ExceptionOccurred = true;
            }

            // All messages sent
            Console.WriteLine("\nSender complete. Press [Enter] to exit.");
            Console.ReadLine();
        }
 public ClientResponseBase(Uri responseAddress, NetMessagingBinding binding, EndpointAddress address, string sessionId, string replyToSessionId) : base(binding, address, sessionId)
 {
     ResponseAddress  = responseAddress;
     ReplyToSessionId = replyToSessionId;
 }
 public ClientResponseBase(Uri responseAddress, NetMessagingBinding binding, EndpointAddress address, string sessionId = null) : base(binding, address, sessionId)
 {
     ResponseAddress = responseAddress;
 }
        private static WcfCommunicationListener <TServiceContract> ResolveCommunicationListener <TServiceContract>(
            StatelessServiceContext context,
            TServiceContract wcfServiceObject,
            NetMessagingBinding netMessagingBinding,
            Func <string> queueNameProvider,
            Func <ServiceContext, string> connectionStringResolver,
            IEndpointBehavior[] behaviors)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (wcfServiceObject == null)
            {
                throw new ArgumentNullException(nameof(wcfServiceObject));
            }

            if (netMessagingBinding == null)
            {
                throw new ArgumentNullException(nameof(netMessagingBinding));
            }

            if (connectionStringResolver == null)
            {
                throw new ArgumentNullException(nameof(connectionStringResolver));
            }

            if (behaviors == null)
            {
                throw new ArgumentNullException(nameof(behaviors));
            }

            string listenConnectionString = connectionStringResolver(context);

            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(listenConnectionString);

            Uri endpointUri;

            try
            {
                endpointUri = builder.Endpoints.SingleOrDefault();
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException("More than one endpoint was detected in connection string");
            }

            if (endpointUri == null)
            {
                throw new InvalidOperationException("No endpoint was detected in connection string");
            }

            UriBuilder uriBuilder = new UriBuilder(endpointUri);

            var listener = new WcfCommunicationListener <TServiceContract>(
                wcfServiceObject: wcfServiceObject,
                serviceContext: context,

                //
                // The name of the endpoint configured in the ServiceManifest under the Endpoints section
                // that identifies the endpoint that the WCF ServiceHost should listen on.
                //
                address: new EndpointAddress(ServiceBusEnvironment.CreateServiceUri("sb", uriBuilder.Host.Split('.').First(), queueNameProvider == null ? typeof(TServiceContract).Name : queueNameProvider.Invoke())),

                //
                // Populate the binding information that you want the service to use.
                //
                listenerBinding: netMessagingBinding
                );

            ServiceEndpoint serviceEndpoint = listener.ServiceHost.Description.Endpoints.Last();

            serviceEndpoint.Behaviors.Add(new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                    keyName: builder.SharedAccessKeyName,
                    sharedAccessKey: builder.SharedAccessKey
                    )
            });

            foreach (IEndpointBehavior behavior in behaviors)
            {
                serviceEndpoint.Behaviors.Add(behavior);
            }

            return(listener);
        }
 public QueuedServiceBusClient(NetMessagingBinding binding, EndpointAddress address, string sessionId = null) : base(binding, address)
 {
     SessionId = sessionId;
 }
Example #17
0
		static void SimpleWcfClientServiceViaServiceBus()
		{
			NetMessagingBinding binding = new NetMessagingBinding();

			// Start up the Echo WCF service listening via Azure Service Bus
			ServiceHost host = new ServiceHost(typeof(EchoService));
			ServiceEndpoint echoServiceEndpoint
				= host.AddServiceEndpoint(typeof(IEchoService), binding, QueueAddress);
			echoServiceEndpoint.Behaviors.Add(new TransportClientEndpointBehavior(TokenProvider));
			host.Open();
			Console.WriteLine("WCF service up and running, listening on {0}", QueueAddress);

			// Create a WCF channel factory and client to send message to the Azure Service Bus
			ChannelFactory<IEchoService> factory = new ChannelFactory<IEchoService>
				(binding, new EndpointAddress(QueueAddress));
			factory.Endpoint.Behaviors.Add(new TransportClientEndpointBehavior(TokenProvider));
			IEchoService proxy = factory.CreateChannel();

			// Send messages to the service
			string requestMessage = "Hello World";
			proxy.Echo(requestMessage);
			Console.WriteLine("Message sent to the queue - '{0}' ", requestMessage);

			// clean up the client and service
			factory.Close();
			host.Close();
		}
Example #18
0
        /// <summary>
        /// Creates a new <see cref="QueuedWcfCommunicationClientFactory{TServiceContract}"/> with default parameters
        /// necessary to connect to an Azure Service Bus queue and publish WCF messages.
        /// </summary>
        /// <param name="netMessagingBinding">
        /// The <see cref="NetMessagingBinding"/> to be used to bind to the WCF endpoint. Must not be null.
        /// </param>
        /// <param name="sharedAccessKeyName">
        /// The name of the shared access key to be used to connect. Must not be null or empty.
        /// </param>
        /// <param name="sharedAccessKey">
        /// The value of the shared access key to be used to connect. Must not be null or empty.
        /// </param>
        /// <param name="exceptionHandlers">
        /// The handlers to be used for handling exceptions. May be null.
        /// </param>
        /// <typeparam name="TServiceContract">
        /// The type of WCF service contract to be used.
        /// </typeparam>
        /// <returns>
        /// A new <see cref="QueuedWcfCommunicationClientFactory{TServiceContract}"/> instance ready for use to publish
        /// messages via the Service Bus. Guaranteed not to be null.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="netMessagingBinding"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Thrown if any string parameters are null or empty.
        /// </exception>
        public static QueuedWcfCommunicationClientFactory <TServiceContract> CreateCommunicationClientFactory <TServiceContract>(NetMessagingBinding netMessagingBinding, string sharedAccessKeyName, string sharedAccessKey, IEnumerable <IExceptionHandler> exceptionHandlers = null) where TServiceContract : class

        {
            if (netMessagingBinding == null)
            {
                throw new ArgumentNullException(nameof(netMessagingBinding));
            }

            if (String.IsNullOrEmpty(sharedAccessKeyName))
            {
                throw new ArgumentException("Must not be null or empty", nameof(sharedAccessKeyName));
            }

            if (String.IsNullOrWhiteSpace(sharedAccessKey))
            {
                throw new ArgumentException("Must not be null or empty", nameof(sharedAccessKey));
            }

            return(CreateCommunicationClientFactory <TServiceContract>(
                       netMessagingBinding,
                       sharedAccessKeyName,
                       sharedAccessKey,
                       servicePartitionResolver: ServicePartitionResolver.GetDefault(),
                       exceptionHandlers: exceptionHandlers
                       ));
        }
Example #19
0
 public QueuedWcfCommunicationClientFactory(NetMessagingBinding clientBinding, TokenProvider tokenProvider, IEnumerable <IExceptionHandler> exceptionHandlers = null, IServicePartitionResolver servicePartitionResolver = null, string traceId = null) :
     base(clientBinding, exceptionHandlers, servicePartitionResolver, traceId, null)
 {
     this.factory = new ChannelFactory <TServiceContract>(clientBinding ?? throw new ArgumentNullException(nameof(clientBinding)));
     this.factory.Endpoint.Behaviors.Add(new TransportClientEndpointBehavior(tokenProvider ?? throw new ArgumentNullException(nameof(tokenProvider))));
 }