Пример #1
0
 public static MessagingFactory CreateMessagingFactory()
 {
     var messagingFactorySettings = new MessagingFactorySettings();
     messagingFactorySettings.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(Issuer, Key);
     var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty);
     return MessagingFactory.Create(serviceUri, messagingFactorySettings);
 }
		public AzureServiceBusTopicController()
		{
			string issuer = ConfigurationManager.AppSettings["ServiceBusIssuer"];
			var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(issuer, ConfigurationManager.AppSettings["ServiceBusSecret"]);
			_address = $"sb://{ConfigurationManager.AppSettings["ServiceBusName"]}.servicebus.windows.net";
			_settings = new MessagingFactorySettings();
			_settings.NetMessagingTransportSettings.BatchFlushInterval = TimeSpan.Zero;
			_settings.TokenProvider = tokenProvider;
		}
Пример #3
0
        static void Main(string[] args)
        {
            var settings = new MessagingFactorySettings()
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sharedAccessPolicyName, sharedAccessPolicyKey),
                TransportType = TransportType.Amqp
            };
            var factory = MessagingFactory.Create(
                 ServiceBusEnvironment.CreateServiceUri("sb", eventHubNamespace, ""), settings);

            EventHubClient client = factory.CreateEventHubClient(eventHubName);

            try
            {

                List<Task> tasks = new List<Task>();
                // Send messages to Event Hub
                Console.WriteLine("Sending messages to Event Hub {0}", client.Path);
                Random random = new Random();
                //for (int i = 0; i < numberOfMessages; ++i)
                while(!Console.KeyAvailable)
                {
                    // One event per device
                    for(int devices = 0; devices < numberOfDevices; devices++)
                    {
                        // Create the device/temperature metric
                        Event info = new Event() {
                            TimeStamp = DateTime.UtcNow,
                            DeviceId = random.Next(numberOfDevices),
                            Temperature = random.Next(100)
                        };
                        // Serialize to JSON
                        var serializedString = JsonConvert.SerializeObject(info);
                        Console.WriteLine(serializedString);
                        EventData data = new EventData(Encoding.UTF8.GetBytes(serializedString))
                        {
                            PartitionKey = info.DeviceId.ToString()
                        };

                        // Send the metric to Event Hub
                        tasks.Add(client.SendAsync(data));
                    }
                    // Sleep a second
                    Thread.Sleep(1000);
                };

                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error on send: " + exp.Message);
            }
        }
Пример #4
0
        /// <summary>
        /// Create a messaging factory based on a address and token provider
        /// </summary>
        /// <param name="address">Base address</param>
        /// <param name="tokenProvider">Token provider</param>
        /// <returns>Messaging factory</returns>
        public static MessagingFactory Create(Uri address, TokenProvider tokenProvider)
        {
            MessagingFactorySettings factorySettings = new MessagingFactorySettings();

            factorySettings.TokenProvider = tokenProvider;
            factorySettings.TransportType = TransportType.Amqp;

            factorySettings.AmqpTransportSettings = new AmqpTransportSettings();
            factorySettings.AmqpTransportSettings.Port = AmqpTransportSettings.AMQPS_PORT;
            factorySettings.AmqpTransportSettings.TokenProvider = factorySettings.TokenProvider;

            return Create(address, factorySettings);
        }
 public AzureServiceBusMessageProducer(ILog logger)
 {
     this.logger = logger;
     this.configuration = AzureServiceBusMessagingGatewayConfigurationSection.GetConfiguration();
     var endpoint = ServiceBusEnvironment.CreateServiceUri("sb", this.configuration.Namespace.Name, String.Empty);
     var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(this.configuration.SharedAccessPolicy.Name, this.configuration.SharedAccessPolicy.Key);
     var settings = new MessagingFactorySettings
     {
         TransportType = TransportType.Amqp,
         OperationTimeout = TimeSpan.FromMinutes(5),
         TokenProvider = tokenProvider
     };
     this.factory = MessagingFactory.Create(endpoint, settings);
 }
Пример #6
0
        public ConnectForm(ServiceBusHelper serviceBusHelper, ConfigFileUse configFileUse)
        {
            InitializeComponent();

            this.configFileUse = configFileUse;
            SetConfigFileUseLabelText(lblConfigFileUse);

            this.serviceBusHelper = serviceBusHelper;
            cboServiceBusNamespace.Items.Add(SelectServiceBusNamespace);
            cboServiceBusNamespace.Items.Add(EnterConnectionString);
            if (serviceBusHelper.ServiceBusNamespaces != null)
            {
                // ReSharper disable CoVariantArrayConversion
                cboServiceBusNamespace.Items.AddRange(serviceBusHelper.ServiceBusNamespaces.Keys.OrderBy(s => s).ToArray());
                // ReSharper restore CoVariantArrayConversion
            }

            ConnectivityMode = ServiceBusHelper.ConnectivityMode;
            cboConnectivityMode.DataSource   = Enum.GetValues(typeof(ConnectivityMode));
            cboConnectivityMode.SelectedItem = ConnectivityMode;

            cboTransportType.DataSource = Enum.GetValues(typeof(TransportType));
            var settings = new MessagingFactorySettings();

            cboTransportType.SelectedItem = settings.TransportType;

            cboServiceBusNamespace.SelectedIndex = connectionStringIndex > 0 ? connectionStringIndex : 0;
            if (cboServiceBusNamespace.Text == EnterConnectionString)
            {
                txtUri.Text = connectionString;
            }

            txtQueueFilterExpression.Text        = FilterExpressionHelper.QueueFilterExpression;
            txtTopicFilterExpression.Text        = FilterExpressionHelper.TopicFilterExpression;
            txtSubscriptionFilterExpression.Text = FilterExpressionHelper.SubscriptionFilterExpression;
            btnOk.Enabled = cboServiceBusNamespace.SelectedIndex > 1 ||
                            (cboServiceBusNamespace.Text == EnterConnectionString &&
                             !string.IsNullOrWhiteSpace(connectionString));

            foreach (var item in ConfigurationHelper.Entities)
            {
                cboSelectedEntities.Items.Add(item);
            }

            foreach (var item in MainForm.SingletonMainForm.SelectedEntities)
            {
                cboSelectedEntities.CheckBoxItems[item].Checked = true;
            }
        }
        public AzureServiceBusMessageProducer(ILog logger)
        {
            this.logger        = logger;
            this.configuration = AzureServiceBusMessagingGatewayConfigurationSection.GetConfiguration();
            var endpoint      = ServiceBusEnvironment.CreateServiceUri("sb", this.configuration.Namespace.Name, String.Empty);
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(this.configuration.SharedAccessPolicy.Name, this.configuration.SharedAccessPolicy.Key);
            var settings      = new MessagingFactorySettings
            {
                TransportType    = TransportType.Amqp,
                OperationTimeout = TimeSpan.FromMinutes(5),
                TokenProvider    = tokenProvider
            };

            this.factory = MessagingFactory.Create(endpoint, settings);
        }
        public MessagingFactory Create(Address address)
        {
            var potentialConnectionString = address.Machine;
            var namespaceManager = createNamespaceManagers.Create(potentialConnectionString);

            var settings = new MessagingFactorySettings
            {
                TokenProvider = namespaceManager.Settings.TokenProvider,
                NetMessagingTransportSettings =
                {
                    BatchFlushInterval = TimeSpan.FromSeconds(0.1)
                }
            };
            return MessagingFactory.Create(namespaceManager.Address, settings);
        }
Пример #9
0
        static void ClientCredentialsCertScenario()
        {
            ClientCredential         clientCredential         = new ClientCredential(ClientId, ConfigurationManager.AppSettings["clientSecret"]);
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateAadTokenProvider(
                    new AuthenticationContext($"https://login.windows.net/{TenantId}"),
                    clientCredential,
                    ServiceAudience.EventHubsAudience
                    ),
                TransportType = TransportType.Amqp
            };

            SendReceive(messagingFactorySettings);
        }
        public MessagingFactoryCreator(IManageNamespaceManagerLifeCycleInternal namespaceManagers, ReadOnlySettings settings)
        {
            this.namespaceManagers = namespaceManagers;
            var transportType      = settings.Get <TransportType>(WellKnownConfigurationKeys.Connectivity.TransportType);
            var batchFlushInterval = settings.Get <TimeSpan>(WellKnownConfigurationKeys.Connectivity.MessagingFactories.BatchFlushInterval);

            if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.MessagingFactories.RetryPolicy))
            {
                retryPolicy = settings.Get <RetryPolicy>(WellKnownConfigurationKeys.Connectivity.MessagingFactories.RetryPolicy);
            }

            if (settings.HasExplicitValue(WellKnownConfigurationKeys.Connectivity.MessagingFactories.MessagingFactorySettingsFactory))
            {
                settingsFactory = settings.Get <Func <string, MessagingFactorySettings> >(WellKnownConfigurationKeys.Connectivity.MessagingFactories.MessagingFactorySettingsFactory);
            }
            else
            {
                settingsFactory = namespaceName =>
                {
                    var factorySettings = new MessagingFactorySettings
                    {
                        TransportType = transportType
                    };

                    switch (transportType)
                    {
                    case TransportType.NetMessaging:
                        factorySettings.NetMessagingTransportSettings = new NetMessagingTransportSettings
                        {
                            BatchFlushInterval = batchFlushInterval
                        };
                        break;

                    case TransportType.Amqp:
                        factorySettings.AmqpTransportSettings = new AmqpTransportSettings
                        {
                            BatchFlushInterval = batchFlushInterval
                        };
                        break;

                    default:
                        break;
                    }

                    return(factorySettings);
                };
            }
        }
		AzureServiceBusEndpointAddressImpl([NotNull] Data data,
			AddressType addressType)
		{
			if (data == null)
				throw new ArgumentNullException("data");

			_data = data;

			_tp = TokenProvider.CreateSharedSecretTokenProvider(_data.UsernameIssuer,
			                                                    _data.PasswordSharedSecret);

			var sbUri = ServiceBusEnvironment.CreateServiceUri("sb", _data.Namespace, string.Empty);

			var mfs = new MessagingFactorySettings
				{
					TokenProvider = _tp,
					NetMessagingTransportSettings =
						{
							// todo: configuration setting
							BatchFlushInterval = 50.Milliseconds()
						},
					OperationTimeout = 3.Seconds()
				};
			_mff = () => MessagingFactory.Create(sbUri, mfs);

			_nm = new NamespaceManager(sbUri, _tp);

			string suffix = "";
			if (addressType == AddressType.Queue)
				_queueDescription = new QueueDescriptionImpl(data.QueueOrTopicName);
			else
			{
				_topicDescription = new TopicDescriptionImpl(data.QueueOrTopicName);
				suffix = "?topic=true";
			}

			_rebuiltUri = new Uri(string.Format("azure-sb://{0}:{1}@{2}/{3}{4}", 
				data.UsernameIssuer,
				data.PasswordSharedSecret,
				data.Namespace,
				data.QueueOrTopicName,
				suffix));

			_friendlyUri = new Uri(string.Format("azure-sb://{0}/{1}{2}",
				data.Namespace,
				data.QueueOrTopicName,
				suffix));
		}
