public static ChannelFactory <T> CreateServiceBusClientChannelFactory <T>(ServiceBusEndpointInfo sbEndpointInfo) where T : IClientChannel
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");

            Binding binding = null;

            switch (sbEndpointInfo.EndpointType)
            {
            case ServiceBusEndpointType.Eventing:

                binding = new NetEventRelayBinding(EndToEndSecurityMode.None, RelayEventSubscriberAuthenticationType.None);
                break;

            case ServiceBusEndpointType.Relay:
            case ServiceBusEndpointType.HybridRelay:

                NetTcpRelayBinding tcpRelayBinding = new NetTcpRelayBinding(EndToEndSecurityMode.None, RelayClientAuthenticationType.None);
                tcpRelayBinding.ConnectionMode = (sbEndpointInfo.EndpointType == ServiceBusEndpointType.HybridRelay ? TcpRelayConnectionMode.Hybrid : TcpRelayConnectionMode.Relayed);

                binding = tcpRelayBinding;
                break;

            default:
                return(null);
            }

            return(CreateServiceBusClientChannelFactory <T>(sbEndpointInfo.ServiceNamespace, sbEndpointInfo.ServicePath, sbEndpointInfo.IssuerName, sbEndpointInfo.IssuerSecret, binding));
        }
Пример #2
0
        public void TestMessageBufferSend()
        {
            int eventCount = 0;
            ServiceBusEndpointInfo diagEndpointInfo = ApplicationConfiguration.Current.ServiceBusSettings.Endpoints[diagnosticEventQueue];

            Assert.IsNotNull(diagEndpointInfo, "{0} service bus endpoint definition has not been found", diagnosticEventQueue);

            try
            {
                string randomQueueName = Guid.NewGuid().ToString();

                using (ReliableServiceBusQueue <TraceEventRecord> sbQueue = new ReliableServiceBusQueue <TraceEventRecord>(randomQueueName, diagEndpointInfo))
                {
                    for (int i = 0; i < 100; i++)
                    {
                        sbQueue.Send(TraceEventRecord.Create(this.GetType().Name, TraceEventType.Information, 0, String.Format("Test event #{0}", i)));
                        eventCount++;
                    }
                }
            }
            finally
            {
                Trace.WriteLine(String.Format("Event count = {0}", eventCount));
            }
        }
Пример #3
0
        public void ValidateServiceBusSettings()
        {
            ApplicationConfiguration appConfig = ApplicationConfiguration.Current;

            Assert.IsTrue(ApplicationConfiguration.IsLoaded);

            ServiceBusConfigurationSettings sbSettings = appConfig.GetConfigurationSection <ServiceBusConfigurationSettings>(ServiceBusConfigurationSettings.SectionName);

            Assert.IsNotNull(sbSettings, "No ServiceBusSettings section was found");
            Assert.IsFalse(String.IsNullOrEmpty(sbSettings.DefaultEndpoint), "DefaultEndpoint not specified");
            Assert.IsFalse(String.IsNullOrEmpty(sbSettings.DefaultIssuerName), "DefaultIssuerName not specified");
            Assert.IsFalse(String.IsNullOrEmpty(sbSettings.DefaultIssuerSecret), "DefaultIssuerSecret not specified");
            Assert.IsTrue(sbSettings.Endpoints != null && sbSettings.Endpoints.Count > 0, "Endpoints collection is empty");

            ServiceBusEndpointInfo firstEndpoint = sbSettings.Endpoints.Get(0);

            Assert.IsNotNull(firstEndpoint, "First endpoint is null");
            Assert.IsFalse(String.IsNullOrEmpty(firstEndpoint.Name), "Element name not specified");
            Assert.IsFalse(String.IsNullOrEmpty(firstEndpoint.ServiceNamespace), "ServiceNamespace not specified");
            Assert.IsFalse(String.IsNullOrEmpty(firstEndpoint.ServicePath), "ServicePath not specified");
            Assert.IsFalse(String.IsNullOrEmpty(firstEndpoint.IssuerName), "IssuerName not specified");
            Assert.IsFalse(String.IsNullOrEmpty(firstEndpoint.IssuerSecret), "IssuerSecret not specified");

            ServiceBusEndpointInfo secondEndpoint = sbSettings.Endpoints.Get(1);

            Assert.IsNotNull(secondEndpoint, "First endpoint is null");
            Assert.IsFalse(String.IsNullOrEmpty(secondEndpoint.Name), "Element name not specified");
            Assert.IsFalse(String.IsNullOrEmpty(secondEndpoint.ServiceNamespace), "ServiceNamespace not specified");
            Assert.IsFalse(String.IsNullOrEmpty(secondEndpoint.ServicePath), "ServicePath not specified");
            // Assert.IsFalse(String.IsNullOrEmpty(secondEndpoint.IssuerName), "IssuerName not specified");
            // Assert.IsFalse(String.IsNullOrEmpty(secondEndpoint.IssuerSecret), "IssuerSecret not specified");
        }