Пример #12
0
        /// <summary>
        /// Helper function to create a messaging factory
        /// </summary>
        /// <returns>create messaging factory task</returns>
        private async Task <MessagingFactory> CreateMessagingFactory()
        {
            int batchIntervalMs = this.batchIntervalMs;

            string[] connectionStringSplit = this.connectionString.Split(';');
            string   endpoint = null;
            string   keyName  = null;
            string   keyValue = null;

            foreach (string str in connectionStringSplit)
            {
                if (str.StartsWith("Endpoint="))
                {
                    endpoint = str.Substring("Endpoint=".Length);
                }
                else if (str.StartsWith("SharedAccessKeyName="))
                {
                    keyName = str.Substring("SharedAccessKeyName=".Length);
                }
                else if (str.StartsWith("SharedAccessKey="))
                {
                    keyValue = str.Substring("SharedAccessKey=".Length);
                }
            }

            if (endpoint == null || keyName == null || keyValue == null)
            {
                throw new ArgumentException($"Invalid connection string: endpoint = {endpoint}, keyName = {keyName}, keyValue = {keyValue}");
            }

            TimeSpan batchInterval = TimeSpan.Zero;

            if (batchIntervalMs > 0)
            {
                batchInterval = TimeSpan.FromMilliseconds(batchIntervalMs);
            }

            TokenProvider            credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, keyValue);
            MessagingFactorySettings mfs         = new MessagingFactorySettings()
            {
                TokenProvider = credentials
            };

            mfs.NetMessagingTransportSettings.BatchFlushInterval = batchInterval;
            MessagingFactory messagingFactory = await MessagingFactory.CreateAsync(endpoint, mfs);

            return(messagingFactory);
        }
Пример #13
0
        private static MessagingFactory CreateMessagingFactoryWithMsiTokenProvider()
        {
            // create a parameter object for the messaging factory that configures
            // the MSI token provider for Service Bus and use of the AMQP protocol:
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience),
                TransportType = TransportType.Amqp
            };

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

            return(messagingFactory);
        }
Пример #14
0
        static void ClientAssertionCertScenario()
        {
            X509Certificate2           certificate = GetCertificate();
            ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(ClientId, certificate);
            MessagingFactorySettings   messagingFactorySettings   = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateAadTokenProvider(
                    new AuthenticationContext($"https://login.windows.net/{TenantId}"),
                    clientAssertionCertificate,
                    ServiceAudience.EventHubsAudience
                    ),
                TransportType = TransportType.Amqp
            };

            SendReceive(messagingFactorySettings);
        }
Пример #15
0
        private static MessagingFactory GetMessagingFactory(string connectionString, TimeSpan?batchFlushInterval)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            var mfs = new MessagingFactorySettings
            {
                TokenProvider = namespaceManager.Settings.TokenProvider
            };

            if (batchFlushInterval.HasValue)
            {
                mfs.NetMessagingTransportSettings.BatchFlushInterval = batchFlushInterval.Value;
            }
            var messagingFactory = MessagingFactory.Create(namespaceManager.Address, mfs);

            return(messagingFactory);
        }
Пример #16
0
        static void UserInteractiveLoginScenario()
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateAadTokenProvider(
                    new AuthenticationContext($"https://login.windows.net/{TenantId}"),
                    ClientId,
                    new Uri("http://eventhubs.microsoft.com"),
                    new PlatformParameters(PromptBehavior.SelectAccount),
                    ServiceAudience.EventHubsAudience
                    ),
                TransportType = TransportType.Amqp
            };

            SendReceive(messagingFactorySettings);
        }
Пример #17
0
        async Task UserInteractiveLoginScenario()
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateAadTokenProvider(
                    new AuthenticationContext($"https://login.windows.net/{TenantId}"),
                    ClientId,
                    new Uri(ConfigurationManager.AppSettings["redirectURI"]),
                    new PlatformParameters(PromptBehavior.SelectAccount),
                    ServiceAudience.ServiceBusAudience
                    ),
                TransportType = TransportType.Amqp
            };

            await SendReceive(messagingFactorySettings);
        }
Пример #18
0
        Task <MessagingFactory> CreateNetMessagingFactory()
        {
            if (Settings.TransportType == TransportType.NetMessaging)
            {
                return(_messagingFactory.Value);
            }

            var mfs = new MessagingFactorySettings
            {
                TokenProvider    = Settings.TokenProvider,
                OperationTimeout = Settings.OperationTimeout,
                TransportType    = TransportType.NetMessaging,
                NetMessagingTransportSettings = Settings.NetMessagingTransportSettings
            };

            return(CreateFactory(mfs));
        }
Пример #19
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience),
                TransportType = TransportType.Amqp
            };

            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/",
                                                                        messagingFactorySettings);

            EventHubClient ehClient = messagingFactory.CreateEventHubClient(txtEventHub.Text);

            ehClient.Send(new EventData(Encoding.UTF8.GetBytes(txtData.Text)));
            ehClient.Close();
            messagingFactory.Close();
        }
Пример #20
0
        /// <summary>
        /// Create new client for servicebus connection. This method is slow!
        /// </summary>
        /// <param name="connectionString">Connection string</param>
        /// <param name="operationTimeoutForClients">Operation timeout for clients</param>
        /// <returns>Object that can handle messaging to the service bus</returns>
        internal static MessagingFactory CreateMessagingFactoryWithTimeout(string connectionString, TimeSpan operationTimeoutForClients)
        {
            var connBuilder     = new ServiceBusConnectionStringBuilder(connectionString);
            var factorySettings = new MessagingFactorySettings
            {
                OperationTimeout = operationTimeoutForClients
            };

            if (connBuilder.SharedAccessKey != null)
            {
                factorySettings.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(connBuilder.SharedAccessKeyName, connBuilder.SharedAccessKey);
            }
            else if (connBuilder.SharedSecretIssuerName != null)
            {
                factorySettings.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(connBuilder.SharedSecretIssuerName, connBuilder.SharedSecretIssuerSecret);
            }
            else if (connBuilder.OAuthUsername != null)
            {
                if (!string.IsNullOrEmpty(connBuilder.OAuthDomain))
                {
                    TokenProvider.CreateOAuthTokenProvider(connBuilder.StsEndpoints,
                                                           new NetworkCredential(connBuilder.OAuthUsername,
                                                                                 connBuilder.OAuthPassword,
                                                                                 connBuilder.OAuthDomain));
                }
                else
                {
                    TokenProvider.CreateOAuthTokenProvider(connBuilder.StsEndpoints,
                                                           new NetworkCredential(connBuilder.OAuthUsername,
                                                                                 connBuilder.OAuthPassword));
                }
            }
            else if (connBuilder.StsEndpoints.Count > 0)
            {
                factorySettings.TokenProvider = TokenProvider.CreateWindowsTokenProvider(connBuilder.StsEndpoints);
            }


            factorySettings.EnableAdditionalClientTimeout = true;

            MessagingFactory messageFactory = MessagingFactory.Create(connBuilder.GetAbsoluteRuntimeEndpoints(), factorySettings);

            messageFactory.RetryPolicy = RetryPolicy.Default;

            return(messageFactory);
        }