Пример #4
0
        /// <summary>
        /// Returns a new OnPremiseConfigurationSource configured with the specified settings.
        /// </summary>
        /// <returns>A new configuration source.</returns>
        public override IConfigurationSource CreateSource()
        {
            // The initial configuration containing the Service Bus endpoint information is expected to be defined in app.config.
            string configFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

            SystemConfigurationSource       systemConfig     = new SystemConfigurationSource();
            ServiceBusConfigurationSettings serviceBusConfig = systemConfig.GetSection(ServiceBusConfigurationSettings.SectionName) as ServiceBusConfigurationSettings;

            if (serviceBusConfig != null)
            {
                ServiceBusEndpointInfo defaultEndpointInfo = UseDefaultServiceBusEndpoint ? serviceBusConfig.Endpoints[serviceBusConfig.DefaultEndpoint] : serviceBusConfig.Endpoints[ServiceBusEndpoint];
                if (defaultEndpointInfo != null)
                {
                    return(new OnPremiseConfigurationSource(defaultEndpointInfo));
                }
                else
                {
                    if (UseDefaultServiceBusEndpoint)
                    {
                        throw new ConfigurationErrorsException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.DefaultServiceBusEndpointNotFound, configFileName, ServiceBusConfigurationSettings.SectionName));
                    }
                    else
                    {
                        throw new ConfigurationErrorsException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.SpecifiedServiceBusEndpointNotFoundInConfigFile, configFileName, ServiceBusConfigurationSettings.SectionName, ServiceBusEndpoint));
                    }
                }
            }
            else
            {
                throw new ConfigurationErrorsException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.ConfigSectionNotFoundInConfigFile, configFileName, ServiceBusConfigurationSettings.SectionName));
            }
        }
Пример #5
0
        /// <summary>
        /// Initializes a new instance of the reliable Windows Azure Service Bus Message Buffer client connected to the specified message buffer
        /// located on the specified Service Bus endpoint and utilizing the specified custom retry policy.
        /// </summary>
        /// <param name="queueName">The name of the target message buffer (queue).</param>
        /// <param name="sbEndpointInfo">The endpoint details.</param>
        /// <param name="retryPolicy">The custom retry policy that will ensure reliable access to the underlying HTTP/REST-based infrastructure.</param>
        public ReliableServiceBusQueue(string queueName, ServiceBusEndpointInfo sbEndpointInfo, RetryPolicy retryPolicy)
        {
            Guard.ArgumentNotNullOrEmptyString(queueName, "queueName");
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");
            Guard.ArgumentNotNull(retryPolicy, "retryPolicy");

            this.sbEndpointInfo = sbEndpointInfo;
            this.retryPolicy    = retryPolicy;

            this.queuePolicy = new MessageBufferPolicy
            {
                ExpiresAfter    = TimeSpan.FromMinutes(120),
                MaxMessageCount = 100000,
                OverflowPolicy  = OverflowPolicy.RejectIncomingMessage
            };

            var address = ServiceBusEnvironment.CreateServiceUri(WellKnownProtocolScheme.SecureHttp, sbEndpointInfo.ServiceNamespace, String.Concat(sbEndpointInfo.ServicePath, !sbEndpointInfo.ServicePath.EndsWith("/") ? "/" : "", queueName));
            var credentialsBehaviour = new TransportClientEndpointBehavior();

            credentialsBehaviour.CredentialType = TransportClientCredentialType.SharedSecret;
            credentialsBehaviour.Credentials.SharedSecret.IssuerName   = sbEndpointInfo.IssuerName;
            credentialsBehaviour.Credentials.SharedSecret.IssuerSecret = sbEndpointInfo.IssuerSecret;

            MessageBufferClient msgBufferClient = null;

            this.retryPolicy.ExecuteAction(() =>
            {
                msgBufferClient = MessageBufferClient.CreateMessageBuffer(credentialsBehaviour, address, this.queuePolicy, DefaultQueueMessageVersion);
            });

            this.queueClient = msgBufferClient;
        }
Пример #6
0
        /// <summary>
        /// Initializes a configuration source that will connect to the on-premises configuration source using the specified Service Bus endpoint.
        /// </summary>
        /// <param name="sbEndpointInfo">The Service Bus endpoint details.</param>
        public OnPremiseConfigurationSource(ServiceBusEndpointInfo sbEndpointInfo)
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");

            this.sbEndpointInfo     = sbEndpointInfo;
            this.retryPolicy        = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(ServiceBusRequestRetryCount, TimeSpan.FromSeconds(ServiceBusRequestRetryIntervalSec));
            this.configSectionCache = new Dictionary <string, ConfigurationSection>(16);
        }
Пример #7
0
        /// <summary>
        /// Applies the specified transformation map against the input document.
        /// </summary>
        /// <param name="transformName">Either partial or fully qualified name of the transformation map.</param>
        /// <param name="input">The input document that needs to be transformed.</param>
        /// <returns>The results from transformation.</returns>
        public XDocument ApplyTransform(string transformName, XDocument input)
        {
            Guard.ArgumentNotNull(this.roleConfigExtension, "roleConfigExtension");
            Guard.ArgumentNotNullOrEmptyString(transformName, "transformName");
            Guard.ArgumentNotNull(input, "input");
            Guard.ArgumentNotNull(input.Root, "input.Root");

            var callToken = TraceManager.WorkerRoleComponent.TraceIn(transformName, input.Root.Name);

            try
            {
                ServiceBusEndpointInfo sbEndpointInfo = this.roleConfigExtension.GetServiceBusEndpoint(WellKnownEndpointName.ScalableTransformService);

                if (sbEndpointInfo != null)
                {
                    using (ReliableServiceBusClient <IScalableTransformationServiceChannel> transform = new ReliableServiceBusClient <IScalableTransformationServiceChannel>(sbEndpointInfo, this.roleConfigExtension.CommunicationRetryPolicy))
                        using (MemoryStream dataStream = new MemoryStream())
                            using (XmlWriter xmlWriter = XmlWriter.Create(dataStream))
                            {
                                input.WriteTo(xmlWriter);

                                xmlWriter.Flush();
                                dataStream.Seek(0, SeekOrigin.Begin);

                                XslTransformState preparedState = transform.RetryPolicy.ExecuteAction <XslTransformState>(() =>
                                {
                                    return(transform.Client.PrepareTransform(dataStream));
                                });

                                XslTransformState transformedState = transform.RetryPolicy.ExecuteAction <XslTransformState>(() =>
                                {
                                    return(transform.Client.ApplyTransform(transformName, preparedState));
                                });

                                using (Stream transformedData = transform.RetryPolicy.ExecuteAction <Stream>(() =>
                                {
                                    return(transform.Client.CompleteTransform(transformedState));
                                }))
                                {
                                    return(XDocument.Load(transformedData));
                                }
                            }
                }
                else
                {
                    throw new CloudApplicationException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ServiceBusEndpointNotFound, WellKnownEndpointName.ScalableTransformService));
                }
            }
            catch (Exception ex)
            {
                TraceManager.WorkerRoleComponent.TraceError(ex, callToken);
                throw;
            }
            finally
            {
                TraceManager.WorkerRoleComponent.TraceOut(callToken);
            }
        }
Пример #8
0
        /// <summary>
        /// Enables to pass data at runtime to bindings to support custom behavior.
        /// </summary>
        /// <param name="endpoint">The endpoint to modify.</param>
        /// <param name="bindingParameters">The objects that binding elements require to support the behavior.</param>
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            // Validate input parameters.
            Guard.ArgumentNotNull(endpoint, "endpoint");

            // Trace the method entry event.
            var callToken = TraceManager.CustomComponent.TraceIn(endpoint.Name, endpoint.ListenUri);

            // Get the Service Bus endpoint definition by its name from the current application configuration.
            // TODO: Check if config is not null
            ServiceBusEndpointInfo sbEndpointInfo = ApplicationConfiguration.Current.ServiceBusSettings.Endpoints[ServiceBusEndpointName];

            // Check if we found a definition.
            if (sbEndpointInfo != null)
            {
                // Trace an information event telling that we have found the Service Bus endpoint definition.
                TraceManager.CustomComponent.TraceInfo(TraceLogMessages.ApplyingServiceBusEndpointConfiguration, ServiceBusEndpointName, endpoint.Name, sbEndpointInfo.ServiceNamespace, sbEndpointInfo.ServicePath, sbEndpointInfo.EndpointType);

                // Look for a TransportClientEndpointBehavior implementation in the collection of registered behaviors.
                var credentialsBehaviour = endpoint.Behaviors.Find <TransportClientEndpointBehavior>();

                // Check if TransportClientEndpointBehavior was registered.
                if (credentialsBehaviour != null)
                {
                    // Configure the TransportClientEndpointBehavior with credentials captured from the application configuration.
                    credentialsBehaviour.CredentialType = TransportClientCredentialType.SharedSecret;
                    credentialsBehaviour.Credentials.SharedSecret.IssuerName   = sbEndpointInfo.IssuerName;
                    credentialsBehaviour.Credentials.SharedSecret.IssuerSecret = sbEndpointInfo.IssuerSecret;

                    // Check if we need to perform any changes at the WCF binding level.
                    var relayBinding = endpoint.Binding as NetTcpRelayBinding;

                    // If it is a NetTcpRelayBinding, we need to ensure that its ConnectionMode property matches the one defined in the application configuration.
                    if (relayBinding != null)
                    {
                        // Configure ConnectionMode with the value from the ServiceBusEndpointInfo configuration object.
                        switch (sbEndpointInfo.EndpointType)
                        {
                        case ServiceBusEndpointType.Relay:
                            relayBinding.ConnectionMode = TcpRelayConnectionMode.Relayed;
                            break;

                        case ServiceBusEndpointType.HybridRelay:
                            relayBinding.ConnectionMode = TcpRelayConnectionMode.Hybrid;
                            break;
                        }
                    }
                }
            }
            else
            {
                // Trace a warning event, do not throw an exception as Service Bus binding will report on missing credentials anyway.
                TraceManager.CustomComponent.TraceWarning(TraceLogMessages.ServiceBusEndpointDefinitionNotFound, ServiceBusEndpointName);
            }

            // Trace an event indicating that we are done.
            TraceManager.CustomComponent.TraceOut(callToken);
        }
Пример #9
0
        private void StartDiagnosticLoggingMockService()
        {
            ServiceBusEndpointInfo diagEndpointInfo = ApplicationConfiguration.Current.ServiceBusSettings.Endpoints[diagnosticServiceEndpointName];

            Assert.IsNotNull(diagEndpointInfo, "{0} service bus endpoint definition has not been found", diagnosticServiceEndpointName);

            this.diagServiceHost = ServiceBusHostFactory.CreateServiceBusEventRelayHost <DiagnosticLoggingMockService>(diagEndpointInfo);
            this.diagServiceHost.Open();
        }
        public InterRoleEventRelayCommunicationExtension(ServiceBusEndpointInfo serviceBusEndpoint)
        {
            Guard.ArgumentNotNull(serviceBusEndpoint, "serviceBusEndpoint");

            this.serviceBusEndpoint = serviceBusEndpoint;

            // Open a WCF service host servicing the IInterRoleCommunicationService contract.
            Subscriber.Open();
        }
Пример #11
0
        /// <summary>
        /// Initializes a new instance of the reliable Windows Azure Service Bus service host that will listen on the specified Service Bus endpoint
        /// and utilize the specified custom retry policy.
        /// </summary>
        /// <param name="sbEndpointInfo">The endpoint details.</param>
        /// <param name="retryPolicy">The custom retry policy that will ensure reliable access to the underlying WCF infrastructure.</param>
        public ReliableServiceBusHost(ServiceBusEndpointInfo sbEndpointInfo, RetryPolicy retryPolicy)
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");
            Guard.ArgumentNotNull(retryPolicy, "retryPolicy");

            this.sbEndpointInfo             = sbEndpointInfo;
            this.serviceHost                = ServiceBusHostFactory.CreateServiceBusHost <T>(sbEndpointInfo);
            this.retryPolicy                = retryPolicy;
            this.retryPolicy.RetryOccurred += HandleRetryState;

            AttachEventHandlers(this.serviceHost);
        }