Пример #21
0
        private static void Main(string[] args)
        {
            var cts = new CancellationTokenSource();

            for (var i = 0; i < 1; i++)
            {
                Task.Factory.StartNew(async partition =>
                {
                    LogEvent logEvent;

                    var settings = new MessagingFactorySettings
                    {
                        TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("LogProcessor", "0ihHa1HNpUyhTYELV+FjPbjJhtt0N5PgHoiPaCwuZNs="),
                        TransportType = TransportType.Amqp
                    };

                    var factory  = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", "logs-ns", string.Empty), settings);
                    var client   = factory.CreateEventHubClient("logs");
                    var group    = client.GetDefaultConsumerGroup();
                    var receiver = await group.CreateReceiverAsync(partition.ToString(), DateTime.UtcNow);

                    Console.WriteLine("Worker process started for partition {0} and consumer group {1}", partition, group.GroupName);

                    while (!cts.IsCancellationRequested)
                    {
                        foreach (var eventData in await receiver.ReceiveAsync(10, new TimeSpan(0, 0, 0, 0, 200)))
                        {
                            logEvent = JsonConvert.DeserializeObject <LogEvent>(Encoding.Unicode.GetString(eventData.GetBytes()));

                            Console.WriteLine("{0} [{1},{2}] {3}: {6}",
                                              DateTime.Now,
                                              eventData.PartitionKey, partition,
                                              logEvent.MachineName, logEvent.SiteName, logEvent.InstanceId, logEvent.Value);
                        }
                    }

                    await receiver.CloseAsync();
                    Console.WriteLine("Worker process finished for partition: {0}", partition);
                }, i as object, TaskCreationOptions.LongRunning);
            }

            Console.ReadKey();
            cts.Cancel();
            Console.ReadKey();
        }
        /// <summary>
        /// Create a messaging factory based on a address and related settings
        /// </summary>
        /// <param name="address">Base address</param>
        /// <param name="settings">Messaging factory settings</param>
        /// <returns>Messaging factory</returns>
        public static MessagingFactory Create(Uri address, MessagingFactorySettings settings)
        {
            MessagingFactory factory;

            settings.TransportType = TransportType.Amqp;

            if (settings.AmqpTransportSettings == null)
            {
                settings.AmqpTransportSettings = new AmqpTransportSettings();
                settings.AmqpTransportSettings.Port = AmqpTransportSettings.AMQPS_PORT;
                ((IServiceBusSecuritySettings)settings.AmqpTransportSettings).TokenProvider = settings.TokenProvider;
            }

            factory = new AmqpMessagingFactory(address, settings.AmqpTransportSettings);
            factory.settings = settings;

            return factory;
        }
Пример #23
0
        static void UserPasswordCredentialScenario()
        {
            UserPasswordCredential userPasswordCredential = new UserPasswordCredential(
                ConfigurationManager.AppSettings["userName"],
                ConfigurationManager.AppSettings["password"]
                );
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateAadTokenProvider(
                    new AuthenticationContext($"https://login.windows.net/{TenantId}"),
                    ClientId,
                    userPasswordCredential,
                    ServiceAudience.EventHubsAudience
                    ),
                TransportType = TransportType.Amqp
            };

            SendReceive(messagingFactorySettings);
        }
Пример #24
0
        Task <MessagingFactory> CreateNetMessagingFactory()
        {
            if (_settings.TransportType == TransportType.NetMessaging)
            {
                return(_messagingFactory.Value);
            }

            var mfs = new MessagingFactorySettings
            {
                TokenProvider    = _settings.TokenProvider,
                OperationTimeout = _settings.OperationTimeout,
                TransportType    = TransportType.NetMessaging,
                NetMessagingTransportSettings = new NetMessagingTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromMilliseconds(50)
                }
            };

            return(CreateFactory(mfs));
        }
Пример #25
0
        async Task SendReceive(MessagingFactorySettings messagingFactorySettings)
        {
            MessagingFactory mf = MessagingFactory.Create($"sb://{ServiceBusNamespace}/", messagingFactorySettings);

            this.receiveClient = mf.CreateQueueClient(QueueName, ReceiveMode.PeekLock);
            this.InitializeReceiver();

            this.sendClient = mf.CreateQueueClient(QueueName);
            var sendTask = this.SendMessagesAsync();

            Console.ReadKey();

            // shut down the receiver, which will stop the OnMessageAsync loop
            await this.receiveClient.CloseAsync();

            // wait for send work to complete if required
            await sendTask;

            await this.sendClient.CloseAsync();
        }
Пример #26
0
        Task <MessagingFactory> CreateMessagingFactory()
        {
            var mfs = new MessagingFactorySettings
            {
                TokenProvider         = _settings.TokenProvider,
                OperationTimeout      = _settings.OperationTimeout,
                TransportType         = TransportType.Amqp,
                AmqpTransportSettings = new AmqpTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromMilliseconds(50)
                }
            };

            var builder = new UriBuilder(_settings.ServiceUri)
            {
                Path = ""
            };

            return(MessagingFactory.CreateAsync(builder.Uri, mfs));
        }
Пример #27
0
        public MessagingFactory GetMessagingFactory(long timeoutSeconds)
        {
            if (!string.IsNullOrWhiteSpace(serviceBroker.Service.ServiceConfiguration[ServiceConfigurationSettings.ConnectionString].ToString()))
            {
                return(MessagingFactory.CreateFromConnectionString(serviceBroker.Service.ServiceConfiguration[ServiceConfigurationSettings.ConnectionString].ToString()));
            }

            try
            {
                MessagingFactorySettings mfSettings = new MessagingFactorySettings();
                mfSettings.TokenProvider    = GetTokenProvider();
                mfSettings.OperationTimeout = GetRequestTimeout(timeoutSeconds);

                return(MessagingFactory.Create(GetServiceUri(), mfSettings));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #28
0
        static MessagingFactorySettings CreateMessagingFactorySettings(ServiceBusHostSettings settings, bool useNetMessaging = false)
        {
            var mfs = new MessagingFactorySettings
            {
                TokenProvider    = settings.TokenProvider,
                OperationTimeout = settings.OperationTimeout
            };

            if (settings.TransportType == TransportType.NetMessaging || useNetMessaging)
            {
                mfs.TransportType = TransportType.NetMessaging;
                mfs.NetMessagingTransportSettings = settings.NetMessagingTransportSettings;
            }
            else
            {
                mfs.TransportType         = TransportType.Amqp;
                mfs.AmqpTransportSettings = settings.AmqpTransportSettings;
            }

            return(mfs);
        }
Пример #29
0
        public void Connect()
        {
            Disconnect();

            _log.DebugFormat("Connecting to '{0}' at {1}", _address, _serviceUri);

            _manager = new NamespaceManager(_serviceUri, _tokenProvider);

            var mfs = new MessagingFactorySettings
            {
                TokenProvider         = _tokenProvider,
                OperationTimeout      = 3.Seconds(),
                TransportType         = TransportType.Amqp,
                AmqpTransportSettings = new AmqpTransportSettings
                {
                    BatchFlushInterval = 50.Milliseconds()
                },
            };

            _factory = MessagingFactory.Create(_serviceUri, mfs);
        }
Пример #30
0
        public CreateLinkSettings(SbmpMessagingFactory messagingFactory, string entityPath, string entityName, Microsoft.ServiceBus.Messaging.Sbmp.LinkInfo linkInfo, Lazy <SbmpMessageCreator> controlMessageCreator = null)
        {
            this.LinkInfo         = linkInfo;
            this.MessagingFactory = messagingFactory;
            EndpointAddress endpointAddress = messagingFactory.CreateEndpointAddress(entityPath);

            this.EntityName            = entityName;
            this.EntityPath            = entityPath;
            this.ControlMessageCreator = controlMessageCreator;
            MessagingFactorySettings settings = this.MessagingFactory.GetSettings();

            this.MessageCreator = new SbmpMessageCreator(this.MessagingFactory, this.MessagingFactory.BaseAddress, this.MessagingFactory.MessageVersion, this.MessagingFactory.Settings, settings.EnableAdditionalClientTimeout, endpointAddress);
            if (this.LinkInfo != null)
            {
                this.MessageCreator = this.MessageCreator.CreateLinkMessageCreator(this.LinkInfo);
                if (settings.NetMessagingTransportSettings.GatewayMode)
                {
                    this.LinkInfo.IsHttp     = true;
                    this.LinkInfo.ApiVersion = ApiVersionHelper.CurrentRuntimeApiVersion;
                }
            }
        }
Пример #31
0
        static async Task EventHubSendReceiveLoopAsync()
        {
            var connectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString)
            {
                EntityPath = eventhubName
            };

            var settings = new MessagingFactorySettings();

            settings.TransportType = Microsoft.ServiceBus.Messaging.TransportType.Amqp;
            settings.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey);
            var factory  = MessagingFactory.Create(connectionStringBuilder.Endpoints.FirstOrDefault <Uri>().ToString(), settings);
            var ehClient = factory.CreateEventHubClient(eventhubName);

            var sasTP = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey);
            var token = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey,
                                                                                    connectionStringBuilder.Endpoints.FirstOrDefault <Uri>().ToString(), TimeSpan.FromHours(12));

            await Task.WhenAll(
                SendMessagesRestAync($"https://{connectionStringBuilder.Endpoints.FirstOrDefault<Uri>().Host}/{connectionStringBuilder.EntityPath}", token)
                , ReceiveMessagesAsync(ehClient));
        }
Пример #32
0
        protected void btnReceive_Click(object sender, EventArgs e)
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience),
                TransportType = TransportType.Amqp
            };

            messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false;

            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/",
                                                                        messagingFactorySettings);

            EventHubClient        ehClient      = messagingFactory.CreateEventHubClient(txtEventHub.Text);
            EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup();
            int partitions = int.Parse(txtPartitions.Text);

            string[] Offsets = new string[partitions];
            if (!string.IsNullOrEmpty(hiddenStartingOffset.Value))
            {
                Offsets = hiddenStartingOffset.Value.Split(',');
            }
            System.Threading.Tasks.Parallel.ForEach(Enumerable.Range(0, int.Parse(txtPartitions.Text)), partitionId =>
            {
                EventHubReceiver receiver = consumerGroup.CreateReceiver($"{partitionId}", Offsets[partitionId] == null ? "-1" : Offsets[partitionId]);
                EventData data            = receiver.Receive(TimeSpan.FromSeconds(1));
                if (data != null)
                {
                    Offsets[partitionId]  = data.Offset;
                    txtReceivedData.Text += $"PartitionId: {partitionId} Seq#:{data.SequenceNumber} data:{Encoding.UTF8.GetString(data.GetBytes())}{Environment.NewLine}";
                }
                receiver.Close();
            });

            hiddenStartingOffset.Value = string.Join(",", Offsets);
            ehClient.Close();
            messagingFactory.Close();
        }