Пример #12
0
        private void ConfigureServiceHostWorkerRole(IExtensibleCloudServiceComponent ownerRole)
        {
            var callToken = TraceManager.WorkerRoleComponent.TraceIn(ownerRole != null ? ownerRole.GetType().FullName : null);
            var startScopeCreateServiceHosts = TraceManager.WorkerRoleComponent.TraceStartScope(TraceLogMessages.ScopeCreateServiceHosts, callToken);

            if (ownerRole != null)
            {
                IList <ServiceBusHostWorkerRoleAttribute> serviceHostAttributes = FrameworkUtility.GetDeclarativeAttributes <ServiceBusHostWorkerRoleAttribute>(ownerRole.GetType());
                IRoleConfigurationSettingsExtension       roleConfigExtension   = ownerRole.Extensions.Find <IRoleConfigurationSettingsExtension>();

                if (serviceHostAttributes != null && serviceHostAttributes.Count > 0 && roleConfigExtension != null)
                {
                    ServiceBusEndpointInfo         endpointInfo = null;
                    ServiceBusListenerRegistration listenerInfo = null;

                    foreach (ServiceBusHostWorkerRoleAttribute serviceHostAttr in serviceHostAttributes)
                    {
                        endpointInfo = roleConfigExtension.GetServiceBusEndpoint(serviceHostAttr.ServiceBusEndpoint);

                        if (endpointInfo != null)
                        {
                            listenerInfo = new ServiceBusListenerRegistration()
                            {
                                ServiceType  = serviceHostAttr.ServiceType,
                                EndpointInfo = endpointInfo,
                                AutoStart    = serviceHostAttr.AutoStart
                            };

                            // All services that are enabled for auto-start will have their service hosts pre-initialized but not as yet openned.
                            if (listenerInfo.AutoStart)
                            {
                                TraceManager.WorkerRoleComponent.TraceInfo(TraceLogMessages.AboutToCreateServiceHost, listenerInfo.ServiceType.FullName, endpointInfo.Name, endpointInfo.ServiceNamespace, endpointInfo.ServicePath, endpointInfo.EndpointType);
                                listenerInfo.ServiceHost = new ReliableServiceBusHost <object>(ServiceBusHostFactory.CreateServiceBusHost(endpointInfo, listenerInfo.ServiceType), roleConfigExtension.CommunicationRetryPolicy);
                            }

                            this.serviceEndpoints.Add(endpointInfo, listenerInfo);
                        }
                        else
                        {
                            throw new CloudApplicationException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.SpecifiedServiceBusEndpointNotFound, serviceHostAttr.ServiceBusEndpoint, ServiceBusConfigurationSettings.SectionName));
                        }
                    }
                }
            }

            TraceManager.WorkerRoleComponent.TraceEndScope(TraceLogMessages.ScopeCreateServiceHosts, startScopeCreateServiceHosts, callToken);
            TraceManager.WorkerRoleComponent.TraceOut(callToken);
        }
Пример #13
0
        public static ServiceHost CreateServiceBusHost(ServiceBusEndpointInfo sbEndpointInfo, Type serviceType)
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");
            Guard.ArgumentNotNull(serviceType, "serviceType");

            switch (sbEndpointInfo.EndpointType)
            {
            case ServiceBusEndpointType.Eventing:
                return(CreateServiceBusEventRelayHost(sbEndpointInfo, serviceType));

            case ServiceBusEndpointType.Relay:
            case ServiceBusEndpointType.HybridRelay:
                return(CreateServiceBusRelayHost(sbEndpointInfo, serviceType));

            default:
                return(null);
            }
        }
Пример #14
0
        /// <summary>
        /// Initializes a new instance of the reliable Windows Azure Service Bus client component to communicate with the specified Service Bus endpoint
        /// using a custom retry policy.
        /// </summary>
        /// <param name="sbEndpointInfo">The endpoint details.</param>
        /// <param name="retryPolicy">The custom retry policy that will ensure reliable access to the underlying WCF infrastructure.</param>
        public ReliableServiceBusClient(ServiceBusEndpointInfo sbEndpointInfo, RetryPolicy retryPolicy)
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");
            Guard.ArgumentNotNull(retryPolicy, "retryPolicy");

            this.sbEndpointInfo = sbEndpointInfo;
            this.channelFactory = ServiceBusClientFactory.CreateServiceBusClientChannelFactory <T>(sbEndpointInfo);

            this.clientChannel          = this.channelFactory.CreateChannel();
            this.clientChannel.Opening += new EventHandler(HandleOpeningEvent);
            this.clientChannel.Opened  += new EventHandler(HandleOpenedEvent);
            this.clientChannel.Faulted += new EventHandler(HandleFaultedEvent);
            this.clientChannel.Closing += new EventHandler(HandleClosingEvent);
            this.clientChannel.Closed  += new EventHandler(HandleClosedEvent);

            this.retryPolicy = retryPolicy;
            this.retryPolicy.RetryOccurred += HandleRetryState;
        }
Пример #15
0
        public void SimulateServiceHostFaultedState()
        {
            string endpointName = "InterRoleCommunication";

            ServiceBusEndpointInfo testEndpointInfo = ApplicationConfiguration.Current.ServiceBusSettings.Endpoints[endpointName];

            Assert.IsNotNull(testEndpointInfo, "{0} service bus endpoint definition has not been found", endpointName);

            ReliableServiceBusHost <InterRoleCommunicationService> serviceHost = new ReliableServiceBusHost <InterRoleCommunicationService>(testEndpointInfo);

            serviceHost.Open();

            bool faultEncountered = false;

            serviceHost.Faulted += (sender, e) =>
            {
                faultEncountered = true;
            };

            Thread.Sleep(60 * 1000);

            Assert.IsTrue(faultEncountered);
        }
Пример #16
0
        public static ServiceHost CreateServiceBusRelayHost(ServiceBusEndpointInfo sbEndpointInfo, Type serviceType)
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");

            return(CreateServiceBusRelayHost(sbEndpointInfo.ServiceNamespace, sbEndpointInfo.ServicePath, sbEndpointInfo.IssuerName, sbEndpointInfo.IssuerSecret, serviceType));
        }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of a <see cref="InterRoleCommunicationExtension"/> object with the specified Service Bus topic endpoint and custom settings.
        /// </summary>
        /// <param name="serviceBusEndpoint">The Service Bus topic endpoint using which this component will be providing inter-role communication.</param>
        /// <param name="settings">The <see cref="InterRoleCommunicationSettings"/> object containing behavioral and runtime settings for the inter-role communication component.</param>
        public InterRoleCommunicationExtension(ServiceBusEndpointInfo serviceBusEndpoint, InterRoleCommunicationSettings settings)
        {
            Guard.ArgumentNotNull(serviceBusEndpoint, "serviceBusEndpoint");
            Guard.ArgumentNotNull(settings, "settings");
            Guard.ArgumentNotNullOrEmptyString(serviceBusEndpoint.TopicName, "serviceBusEndpoint.TopicName");

            // Initialize internal fields.
            this.settings           = settings;
            this.serviceBusEndpoint = serviceBusEndpoint;
            this.retryPolicy        = this.settings.RetryPolicy ?? RetryPolicy.NoRetry;
            this.senderRoleID       = FrameworkUtility.GetHashedValue(CloudEnvironment.DeploymentId, CloudEnvironment.CurrentRoleName);
            this.senderInstanceID   = FrameworkUtility.GetHashedValue(CloudEnvironment.DeploymentId, CloudEnvironment.CurrentRoleInstanceId);

            // Configure Service Bus credentials and service namespace URI.
            var credentials = TokenProvider.CreateSharedSecretTokenProvider(serviceBusEndpoint.IssuerName, serviceBusEndpoint.IssuerSecret);
            var address     = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusEndpoint.ServiceNamespace, String.Empty);

            // Configure Service Bus messaging factory and namespace client which is required for subscription management.
            this.messagingFactory = MessagingFactory.Create(address, credentials);
            this.nsManager        = new NamespaceManager(address, credentials);

            // Figure out the name of the subscription. If subscription name was specified in the endpoint definition, treat it as static.
            // If no subscription name was specified, assign a globally unique name based on hashed deployment ID and role instance ID values.
            this.useStaticSubscription = !String.IsNullOrEmpty(serviceBusEndpoint.SubscriptionName);
            this.ircSubscriptionName   = this.useStaticSubscription ? serviceBusEndpoint.SubscriptionName : (this.settings.UseCompetingConsumers ? String.Concat(SubscriptionNamePrefix, this.senderRoleID) : String.Concat(SubscriptionNamePrefix, this.senderInstanceID));

            // Configure the underlying messaging entities such as topic and subscription.
            ConfigureTopicClient(this.serviceBusEndpoint.TopicName);
            ConfigureSubscriptionClient(this.ircSubscriptionName);

            // Configure a fault handler for the receive action.
            this.receiveFaultAction = ((msg, ex) =>
            {
                // Log an error.
                TraceManager.ServiceComponent.TraceError(ex);

                try
                {
                    if (msg != null)
                    {
                        // Abandons a brokered message. This will cause Service Bus to unlock the message and make it available to be received again,
                        // either by the same consumer or by another completing consumer.
                        msg.Abandon(this.retryPolicy);
                    }
                }
                catch (MessageLockLostException)
                {
                    // It's too late to compensate the loss of a message lock. Should just ignore it so that it does not break the receive loop.
                }
                catch (CommunicationObjectAbortedException)
                {
                    // There is nothing we can do as connection might have been lost or underlying topic/subscription might have been removed.
                }
                catch (CommunicationObjectFaultedException)
                {
                    // If Abandon fail with this exception, the only recourse is to Receive another message (possibly the same one).
                }
            });

            // Configure event receive action.
            this.receiveAction = (() =>
            {
                BrokeredMessage msg = null;
                bool completedAsync = false;

                this.retryPolicy.ExecuteAction(() =>
                {
                    // Make sure we are not told to stop receiving while we are retrying.
                    if (!cts.IsCancellationRequested)
                    {
#if PERF_TEST
                        Stopwatch watch = Stopwatch.StartNew();
#endif
                        if ((msg = this.subscriptionClient.Receive(this.settings.EventWaitTimeout)) != null)
                        {
#if PERF_TEST
                            watch.Stop();
                            TraceManager.ServiceComponent.TraceDetails("Waited for a new event for {0}ms", watch.ElapsedMilliseconds);
#endif
                            try
                            {
                                // Make sure we are not told to stop receiving while we were waiting for a new message.
                                if (!this.cts.IsCancellationRequested)
                                {
                                    if (this.settings.EnableAsyncDispatch)
                                    {
                                        // Invoke the dispatch action asynchronously.
                                        this.dispatchAction.BeginInvoke(msg, this.endDispatch, msg);

                                        completedAsync = true;
                                    }
                                    else
                                    {
                                        // Invoke the dispatch action synchronously.
                                        this.dispatchAction(msg);

                                        // Mark brokered message as complete.
                                        msg.Complete(this.retryPolicy);
                                    }
                                }
                                else
                                {
                                    // If we were told to stop processing, the current message needs to be unlocked and return back to the queue.
                                    msg.Abandon(this.retryPolicy);
                                }
                            }
                            catch (Exception ex)
                            {
                                this.receiveFaultAction(msg, ex);
                            }
                            finally
                            {
                                // Do not attempt to dispose a BrokeredMessage instance if it was dispatched for processing asynchronously.
                                if (msg != null && !completedAsync)
                                {
                                    // Ensure that any resources allocated by a BrokeredMessage instance are released.
                                    msg.Dispose();
                                }
                            }
                        }
                    }
                });
            });

            // Configure event receive complete action.
            this.endReceive = ((ar) =>
            {
                try
                {
                    this.receiveAction.EndInvoke(ar);
                }
                catch (Exception ex)
                {
                    // Log this error. Do not allow an unhandled exception to kill the current process.
                    TraceManager.ServiceComponent.TraceError(ex);
                }

                if (!cts.IsCancellationRequested)
                {
                    this.receiveHandle = this.receiveAction.BeginInvoke(this.endReceive, null);
                }
            });

            // Configure event dispatch action. This action is performed when notifying subscribers about a new IRC event.
            this.dispatchAction = ((msg) =>
            {
                // Extract the event data from brokered message.
                InterRoleCommunicationEvent e = msg.GetBody <InterRoleCommunicationEvent>(this.serializer);

                // Notify all registered subscribers.
                NotifySubscribers(e);
            });

            this.endDispatch = ((ar) =>
            {
                BrokeredMessage msg = null;

                try
                {
                    msg = ar.AsyncState as BrokeredMessage;
                    this.dispatchAction.EndInvoke(ar);

                    if (msg != null)
                    {
                        // Mark brokered message as complete.
                        msg.Complete(this.retryPolicy);
                    }
                }
                catch (Exception ex)
                {
                    this.receiveFaultAction(msg, ex);
                }
                finally
                {
                    if (msg != null)
                    {
                        // Ensure that any resources allocated by a BrokeredMessage instance are released.
                        msg.Dispose();
                    }
                }
            });
        }