Пример #33
0
        public AzureAdvancedBus(IAzureNetQLogger logger, IConnectionConfiguration configuration)
        {
            this.namespaceManager = NamespaceManager.CreateFromConnectionString(configuration.ConnectionString);

            var pairs = configuration.ConnectionString.Split(';').Select(o => o.Split('=')).Where(o => o.Length > 1);

            var dictionary = pairs.ToDictionary(key => key[0], value => value[1]);
            var address    = this.namespaceManager.Address;

            int port;

            if (dictionary.ContainsKey("Endpoint") && dictionary.ContainsKey("RuntimePort") &&
                int.TryParse(dictionary["RuntimePort"], out port))
            {
                var template = new Uri(string.Format("{0}", dictionary["Endpoint"]));
                address = new UriBuilder(template.Scheme, template.Host, port, template.PathAndQuery).Uri;
            }

            var mfs = new MessagingFactorySettings
            {
                TokenProvider = this.namespaceManager.Settings.TokenProvider,
                NetMessagingTransportSettings =
                {
                    BatchFlushInterval =
                        configuration
                        .BatchingInterval
                }
            };

            this.messagingFactory = MessagingFactory.Create(address, mfs);

            this.queues        = new ConcurrentDictionary <string, QueueClient>();
            this.topics        = new ConcurrentDictionary <string, TopicClient>();
            this.subscriptions = new ConcurrentDictionary <string, SubscriptionClient>();

            this.logger        = logger;
            this.configuration = configuration;
        }
Пример #34
0
        static void SendReceive(MessagingFactorySettings messagingFactorySettings)
        {
            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{EventHubNamespace}/",
                                                                        messagingFactorySettings);

            EventHubClient        ehClient      = messagingFactory.CreateEventHubClient(EventHubName);
            EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup();

            var receiveTask = Task.Factory.StartNew(() =>
            {
                string[] partitionIds = { "0", "1" };
                Parallel.ForEach(partitionIds, partitionId =>
                {
                    EventHubReceiver receiver = consumerGroup.CreateReceiver(partitionId, EventHubConsumerGroup.StartOfStream);
                    while (true)
                    {
                        EventData data = receiver.Receive(TimeSpan.FromSeconds(10));
                        if (data == null)
                        {
                            break;
                        }
                        Console.WriteLine($"Received from partition {partitionId} : " + Encoding.UTF8.GetString(data.GetBytes()));
                    }
                    receiver.Close();
                });
            });

            System.Threading.Thread.Sleep(5000);

            ehClient.Send(new EventData(Encoding.UTF8.GetBytes($"{DateTime.UtcNow}")));

            Task.WaitAll(receiveTask);

            ehClient.Close();
            messagingFactory.Close();
            Console.WriteLine("Send / Receive complete. Press enter to exit.");
            Console.ReadLine();
        }
Пример #35
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            // create a parameter object for the messaging factory that configures
            // the MSI token provider for Service Bus and use of the AMQP protocol:
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience),
                TransportType = TransportType.Amqp
            };

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

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

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

            queueClient.Close();
            messagingFactory.Close();
        }
Пример #36
0
        /// <summary>
        /// Initializes a new instance of the ServiceBusNamespace class for an on-premises namespace.
        /// </summary>
        /// <param name="connectionString">The service bus namespace connection string.</param>
        /// <param name="endpoint">The endpoint of the service bus namespace.</param>
        /// <param name="stsEndpoint">The sts endpoint of the service bus namespace.</param>
        /// <param name="runtimePort">The runtime port.</param>
        /// <param name="managementPort">The management port.</param>
        /// <param name="windowsDomain">The Windows domain or machine name.</param>
        /// <param name="windowsUsername">The Windows user name.</param>
        /// <param name="windowsPassword">The Windows user password.</param>
        /// <param name="ns">The service bus namespace.</param>
        /// <param name="transportType">The transport type to use to access the namespace.</param>
        public ServiceBusNamespace(string connectionString,
                                   string endpoint,
                                   string stsEndpoint,
                                   string runtimePort,
                                   string managementPort,
                                   string windowsDomain,
                                   string windowsUsername,
                                   string windowsPassword,
                                   string ns,
                                   TransportType transportType,
                                   bool isUserCreated = false)
        {
            ConnectionStringType = ServiceBusNamespaceType.OnPremises;
            ConnectionString     = connectionString;
            Uri = endpoint;
            var uri = new Uri(endpoint);


            if (string.IsNullOrWhiteSpace(endpoint))
            {
                Uri = ServiceBusEnvironment.CreateServiceUri(uri.Scheme, ns, null).ToString();
            }

            Namespace = ns;
            var settings = new MessagingFactorySettings();

            TransportType   = settings.TransportType;
            StsEndpoint     = stsEndpoint;
            RuntimePort     = runtimePort;
            ManagementPort  = managementPort;
            WindowsDomain   = windowsDomain;
            WindowsUserName = windowsUsername;
            WindowsPassword = windowsPassword;
            TransportType   = transportType;
            UserCreated     = isUserCreated;
        }
Пример #37
0
        async Task<MessagingFactory> CreateFactory(MessagingFactorySettings mfs)
        {
            var builder = new UriBuilder(_settings.ServiceUri) {Path = ""};

            var messagingFactory = await MessagingFactory.CreateAsync(builder.Uri, mfs).ConfigureAwait(false);

            messagingFactory.RetryPolicy = new RetryExponential(_settings.RetryMinBackoff, _settings.RetryMaxBackoff, _settings.RetryLimit);

            return messagingFactory;
        }
Пример #38
0
        /// <summary>
        /// Connects the ServiceBusHelper object to service bus namespace contained in the ServiceBusNamespaces dictionary.
        /// </summary>
        /// <param name="uri">The full uri of the service namespace.</param>
        /// <param name="issuerName">The issuer name of the shared secret credentials.</param>
        /// <param name="issuerSecret">The issuer secret of the shared secret credentials.</param>
        /// <param name="transportType">The current transport type.</param>
        /// <param name="sharedAccessKeyName">The shared access key name.</param>
        /// <param name="sharedAccessKey">The shared access key.</param>
        /// <returns>True if the operation succeeds, false otherwise.</returns>
        public bool Connect(string uri, 
                            string issuerName, 
                            string issuerSecret,
                            string sharedAccessKeyName,
                            string sharedAccessKey,
                            TransportType transportType)
        {
            Func<bool> func = (() =>
            {
                if (string.IsNullOrWhiteSpace(uri))
                {
                    throw new ArgumentException(ServiceBusUriArgumentCannotBeNull);
                }
                if (string.IsNullOrWhiteSpace(issuerName))
                {
                    throw new ArgumentException(ServiceBusIssuerNameArgumentCannotBeNull);
                }
                if (string.IsNullOrWhiteSpace(issuerSecret))
                {
                    throw new ArgumentException(ServiceBusIssuerSecretArgumentCannotBeNull);
                }

                // Create the service URI using the uri specified in the Connect form
                namespaceUri = new Uri(uri);
                if (!string.IsNullOrWhiteSpace(namespaceUri.Host) &&
                    namespaceUri.Host.Contains('.'))
                {
                    Namespace = namespaceUri.Host.Substring(0, namespaceUri.Host.IndexOf('.'));
                }

                // Create the atom feed URI using the scheme, namespace and service name (optional)
                if (uri.Substring(0, 4) != Uri.UriSchemeHttp)
                {
                    var index = uri.IndexOf("://", StringComparison.Ordinal);
                    if (index > 0)
                    {
                        uri = Uri.UriSchemeHttp + uri.Substring(index);
                    }
                }
                atomFeedUri = new Uri(uri);

                ServicePath = string.Empty;

                // Create shared secret credentials to to authenticate with the Access Control service, 
                // and acquire an access token that proves to the Service Bus insfrastructure that the 
                // the Service Bus Explorer is authorized to access the entities in the specified namespace.
                tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName,
                                                                              issuerSecret);

                currentIssuerName = issuerName;
                currentIssuerSecret = issuerSecret;
                currentSharedAccessKeyName = sharedAccessKeyName;
                currentSharedAccessKey = sharedAccessKey;
                TransportType = transportType;

                // Create and instance of the NamespaceManagerSettings which 
                // specifies service namespace client settings and metadata.
                var namespaceManagerSettings = new NamespaceManagerSettings
                {
                    TokenProvider = tokenProvider,
                    OperationTimeout = TimeSpan.FromMinutes(5)
                };

                // The NamespaceManager class can be used for managing entities, 
                // such as queues, topics, subscriptions, and rules, in your service namespace. 
                // You must provide service namespace address and access credentials in order 
                // to manage your service namespace.
                namespaceManager = new NamespaceManager(namespaceUri, namespaceManagerSettings);
                WriteToLogIf(traceEnabled, string.Format(CultureInfo.CurrentCulture, ServiceBusIsConnected, namespaceUri.AbsoluteUri));

                // The MessagingFactorySettings specifies the service bus messaging factory settings.
                var messagingFactorySettings = new MessagingFactorySettings
                {
                    TokenProvider = tokenProvider,
                    OperationTimeout = TimeSpan.FromMinutes(5)
                };
                // In the first release of the service bus, the only available transport protocol is sb 
                if (scheme == DefaultScheme)
                {
                    messagingFactorySettings.NetMessagingTransportSettings = new NetMessagingTransportSettings();
                }

                // As the name suggests, the MessagingFactory class is a Factory class that allows to create
                // instances of the QueueClient, TopicClient and SubscriptionClient classes.
                MessagingFactory = MessagingFactory.Create(namespaceUri, messagingFactorySettings);
                WriteToLogIf(traceEnabled, MessageFactorySuccessfullyCreated);
                return true;
            });
            return RetryHelper.RetryFunc(func, writeToLog);
        }