Пример #18
0
 /// <summary>
 /// Initializes a new instance of the reliable Windows Azure Service Bus Message Buffer client connected to the specified message buffer
 /// located on the specified Service Bus endpoint. No retry policy will be enforced when using this constructor overload.
 /// </summary>
 /// <param name="queueName">The name of the target message buffer (queue).</param>
 /// <param name="sbEndpointInfo">The endpoint details.</param>
 public ReliableServiceBusQueue(string queueName, ServiceBusEndpointInfo sbEndpointInfo)
     : this(queueName, sbEndpointInfo, RetryPolicy.NoRetry)
 {
 }
Пример #19
0
        /// <summary>
        /// Returns a client communication channel of type <typeparamref name="T"/> for communication with the specified Service Bus endpoint.
        /// The type of endpoint is determined from the endpoint details supplied in the <see cref="ServiceBusEndpointInfo"/> instance.
        /// </summary>
        /// <typeparam name="T">The type of the client communication channel. Must inherit from service contract as well as <see cref="System.ServiceModel.IClientChannel"/>.</typeparam>
        /// <param name="sbEndpointInfo">The Service Bus endpoint details.</param>
        /// <returns>An instance of the communication channel of a specified type that is bound to the specified endpoint.</returns>
        public static T CreateServiceBusClient <T>(ServiceBusEndpointInfo sbEndpointInfo) where T : IClientChannel
        {
            ChannelFactory <T> clientChannelFactory = CreateServiceBusClientChannelFactory <T>(sbEndpointInfo);

            return(clientChannelFactory.CreateChannel());
        }
Пример #20
0
        /// <summary>
        /// Returns a client communication channel of type <typeparamref name="T"/> for communication with the specified Service Bus one-way event relay endpoint.
        /// </summary>
        /// <typeparam name="T">The type of the client communication channel. Must inherit from service contract as well as <see cref="System.ServiceModel.IClientChannel"/>.</typeparam>
        /// <param name="sbEndpointInfo">The Service Bus endpoint details.</param>
        /// <returns>An instance of the communication channel of a specified type that is bound to the specified endpoint.</returns>
        public static T CreateServiceBusEventRelayClient <T>(ServiceBusEndpointInfo sbEndpointInfo) where T : IClientChannel
        {
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");

            return(CreateServiceBusEventRelayClient <T>(sbEndpointInfo.ServiceNamespace, sbEndpointInfo.ServicePath, sbEndpointInfo.IssuerName, sbEndpointInfo.IssuerSecret));
        }
Пример #21
0
 /// <summary>
 /// Initializes a new instance of a <see cref="InterRoleCommunicationExtension"/> object with the specified Service Bus topic endpoint and defaults settings.
 /// </summary>
 /// <param name="serviceBusEndpoint">The Service Bus topic endpoint using which the IRC component will be providing inter-role communication.</param>
 public InterRoleCommunicationExtension(ServiceBusEndpointInfo serviceBusEndpoint)
     : this(serviceBusEndpoint, InterRoleCommunicationSettings.Default)
 {
 }
        public static void MyClassInitialize(TestContext testContext)
        {
            var serviceBusSettings = ConfigurationManager.GetSection(ServiceBusConfigurationSettings.SectionName) as ServiceBusConfigurationSettings;

            topicEndpoint = serviceBusSettings.Endpoints.Get(serviceBusSettings.DefaultEndpoint);
        }