Пример #39
0
        /// <summary>
        /// Gets a new messaging factory object.
        /// </summary>
        /// <returns>A messaging factory object.</returns>
        private MessagingFactory GetMessagingFactory()
        {
            // The MessagingFactorySettings specifies the service bus messaging factory settings.
            var messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = tokenProvider,
                OperationTimeout = TimeSpan.FromMinutes(5)
            };
            // In the first release of the service bus, the only available transport protocol is sb 
            if (scheme == DefaultScheme)
            {
                messagingFactorySettings.NetMessagingTransportSettings = new NetMessagingTransportSettings();
            }

            // As the name suggests, the MessagingFactory class is a Factory class that allows to create
            // instances of the QueueClient, TopicClient and SubscriptionClient classes.
            var factory = MessagingFactory.Create(namespaceUri, messagingFactorySettings);
            WriteToLogIf(traceEnabled, MessageFactorySuccessfullyCreated);
            return factory;
        }
        /// <summary>
        /// Connects the ServiceBusHelper object to service bus namespace contained in the ServiceBusNamespaces dictionary.
        /// </summary>
        /// <param name="serviceBusNamespace">The key of the service bus namespace in the ServiceBusNamespaces dictionary.</param>
        /// <returns>True if the operation succeeds, false otherwise.</returns>
        public bool Connect(string serviceBusNamespace)
        {
            Func<bool> func = (() =>
            {
                if (string.IsNullOrEmpty(serviceBusNamespace))
                {
                    throw new ArgumentException(ServiceBusNamespaceArgumentCannotBeNull);
                }
                if (serviceBusNamespaces.ContainsKey(serviceBusNamespace))
                {
                    // Create the service URI using the scheme, namespace and service path (optional)
                    namespaceUri = ServiceBusEnvironment.CreateServiceUri(scheme,
                                                                        serviceBusNamespaces[
                                                                            serviceBusNamespace
                                                                            ].Namespace,
                                                                        serviceBusNamespaces[
                                                                            serviceBusNamespace
                                                                            ].ServicePath);
                    // Create the atom feed URI using the scheme, namespace and service path (optional)
                    atomFeedUri = ServiceBusEnvironment.CreateServiceUri("http",
                                                                        serviceBusNamespaces[
                                                                            serviceBusNamespace
                                                                            ].Namespace,
                                                                        serviceBusNamespaces[
                                                                            serviceBusNamespace
                                                                            ].ServicePath);

                    Namespace = serviceBusNamespaces[serviceBusNamespace].Namespace;
                    ServicePath = serviceBusNamespaces[serviceBusNamespace].ServicePath;

                    // Create shared secret credentials to to authenticate with the Access Control service, 
                    // and acquire an access token that proves to the Service Bus insfrastructure that the 
                    // the Service Bus Explorer is authorized to access the entities in the specified namespace.
                    tokenProvider =
                        TokenProvider.CreateSharedSecretTokenProvider(
                            serviceBusNamespaces[serviceBusNamespace].IssuerName,
                            serviceBusNamespaces[serviceBusNamespace].IssuerSecret);

                    currentIssuerName = serviceBusNamespaces[serviceBusNamespace].IssuerName;
                    currentIssuerSecret = serviceBusNamespaces[serviceBusNamespace].IssuerSecret;

                    // Create and instance of the NamespaceManagerSettings which 
                    // specifies service namespace client settings and metadata.
                    var namespaceManagerSettings = new NamespaceManagerSettings
                                                    {
                                                        TokenProvider = tokenProvider,
                                                        OperationTimeout =
                                                            TimeSpan.FromMinutes(5)
                                                    };

                    // The NamespaceManager class can be used for managing entities, 
                    // such as queues, topics, subscriptions, and rules, in your service namespace. 
                    // You must provide service namespace address and access credentials in order 
                    // to manage your service namespace.
                    namespaceManager = new NamespaceManager(namespaceUri,
                                                            namespaceManagerSettings);
                    WriteToLogIf(traceEnabled,
                                    string.Format(CultureInfo.CurrentCulture,
                                                    ServiceBusIsConnected,
                                                    namespaceUri.AbsoluteUri));

                    // The MessagingFactorySettings specifies the service bus messaging factory settings.
                    var messagingFactorySettings = new MessagingFactorySettings
                                                    {
                                                        TokenProvider = tokenProvider,
                                                        OperationTimeout =
                                                            TimeSpan.FromMinutes(5)
                                                    };
                    // In the first release of the service bus, the only available transport protocol is sb 
                    if (scheme == DefaultScheme)
                    {
                        messagingFactorySettings.NetMessagingTransportSettings =
                            new NetMessagingTransportSettings();
                    }

                    // As the name suggests, the MessagingFactory class is a Factory class that allows to create
                    // instances of the QueueClient, TopicClient and SubscriptionClient classes.
                    MessagingFactory = MessagingFactory.Create(namespaceUri,
                                                            messagingFactorySettings);
                    WriteToLogIf(traceEnabled, MessageFactorySuccessfullyCreated);
                    return true;
                }
                throw new ApplicationException(string.Format(CultureInfo.CurrentCulture,
                                                            ServiceBusNamespaceDoesNotExist,
                                                            serviceBusNamespace));
            });
            return RetryHelper.RetryFunc(func, writeToLog);
        }
 /// <summary>
 /// Initializes a new instance of the ServiceBusNamespace class for an on-premises namespace.
 /// </summary>
 /// <param name="connectionString">The service bus namespace connection string.</param>
 /// <param name="endpoint">The endpoint of the service bus namespace.</param>
 /// <param name="stsEndpoint">The sts endpoint of the service bus namespace.</param>
 /// <param name="runtimePort">The runtime port.</param>
 /// <param name="managementPort">The management port.</param>
 /// <param name="windowsDomain">The Windows domain or machine name.</param>
 /// <param name="windowsUsername">The Windows user name.</param>
 /// <param name="windowsPassword">The Windows user password.</param>
 /// <param name="ns">The service bus namespace.</param>
 /// <param name="transportType">The transport type to use to access the namespace.</param>
 public ServiceBusNamespace(string connectionString,
                            string endpoint,
                            string stsEndpoint,
                            string runtimePort,
                            string managementPort,
                            string windowsDomain,
                            string windowsUsername,
                            string windowsPassword,
                            string ns,
                            TransportType transportType)
 {
     ConnectionStringType = ServiceBusNamespaceType.OnPremises;
     ConnectionString = connectionString;
     Uri = endpoint;
     var uri = new Uri(endpoint);
     if (string.IsNullOrWhiteSpace(endpoint))
     {
         Uri = ServiceBusEnvironment.CreateServiceUri(uri.Scheme, ns, null).ToString();
     }
     Namespace = ns;
     IssuerName = default(string);
     IssuerSecret = default(string);
     var settings = new MessagingFactorySettings();
     TransportType = settings.TransportType;
     StsEndpoint = stsEndpoint;
     RuntimePort = runtimePort;
     ManagementPort = managementPort;
     WindowsDomain = windowsDomain;
     WindowsUserName = windowsUsername;
     WindowsPassword = windowsPassword;
     TransportType = transportType;
 }
            public async Task Should_be_configured_and_working()
            {
                var settings = new TestAzureServiceBusAccountSettings();
                var provider = new SharedAccessKeyTokenProvider(settings);

                TokenProvider tokenProvider = provider.GetTokenProvider();

                Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", Configuration.ServiceNamespace,
                                                                        "MassTransit.AzureServiceBusTransport.Tests");
                var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

                CreateQueue(namespaceManager, serviceUri, "TestClient");


                CreateHostQueue(tokenProvider);

                var mfs = new MessagingFactorySettings
                {
                    TokenProvider         = tokenProvider,
                    OperationTimeout      = TimeSpan.FromSeconds(30),
                    TransportType         = TransportType.Amqp,
                    AmqpTransportSettings = new AmqpTransportSettings
                    {
                        BatchFlushInterval = TimeSpan.FromMilliseconds(50),
                    },
                };

                MessagingFactory factory =
                    MessagingFactory.Create(
                        ServiceBusEnvironment.CreateServiceUri("sb", Configuration.ServiceNamespace, Environment.MachineName), mfs);

                MessageReceiver receiver = await factory.CreateMessageReceiverAsync("Control");

                receiver.PrefetchCount = 100;

                var       done  = TaskUtil.GetTask <bool>();
                int       count = 0;
                const int limit = 1000;

                receiver.OnMessageAsync(async message =>
                {
                    await message.CompleteAsync();

                    int received = Interlocked.Increment(ref count);
                    if (received == limit)
                    {
                        done.TrySetResult(true);
                    }
                }, new OnMessageOptions
                {
                    AutoComplete       = false,
                    MaxConcurrentCalls = 100,
                    AutoRenewTimeout   = TimeSpan.FromSeconds(60),
                });

                MessageSender client = await factory.CreateMessageSenderAsync("Control");

                Stopwatch stopwatch = Stopwatch.StartNew();

                Task[] tasks = new Task[limit];
                for (int i = 0; i < limit; i++)
                {
                    tasks[i] = SendAMessage(client);
                }

                await done.Task;

                stopwatch.Stop();

                await Task.WhenAll(tasks);

                await receiver.CloseAsync();

                Console.WriteLine("Performance: {0:F2}/s", limit * 1000 / stopwatch.ElapsedMilliseconds);
            }