Пример #23
0
 /// <summary>
 /// Initializes a new instance of the reliable Windows Azure Service Bus client component to communicate with the specified Service Bus endpoint.
 /// No retry policy will be enforced when using this constructor overload.
 /// </summary>
 /// <param name="sbEndpointInfo">The endpoint details.</param>
 public ReliableServiceBusClient(ServiceBusEndpointInfo sbEndpointInfo)
     : this(sbEndpointInfo, RetryPolicy.NoRetry)
 {
 }
Пример #24
0
 public static ServiceHost CreateServiceBusEventRelayHost <T>(ServiceBusEndpointInfo sbEndpointInfo)
 {
     return(CreateServiceBusEventRelayHost <T>(sbEndpointInfo.ServiceNamespace, sbEndpointInfo.ServicePath, sbEndpointInfo.IssuerName, sbEndpointInfo.IssuerSecret));
 }
Пример #25
0
 public static ServiceHost CreateServiceBusEventRelayHost(ServiceBusEndpointInfo sbEndpointInfo, Type serviceType)
 {
     return(CreateServiceBusEventRelayHost(sbEndpointInfo.ServiceNamespace, sbEndpointInfo.ServicePath, sbEndpointInfo.IssuerName, sbEndpointInfo.IssuerSecret, serviceType));
 }
Пример #26
0
 public static ServiceHost CreateServiceBusHost <T>(ServiceBusEndpointInfo sbEndpointInfo)
 {
     return(CreateServiceBusHost(sbEndpointInfo, typeof(T)));
 }
Пример #27
0
        /// <summary>
        /// Notifies this extension component that it has been registered in the owner's collection of extensions.
        /// </summary>
        /// <param name="owner">The extensible owner object that aggregates this extension.</param>
        public void Attach(IExtensibleCloudServiceComponent owner)
        {
            owner.Extensions.Demand <IRoleConfigurationSettingsExtension>();
            IRoleConfigurationSettingsExtension roleConfigExtension = owner.Extensions.Find <IRoleConfigurationSettingsExtension>();

            this.serviceBusEndpoint = roleConfigExtension.GetServiceBusEndpoint(WellKnownEndpointName.InterRoleCommunication);
            this.retryPolicy        = roleConfigExtension.CommunicationRetryPolicy;

            if (this.serviceBusEndpoint != null)
            {
                // Configure Service Bus credentials and entity URI.
                var credentials = TransportClientCredentialBase.CreateSharedSecretCredential(this.serviceBusEndpoint.IssuerName, this.serviceBusEndpoint.IssuerSecret);
                var address     = ServiceBusEnvironment.CreateServiceUri(WellKnownProtocolScheme.ServiceBus, this.serviceBusEndpoint.ServiceNamespace, String.Empty);

                // Configure Service Bus messaging factory and namespace client which is required for subscription management.
                this.messagingFactory = MessagingFactory.Create(address, credentials);
                this.managementClient = new ServiceBusNamespaceClient(address, credentials);

                ConfigureTopicClient();
                ConfigureSubscriptionClient(this.ircSubscription = ConfigureSubscription(String.Concat(SubscriptionNamePrefix, this.senderInstanceID)));

                // Configure event receive action.
                this.receiveAction = (() =>
                {
                    BrokeredMessage msg = null;

                    this.retryPolicy.ExecuteAction(() =>
                    {
                        // Make sure we are not told to stop receiving while we are retrying.
                        if (!cts.IsCancellationRequested)
                        {
                            if (EventReceiver.TryReceive(Settings.EventWaitTimeout, out msg))
                            {
                                try
                                {
                                    // Make sure we are not told to stop receiving while we were waiting for a new message.
                                    if (!cts.IsCancellationRequested)
                                    {
                                        // Extract the event data from brokered message.
                                        InterRoleCommunicationEvent e = msg.GetBody <InterRoleCommunicationEvent>();

                                        // Notify all registered subscribers.
                                        NotifySubscribers(e);

                                        // Mark brokered message as complete.
                                        msg.Complete(this.retryPolicy);
                                    }
                                    else
                                    {
                                        msg.Defer(this.retryPolicy);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // Abandons a brokered message and unlocks the message.
                                    msg.Abandon(this.retryPolicy);

                                    // Log an error.
                                    TraceManager.ServiceComponent.TraceError(ex);
                                }
                            }
                        }
                    });
                });

                // Configure event receive complete action.
                this.endReceive = ((ar) =>
                {
                    this.receiveAction.EndInvoke(ar);

                    if (!cts.IsCancellationRequested)
                    {
                        this.receiveHandle = this.receiveAction.BeginInvoke(this.endReceive, null);
                    }
                });

                // Configure event send action.
                this.sendAction = ((e) =>
                {
                    this.retryPolicy.ExecuteAction(() => { EventSender.Send(e); });
                });

                // Configure event send complete action.
                this.endSend = ((ar) =>
                {
                    sendAction.EndInvoke(ar);
                });
            }
            else
            {
                throw new CloudApplicationException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.SpecifiedServiceBusEndpointNotFound, WellKnownEndpointName.InterRoleCommunication, ServiceBusConfigurationSettings.SectionName));
            }
        }