Пример #43
0
        Task<MessagingFactory> CreateMessagingFactory()
        {
            var mfs = new MessagingFactorySettings
            {
                TokenProvider = _settings.TokenProvider,
                OperationTimeout = _settings.OperationTimeout,
                TransportType = TransportType.Amqp,
                AmqpTransportSettings = new AmqpTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromMilliseconds(50)
                }
            };

            var builder = new UriBuilder(_settings.ServiceUri) {Path = ""};

            return MessagingFactory.CreateAsync(builder.Uri, mfs);
        }
Пример #44
0
        private ServiceBusNamespace GetServiceBusNamespace(string key, string connectionString)
        {

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIsNullOrEmpty, key));
                return null;
            }

            var toLower = connectionString.ToLower();
            var parameters = connectionString.Split(';').ToDictionary(s => s.Substring(0, s.IndexOf('=')).ToLower(), s => s.Substring(s.IndexOf('=') + 1));

            if (toLower.Contains(ConnectionStringEndpoint) &&
                toLower.Contains(ConnectionStringSharedAccessKeyName) &&
                toLower.Contains(ConnectionStringSharedAccessKey))
            {
                if (parameters.Count < 3)
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIsWrong, key));
                    return null;
                }
                var endpoint = parameters.ContainsKey(ConnectionStringEndpoint) ?
                               parameters[ConnectionStringEndpoint] :
                               null;

                if (string.IsNullOrWhiteSpace(endpoint))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceEndpointIsNullOrEmpty, key));
                    return null;
                }

                var stsEndpoint = parameters.ContainsKey(ConnectionStringStsEndpoint) ?
                                  parameters[ConnectionStringStsEndpoint] :
                                  null;

                Uri uri;
                try
                {
                    uri = new Uri(endpoint);
                }
                catch (Exception)
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceEndpointUriIsInvalid, key));
                    return null;
                }
                var ns = uri.Host.Split('.')[0];

                if (!parameters.ContainsKey(ConnectionStringSharedAccessKeyName) || string.IsNullOrWhiteSpace(parameters[ConnectionStringSharedAccessKeyName]))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceSharedAccessKeyNameIsInvalid, key));
                }
                var sharedAccessKeyName = parameters[ConnectionStringSharedAccessKeyName];

                if (!parameters.ContainsKey(ConnectionStringSharedAccessKey) || string.IsNullOrWhiteSpace(parameters[ConnectionStringSharedAccessKey]))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceSharedAccessKeyIsInvalid, key));
                }
                var sharedAccessKey = parameters[ConnectionStringSharedAccessKey];


                var settings = new MessagingFactorySettings();
                var transportType = settings.TransportType;

                if (parameters.ContainsKey(ConnectionStringTransportType))
                {
                    Enum.TryParse(parameters[ConnectionStringTransportType], true, out transportType);
                }

                return new ServiceBusNamespace(ServiceBusNamespaceType.Cloud, connectionString, endpoint, ns, null, sharedAccessKeyName, sharedAccessKey, stsEndpoint, transportType, true);
            }

            if (toLower.Contains(ConnectionStringRuntimePort) ||
                toLower.Contains(ConnectionStringManagementPort) ||
                toLower.Contains(ConnectionStringWindowsUsername) ||
                toLower.Contains(ConnectionStringWindowsDomain) ||
                toLower.Contains(ConnectionStringWindowsPassword))
            {
                if (!toLower.Contains(ConnectionStringEndpoint) ||
                    !toLower.Contains(ConnectionStringStsEndpoint) ||
                    !toLower.Contains(ConnectionStringRuntimePort) ||
                    !toLower.Contains(ConnectionStringManagementPort))
                {
                    return null;
                }

                var endpoint = parameters.ContainsKey(ConnectionStringEndpoint) ?
                               parameters[ConnectionStringEndpoint] :
                               null;

                if (string.IsNullOrWhiteSpace(endpoint))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceEndpointIsNullOrEmpty, key));
                    return null;
                }

                Uri uri;
                try
                {
                    uri = new Uri(endpoint);
                }
                catch (Exception)
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceEndpointUriIsInvalid, key));
                    return null;
                }
                var ns = uri.Host.Split('.')[0];

                var stsEndpoint = parameters.ContainsKey(ConnectionStringStsEndpoint) ?
                                  parameters[ConnectionStringStsEndpoint] :
                                  null;

                if (string.IsNullOrWhiteSpace(stsEndpoint))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceStsEndpointIsNullOrEmpty, key));
                    return null;
                }

                var runtimePort = parameters.ContainsKey(ConnectionStringRuntimePort) ?
                                  parameters[ConnectionStringRuntimePort] :
                                  null;

                if (string.IsNullOrWhiteSpace(runtimePort))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceRuntimePortIsNullOrEmpty, key));
                    return null;
                }

                var managementPort = parameters.ContainsKey(ConnectionStringManagementPort) ?
                                     parameters[ConnectionStringManagementPort] :
                                     null;

                if (string.IsNullOrWhiteSpace(managementPort))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceManagementPortIsNullOrEmpty, key));
                    return null;
                }

                var windowsDomain = parameters.ContainsKey(ConnectionStringWindowsDomain) ?
                                    parameters[ConnectionStringWindowsDomain] :
                                    null;

                var windowsUsername = parameters.ContainsKey(ConnectionStringWindowsUsername) ?
                                      parameters[ConnectionStringWindowsUsername] :
                                      null;

                var windowsPassword = parameters.ContainsKey(ConnectionStringWindowsPassword) ?
                                      parameters[ConnectionStringWindowsPassword] :
                                      null;
                var settings = new MessagingFactorySettings();
                var transportType = settings.TransportType;
                if (parameters.ContainsKey(ConnectionStringTransportType))
                {
                    Enum.TryParse(parameters[ConnectionStringTransportType], true, out transportType);
                }
                return new ServiceBusNamespace(connectionString, endpoint, stsEndpoint, runtimePort, managementPort, windowsDomain, windowsUsername, windowsPassword, ns, transportType);
            }

            if (toLower.Contains(ConnectionStringEndpoint) &&
                toLower.Contains(ConnectionStringSharedSecretIssuer) &&
                toLower.Contains(ConnectionStringSharedSecretValue))
            {
                if (parameters.Count < 3)
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIsWrong, key));
                    return null;
                }

                var endpoint = parameters.ContainsKey(ConnectionStringEndpoint) ?
                               parameters[ConnectionStringEndpoint] :
                               null;

                if (string.IsNullOrWhiteSpace(endpoint))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceEndpointIsNullOrEmpty, key));
                    return null;
                }

                var stsEndpoint = parameters.ContainsKey(ConnectionStringStsEndpoint) ?
                                  parameters[ConnectionStringStsEndpoint] :
                                  null;

                Uri uri;
                try
                {
                    uri = new Uri(endpoint);
                }
                catch (Exception)
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceEndpointUriIsInvalid, key));
                    return null;
                }
                var ns = uri.Host.Split('.')[0];
                var issuerName = parameters.ContainsKey(ConnectionStringSharedSecretIssuer) ?
                                     parameters[ConnectionStringSharedSecretIssuer] :
                                     ConnectionStringOwner;

                if (!parameters.ContainsKey(ConnectionStringSharedSecretValue) ||
                    string.IsNullOrWhiteSpace(parameters[ConnectionStringSharedSecretValue]))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIssuerSecretIsNullOrEmpty, key));
                    return null;

                }
                var issuerSecret = parameters[ConnectionStringSharedSecretValue];

                var settings = new MessagingFactorySettings();
                var transportType = settings.TransportType;
                if (parameters.ContainsKey(ConnectionStringTransportType))
                {
                    Enum.TryParse(parameters[ConnectionStringTransportType], true, out transportType);
                }

                return new ServiceBusNamespace(ServiceBusNamespaceType.Cloud, connectionString, endpoint, ns, null, issuerName, issuerSecret, stsEndpoint, transportType);
            }
            else
            {
                if (parameters.Count < 4)
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIsWrong, key));
                    return null;
                }

                var uriString = parameters.ContainsKey(ConnectionStringUri) ?
                                    parameters[ConnectionStringUri] :
                                    null;

                if (string.IsNullOrWhiteSpace(uriString) && !parameters.ContainsKey(ConnectionStringNameSpace))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceNamespaceAndUriAreNullOrEmpty, key));
                    return null;
                }

                var ns = parameters[ConnectionStringNameSpace];

                var servicePath = parameters.ContainsKey(ConnectionStringServicePath) ?
                                      parameters[ConnectionStringServicePath] :
                                      null;

                if (!parameters.ContainsKey(ConnectionStringIssuerName))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIssuerNameIsNullOrEmpty, key));
                    return null;
                }
                var issuerName = parameters.ContainsKey(ConnectionStringIssuerName) ?
                                     parameters[ConnectionStringIssuerName] :
                                     ConnectionStringOwner;

                if (!parameters.ContainsKey(ConnectionStringIssuerSecret) ||
                    string.IsNullOrWhiteSpace(parameters[ConnectionStringIssuerSecret]))
                {
                    WriteToLog(string.Format(CultureInfo.CurrentCulture, ServiceBusNamespaceIssuerSecretIsNullOrEmpty, key));
                    return null;

                }
                var issuerSecret = parameters[ConnectionStringIssuerSecret];

                var settings = new MessagingFactorySettings();
                var transportType = settings.TransportType;
                if (parameters.ContainsKey(ConnectionStringTransportType))
                {
                    Enum.TryParse(parameters[ConnectionStringTransportType], true, out transportType);
                }

                return new ServiceBusNamespace(ServiceBusNamespaceType.Custom, connectionString, uriString, ns, servicePath, issuerName, issuerSecret, null, transportType);
            }
        }
Пример #45
0
        Task<MessagingFactory> CreateNetMessagingFactory()
        {
            if (_settings.TransportType == TransportType.NetMessaging)
                return _messagingFactory.Value;

            var mfs = new MessagingFactorySettings
            {
                TokenProvider = _settings.TokenProvider,
                OperationTimeout = _settings.OperationTimeout,
                TransportType = TransportType.NetMessaging,
                NetMessagingTransportSettings = new NetMessagingTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromMilliseconds(50)
                }
            };

            return CreateFactory(mfs);
        }
            public async Task Should_be_configured_and_working()
            {
                var settings = new TestAzureServiceBusAccountSettings();
                var provider = new SharedAccessKeyTokenProvider(settings);

                TokenProvider tokenProvider = provider.GetTokenProvider();

                Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", "masstransit-build",
                    "MassTransit.AzureServiceBusTransport.Tests");
                var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);
                CreateQueue(namespaceManager, serviceUri, "TestClient");


                CreateHostQueue(tokenProvider);

                var mfs = new MessagingFactorySettings
                {
                    TokenProvider = tokenProvider,
                    OperationTimeout = TimeSpan.FromSeconds(30),
                    TransportType = TransportType.Amqp,
                    AmqpTransportSettings = new AmqpTransportSettings
                    {
                        BatchFlushInterval = TimeSpan.FromMilliseconds(50),
                    },
                };

                MessagingFactory factory =
                    MessagingFactory.Create(
                        ServiceBusEnvironment.CreateServiceUri("sb", "masstransit-build", Environment.MachineName), mfs);

                MessageReceiver receiver = await factory.CreateMessageReceiverAsync("Control");
                receiver.PrefetchCount = 100;

                var done = new TaskCompletionSource<bool>();
                int count = 0;
                const int limit = 1000;
                receiver.OnMessageAsync(async message =>
                {
                    var receiveContext = new ServiceBusReceiveContext(new Uri("sb://localhost/queue"), message, new ReceiveObservable());

                    await message.CompleteAsync();

                    int received = Interlocked.Increment(ref count);
                    if (received == limit)
                        done.TrySetResult(true);
                }, new OnMessageOptions
                {
                    AutoComplete = false,
                    MaxConcurrentCalls = 100,
                    AutoRenewTimeout = TimeSpan.FromSeconds(60),
                });

                MessageSender client = await factory.CreateMessageSenderAsync("Control");

                Stopwatch stopwatch = Stopwatch.StartNew();
                Task[] tasks = new Task[limit];
                for (int i = 0; i < limit; i++)
                {
                    tasks[i] = SendAMessage(client);
                }

                await done.Task;
                stopwatch.Stop();

                await Task.WhenAll(tasks);

                await receiver.CloseAsync();

                Console.WriteLine("Performance: {0:F2}/s", limit * 1000 / stopwatch.ElapsedMilliseconds);
            }
Пример #47
0
            public async Task Should_be_configured_and_working()
            {
                var settings = new TestAzureServiceBusAccountSettings();
                var provider = new SharedAccessKeyTokenProvider(settings);

                var tokenProvider = provider.GetTokenProvider();

                var namespaceSettings = new NamespaceManagerSettings
                {
                    TokenProvider = tokenProvider
                };

                var serviceUri = AzureServiceBusEndpointUriCreator.Create(
                    Configuration.ServiceNamespace,
                    "MassTransit.Azure.ServiceBus.Core.Tests"
                    );

                var namespaceManager = new NamespaceManager(serviceUri, namespaceSettings);

                await CreateQueue(namespaceManager, serviceUri, "TestClient");

                await CreateHostQueue(tokenProvider);

                var mfs = new MessagingFactorySettings
                {
                    TokenProvider    = tokenProvider,
                    OperationTimeout = TimeSpan.FromSeconds(30),
                    TransportType    = TransportType.Amqp
                };

                var factory = await MessagingFactory.CreateAsync(serviceUri, mfs);

                var receiver = factory.CreateQueueClient("Control");

                receiver.PrefetchCount = 100;

                var       done  = new TaskCompletionSource <bool>();
                var       count = 0;
                const int limit = 1000;

                receiver.RegisterMessageHandler(async(message, cancellationToken) =>
                {
                    await receiver.CompleteAsync(message.SystemProperties.LockToken);

                    var received = Interlocked.Increment(ref count);
                    if (received == limit)
                    {
                        done.TrySetResult(true);
                    }
                }, new MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    AutoComplete         = false,
                    MaxConcurrentCalls   = 100,
                    MaxAutoRenewDuration = TimeSpan.FromSeconds(60)
                });

                var client = factory.CreateMessageSender("Control");

                var stopwatch = Stopwatch.StartNew();
                var tasks     = new Task[limit];

                for (var i = 0; i < limit; i++)
                {
                    tasks[i] = SendAMessage(client);
                }

                await done.Task;

                stopwatch.Stop();

                await Task.WhenAll(tasks);

                await receiver.CloseAsync();

                Console.WriteLine("Performance: {0:F2}/s", limit * 1000 / stopwatch.ElapsedMilliseconds);
            }
Пример #48
0
        private QueueClient CreateQueueClientIfNotExist(string p_healthMonitorCommandQueueName, bool p_requiresSession, string p_serviceBusUri, TokenProvider p_tokenProvider, NamespaceManager p_namespaceManager)
        {
            if (!p_namespaceManager.QueueExists(p_healthMonitorCommandQueueName))
            {
                QueueDescription qDesc = new QueueDescription(p_healthMonitorCommandQueueName);
                qDesc.MaxSizeInMegabytes = 5120;
                qDesc.DefaultMessageTimeToLive = TimeSpan.FromDays(14); // on Free tier pricing, max 14 days are allowed
                qDesc.EnableDeadLetteringOnMessageExpiration = false;
                qDesc.LockDuration = TimeSpan.FromMinutes(5);  // default is 30seconds, I have changed it to 5minutes, which is the maximum
                qDesc.RequiresDuplicateDetection = false;
                // 'RequiresSession' cannot be set when creating a Queue IF the namespace 'sqhealthmonitorservicebusqueue-ns' is using free 'Basic' tier.
                qDesc.RequiresSession = p_requiresSession;      // if there is only one consumer of the command queue, no sessionID is required, for the commandResult there are more consumers
                qDesc.EnablePartitioning = true;
                // until this line is the properties that can be set in Azure portal

                qDesc.EnableBatchedOperations = false;      // for low latency, quick response, don't wait miliseconds to batch messages, but send them instantly
                var qDescCreated = p_namespaceManager.CreateQueue(qDesc);
            }
            MessagingFactorySettings mfs = new MessagingFactorySettings();
            mfs.TokenProvider = p_tokenProvider;
            //mfs.TransportType = TransportType.Amqp;       // 400msec latency
            mfs.TransportType = Microsoft.ServiceBus.Messaging.TransportType.NetMessaging;     // 50msec latency
            mfs.NetMessagingTransportSettings.BatchFlushInterval = TimeSpan.Zero;  // instead of 20msec, // latency is 37msec was the minimum I measured (instead of 43msec)
            MessagingFactory factory = MessagingFactory.Create(p_serviceBusUri, mfs);
            var queueClient = factory.CreateQueueClient(p_healthMonitorCommandQueueName, ReceiveMode.PeekLock);
            queueClient.PrefetchCount = 0;  // it is the default too, and it was 0 in the fast and in the slow cases too
            return queueClient;
        }
Пример #49
0
        Task<MessagingFactory> CreateNetMessagingFactory()
        {
            if (_settings.TransportType == TransportType.NetMessaging)
                return _messagingFactory.Value;

            var mfs = new MessagingFactorySettings
            {
                TokenProvider = _settings.TokenProvider,
                OperationTimeout = _settings.OperationTimeout,
                TransportType = TransportType.NetMessaging,
                NetMessagingTransportSettings = _settings.NetMessagingTransportSettings
            };

            return CreateFactory(mfs);
        }