Пример #28
0
        /// <summary>
        /// Initializes a new instance of the trace listener using the specified configuration settings.
        /// </summary>
        /// <param name="diagnosticServiceEndpoint">The name of the Service Bus endpoint definition that corresponds to the on-premises hosted diagnostic service.</param>
        /// <param name="diagnosticStorageAccount">The name of the storage account in which diagnostic data will be queued before relayed to the on-premises hosted diagnostic service.</param>
        /// <param name="inMemoryQueueCapacity">The maximum capacity of the non-durable in-memory queue in which trace events are being stored before they are persisted into an Azure queue.</param>
        /// <param name="inMemoryQueueListenerSleepTimeout">The interval in milliseconds during which a dequeue thread is waiting for new events in the in-memory queue.</param>
        /// <param name="diagQueueEventBatchSize">The maximum number of trace events in a batch that is submitted to the on-premises hosted diagnostic service.</param>
        /// <param name="diagQueueListenerSleepTimeout">The interval in milliseconds during which a dequeue thread is waiting for new events to be deposited into the Azure queue.</param>
        public OnPremisesBufferedTraceListener(string diagnosticServiceEndpoint, string diagnosticStorageAccount, int inMemoryQueueCapacity, int inMemoryQueueListenerSleepTimeout, int diagQueueEventBatchSize, int diagQueueListenerSleepTimeout)
        {
            Guard.ArgumentNotNullOrEmptyString(diagnosticServiceEndpoint, "diagnosticServiceEndpoint");
            Guard.ArgumentNotZeroOrNegativeValue(inMemoryQueueCapacity, "inMemoryQueueCapacity");
            Guard.ArgumentNotZeroOrNegativeValue(inMemoryQueueListenerSleepTimeout, "inMemoryQueueListenerSleepTimeout");
            Guard.ArgumentNotZeroOrNegativeValue(diagQueueEventBatchSize, "diagQueueEventBatchSize");
            Guard.ArgumentNotZeroOrNegativeValue(diagQueueListenerSleepTimeout, "diagQueueListenerSleepTimeout");

            // Configure the general properties of the trace listener.
            Name       = ListenerName;
            NeedIndent = false;

            // Configure the in-memory queue and its parameters, set up a backup trace listener.
            this.inMemoryQueue                     = new ConcurrentQueue <TraceEventRecord>();
            this.inMemoryQueueCapacity             = inMemoryQueueCapacity;
            this.inMemoryQueueListenerSleepTimeout = inMemoryQueueListenerSleepTimeout;
            this.diagQueueEventBatchSize           = diagQueueEventBatchSize;
            this.diagQueueListenerSleepTimeout     = diagQueueListenerSleepTimeout;
            this.diagQueueName                     = GetServiceBusQueueName(CloudEnvironment.CurrentRoleInstanceId);
            this.backupTraceListener               = new CloudDiagnosticTraceListener();

            // Configure Service Bus endpoint for the Diagnostic Service.
            ServiceBusEndpointInfo diagServiceEndpointInfo = ApplicationConfiguration.Current.ServiceBusSettings.Endpoints[diagnosticServiceEndpoint];

            // Validate Service Bus endpoints.
            if (null == diagServiceEndpointInfo)
            {
                throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.SpecifiedServiceBusEndpointNotFound, diagnosticServiceEndpoint, ServiceBusConfigurationSettings.SectionName));
            }

            // Retrieve the storage account settings from application configuration.
            StorageAccountConfigurationSettings storageSettings = ApplicationConfiguration.Current.GetConfigurationSection <StorageAccountConfigurationSettings>(StorageAccountConfigurationSettings.SectionName);

            // Validate the presence of storage account settings.
            if (null == storageSettings)
            {
                throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ConfigSectionNotFoundInConfigSource, StorageAccountConfigurationSettings.SectionName));
            }

            // Determine the storage account for storing tracing data. By default, assume that storage account is defined in the trace listener configuration.
            string diagStorageAccountName = diagnosticStorageAccount;

            // If storage account is not defined in the trace listener configuration, switch to the storage account specified in the Application Diagnostic Settings section.
            if (String.IsNullOrEmpty(diagStorageAccountName))
            {
                // Retrieve the diagnostic settings from application configuration.
                ApplicationDiagnosticSettings diagSettings = ApplicationConfiguration.Current.GetConfigurationSection <ApplicationDiagnosticSettings>(ApplicationDiagnosticSettings.SectionName);

                // Validate the presence of diagnostic settings.
                if (null == diagSettings)
                {
                    throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ConfigSectionNotFoundInConfigSource, ApplicationDiagnosticSettings.SectionName));
                }

                diagStorageAccountName = diagSettings.DiagnosticStorageAccount;
            }

            // Resolve the storage account details based on the account name defined in the diagnostic settings .
            StorageAccountInfo diagStorageAccount = storageSettings.Accounts.Get(diagStorageAccountName);

            // Validate storage account details.
            if (null == diagStorageAccount)
            {
                throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.StorageAccountNotFoundInConfigSource, diagStorageAccountName));
            }

            // Configure retry policies.
            this.sbRetryPolicy                   = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(DefaultRetryCount);
            this.queueRetryPolicy                = new RetryPolicy <StorageTransientErrorDetectionStrategy>(DefaultRetryCount);
            this.sbRetryPolicy.RetryOccurred    += HandleServiceBusEndpointRetryState;
            this.queueRetryPolicy.RetryOccurred += HandleCloudQueueRetryState;

            // Configure Service Bus and Message Queue clients.
            this.diagnosticService   = new ReliableServiceBusClient <IDiagnosticLoggingServiceChannel>(diagServiceEndpointInfo, this.sbRetryPolicy);
            this.diagQueueStorage    = new ReliableCloudQueueStorage(diagStorageAccount, this.queueRetryPolicy);
            this.diagQueueReaderDone = new ManualResetEvent(false);
            this.diagQueueWriterDone = new ManualResetEvent(false);

            // Ensure that destination cloud queue exists, create if necessary.
            this.diagQueueStorage.CreateQueue(this.diagQueueName);

            // Enable background listeners to run.
            this.isRunning = true;

            StartInMemoryQueueListener();
            StartServiceBusQueueListener();
        }