Пример #50
0
        Task<MessagingFactory> CreateMessagingFactory()
        {
            var mfs = new MessagingFactorySettings
            {
                TokenProvider = _settings.TokenProvider,
                OperationTimeout = _settings.OperationTimeout,
                TransportType = _settings.TransportType
            };

            switch (_settings.TransportType)
            {
                case TransportType.NetMessaging:
                    mfs.NetMessagingTransportSettings = _settings.NetMessagingTransportSettings;
                    break;
                case TransportType.Amqp:
                    mfs.AmqpTransportSettings = _settings.AmqpTransportSettings;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return CreateFactory(mfs);
        }
        public void Connect()
        {
            Disconnect();

            _log.DebugFormat("Connecting to '{0}' at {1}", _address, _serviceUri);

            _manager = new NamespaceManager(_serviceUri, _tokenProvider);

            var mfs = new MessagingFactorySettings
            {
                TokenProvider = _tokenProvider,
                OperationTimeout = 3.Seconds(),
                TransportType = TransportType.Amqp,
                AmqpTransportSettings = new AmqpTransportSettings
                {
                    BatchFlushInterval = 50.Milliseconds()
                },
            };

            _factory = MessagingFactory.Create(_serviceUri, mfs);
        }
Пример #52
0
        public ConnectForm(ServiceBusHelper serviceBusHelper)
        {
            InitializeComponent();
            this.serviceBusHelper = serviceBusHelper;
            cboServiceBusNamespace.Items.Add(SelectServiceBusNamespace);
            cboServiceBusNamespace.Items.Add(EnterConnectionString);
            if (serviceBusHelper.ServiceBusNamespaces != null)
            {
                // ReSharper disable CoVariantArrayConversion
                cboServiceBusNamespace.Items.AddRange(serviceBusHelper.ServiceBusNamespaces.Keys.OrderBy(s=>s).ToArray());
                // ReSharper restore CoVariantArrayConversion
            }

            ConnectivityMode = ServiceBusHelper.ConnectivityMode;
            cboConnectivityMode.DataSource = Enum.GetValues(typeof(ConnectivityMode));
            cboConnectivityMode.SelectedItem = ConnectivityMode;

            cboTransportType.DataSource = Enum.GetValues(typeof(TransportType));
            var settings = new MessagingFactorySettings();
            cboTransportType.SelectedItem = settings.TransportType;

            cboServiceBusNamespace.SelectedIndex = connectionStringIndex > 0 ? connectionStringIndex : 0;
            if (cboServiceBusNamespace.Text == EnterConnectionString)
            {
                txtUri.Text = connectionString;
            }

            txtQueueFilterExpression.Text = FilterExpressionHelper.QueueFilterExpression;
            txtTopicFilterExpression.Text = FilterExpressionHelper.TopicFilterExpression;
            txtSubscriptionFilterExpression.Text = FilterExpressionHelper.SubscriptionFilterExpression;
            btnOk.Enabled = cboServiceBusNamespace.SelectedIndex > 1 || (cboServiceBusNamespace.Text == EnterConnectionString && !string.IsNullOrWhiteSpace(connectionString));

            foreach (var item in MainForm.SingletonMainForm.Entities)
            {
                cboSelectedEntities.Items.Add(item);
            }

            foreach (var item in MainForm.SingletonMainForm.SelectedEntities)
            {
                cboSelectedEntities.CheckBoxItems[item].Checked = true;
            }
        }
Пример #53
0
        // https://azure.microsoft.com/sv-se/documentation/articles/websites-dotnet-webjobs-sdk-storage-queues-how-to/
        // This function will get triggered/executed when a new message is written on an Azure Queue called sqhealthmonitorqueue.
        // By default, the SDK gets a batch of 16 queue messages at a time and executes the function that processes them in parallel.
        public static void ProcessAzureQueueMessage([QueueTrigger("sqhealthmonitorqueue")] string p_message, TextWriter azureBlogLog, CancellationToken token)
        {
            // 1. Get StorageQueue message
            azureBlogLog.WriteLine(p_message); // logs the message to Blob storage log
            if (token.IsCancellationRequested)  // for Long processes, use CancellationToken
            {
                azureBlogLog.WriteLine("Function was cancelled at iteration");
                return;
            }
            // Process the storageQueue message... maybe a long time
            Utils.Logger.Debug("ReceivedStorageQueueMessage: " + p_message);

            // 2. Send Service BusQueue message
            if (gBusQueueClient == null)
            {
                string azureServiceBusKN = Encoding.UTF8.GetString(Convert.FromBase64String(ConfigurationManager.ConnectionStrings["HQHealthMonitor.AzureServiceBusKN"].ConnectionString));
                string azureServiceBusK = Encoding.UTF8.GetString(Convert.FromBase64String(ConfigurationManager.ConnectionStrings["HQHealthMonitor.AzureServiceBusK"].ConnectionString));
                Utils.Logger.Debug("AzureServiceBusConnectionName and key: " + azureServiceBusKN + ":" + azureServiceBusK);
                // this fast MessagingFactory implementation is in Microsoft.ServiceBus.Messaging.Configuration.KeyValueConfigurationManager

                // MessagingFactory.CreateFromConnectionString(connectionString, true) true = useCache; Cache used for creating the MessagingFactor, so next time you don't have to.
                // MessagingFactory CreationCache is not used, MessagingFactory is deleted and recreated every time this Function is called.
                // So, my SLOW version was slow, because MessagingFactory creation is very slow = 200-500msec. And I created it every time. First time.
                // However, when the created Factory was in the cache, we don't have to create it before every Send operation.
                // solution: create once and store it in memory
                TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(azureServiceBusKN, azureServiceBusK); // SAS: latency is 250msec or more
                MessagingFactorySettings mfs = new MessagingFactorySettings();
                mfs.TokenProvider = tokenProvider;
                //mfs.TransportType = TransportType.Amqp;       // 600msec latency
                mfs.TransportType = TransportType.NetMessaging;     // 230msec latency
                mfs.NetMessagingTransportSettings.BatchFlushInterval = TimeSpan.Zero;  // instead of 20msec, // latency is 37msec was the minimum I measured (instead of 43msec)
                //mfs.NetMessagingTransportSettings.BatchFlushInterval = TimeSpan.FromMilliseconds(20);  // instead of 20msec
                MessagingFactory factory = MessagingFactory.Create("sb://sqhealthmonitorservicebusqueue-ns.servicebus.windows.net/", mfs);
                gBusQueueClient = factory.CreateQueueClient("SQHealthMonitorServiceBusQueue", ReceiveMode.PeekLock);
                gBusQueueClient.PrefetchCount = 0;  // it is the default too, and it was 0 in the fast and in the slow cases too

                //gBusQueueClient = QueueClient.CreateFromConnectionString(azureServiceBusConnectionString, "SQHealthMonitorServiceBusQueue");  // latency is 43msec was the minimum I measured

                // Callback to handle received messages.
                // 3. Receive BusQueue message
                OnMessageOptions options = new OnMessageOptions();   // Configure the callback options.
                options.AutoComplete = false;
                options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
                gBusQueueClient.OnMessage((receivedMessage) =>
                {
                    try
                    {
                        //Service Bus Queue performance: from StorageQueue vs ServiceBusQueue vs. EventHub.txt
                        //> first message arrives after 650msec // +GetBody() takes 150msec
                        //> next messages arrives in 39, 45, 60 msec.Great ! because we don't poll it every 5 seconds. Great subscriber model.
                        long highResReceivedTimeTick = System.Diagnostics.Stopwatch.GetTimestamp();   // this gives back UTC timestamp. Checked.

                        DateTime receivedTime = DateTime.UtcNow;
                        Utils.Logger.Debug("BusQueue message was received.");  // this takes 100msec
                        string messageBody = receivedMessage.GetBody<string>();

                        //Utils.Logger.Debug("BusQueue message.GetBody(): " + messageBody + "/" + receivedMessage.MessageId + "/" + receivedMessage.Properties["TestProperty"]);
                        Utils.Logger.Debug("BusQueue message.GetBody(): " + messageBody); // this takes 100msec

                        int separatorPos = messageBody.IndexOf(',');
                        if (separatorPos != -1)
                        {
                            string sentDateTimeStr = messageBody.Substring(0, separatorPos);
                            DateTime sentTime;
                            if (DateTime.TryParse(sentDateTimeStr, out sentTime))
                            {
                                int separatorPosTick = messageBody.IndexOf(',', separatorPos + 1);
                                if (separatorPosTick != -1)
                                {
                                    string highResSentDateTimeStr = messageBody.Substring(separatorPos + 1, separatorPosTick - separatorPos - 1);
                                    long highResSentTimeTick;
                                    if (Int64.TryParse(highResSentDateTimeStr, out highResSentTimeTick))
                                    {
                                        long elapsedTicks = highResReceivedTimeTick - highResSentTimeTick;
                                        long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
                                        long totalNanoSeconds = elapsedTicks * nanosecPerTick;
                                        long totalMiliseconds = totalNanoSeconds / 1000L / 1000L;
                                        Utils.Logger.Debug("BusQueue message was received in " + (receivedTime - sentTime).ToString() + " in highResTick as msec:" + totalMiliseconds);
                                    }
                                }
                            }
                        }
                        receivedMessage.Complete(); // Remove message from queue. Only send Complete(), when we are confident that we could send at least 1 email/SMS/phonecall to the user. We have 5 minutes to do that, because BusQueue LockDuration is 5 minutes maximum. After that message goes back to the queue (or Dead?)
                    }
                    catch (Exception ex)
                    {
                        Utils.Logger.Error(ex, "BusQueue message was received, but crash occured: " + ex.Message);
                        receivedMessage.Abandon();  // Indicates a problem, unlock message in queue.
                    }
                }, options);

            }

            // Performance Measurement:
            // Note: Usually the system clock (which is where DateTime.Now gets its data from) has a resolution of around 10-15ms.
            // The problem with DateTime when dealing with milliseconds isn't due to the DateTime class at all, but rather, has to do with CPU ticks and thread slices. Essentially, when an operation is paused by the scheduler to allow other threads to execute, it must wait at a minimum of 1 time slice before resuming which is around 15ms on modern Windows OSes.
            //Someone suggested to look at the Stopwatch class. Although the Stopwatch class is very accurate it does not tell me the current time, something i need in order to save the state of my program.
            // if you print DateTime.Now in a loop you will see that it increments in descrete jumps of approx. 15 ms.
            //The ElapsedTicks value from Stopwatch is not normally the same as the DateTime.Ticks value.
            //Stopwatch ticks are far more accurate, when the IsHighResolution property is true.Otherwise, they are equivalent.
            // Intel i7 values: IsHighResolution    true    ,  Frequency   3914060
            //Stopwatch stopWatch = new Stopwatch();
            long stopWatchTickCount = System.Diagnostics.Stopwatch.GetTimestamp();   // this gives back UTC timestamp. Checked.
            //DateTime highResDateTimeUtcNow = new DateTime(tickCount); // it doesn't work. This date is: year 0, month 0, day 0, and a couple of seconds.

            string busQueueMessageToSend = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture) + "," + stopWatchTickCount + ",Test Message to BusQueue=" + p_message;
            BrokeredMessage busMessage = new BrokeredMessage(busQueueMessageToSend);
            // Set some addtional custom app-specific properties.
            busMessage.Properties["TestProperty"] = "TestValue";
            busMessage.Properties["Message number"] = 5;
            gBusQueueClient.Send(busMessage);    // Send message to the queue.
            //Utils.Logger.Debug("BusQueue message was sent: with busQueueClient.Send(busMessage):" + busQueueMessageToSend);    // this takes 100msec
        }