예제 #1
0
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (ValidateUserInput())
            {
                ConnectionStringProperties objConnectionString = new ConnectionStringProperties();

                objConnectionString.DataSource     = txtServerName.Text.Trim();
                objConnectionString.InitialCatalog = cmbSelectDatabase.SelectedText;
                objConnectionString.UserId         = txtUserName.Text.Trim();
                objConnectionString.Password       = txtPassword.Text.Trim();

                var connectionString = _connectionStringService.BuildConnectionString(objConnectionString, true);

                if (_dbConnectService.TestConnection(connectionString))
                {
                    Global.ConnectionString = connectionString;

                    var lstDatabases = _dbConnectService.GetDatabases().ToList();

                    if (lstDatabases.Count > 0)
                    {
                        cmbSelectDatabase.DataSource    = lstDatabases;
                        cmbSelectDatabase.DisplayMember = "DbName";
                        cmbSelectDatabase.ValueMember   = "DbId";
                    }
                }
            }
        }
예제 #2
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventProcessorManager"/> class.
        /// </summary>
        ///
        /// <param name="consumerGroup">The name of the consumer group the event processors are associated with.  Events are read in the context of this group.</param>
        /// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace.</param>
        /// <param name="partitionManager">Interacts with the storage system with responsibility for creation of checkpoints and for ownership claim.</param>
        /// <param name="clientOptions">The set of options to use for the event processors.</param>
        /// <param name="onInitialize">A callback action to be called on <see cref="EventProcessorClient.PartitionInitializingAsync" />.</param>
        /// <param name="onStop">A callback action to be called on <see cref="EventProcessorClient.PartitionClosingAsync" />.</param>
        /// <param name="onProcessEvent">A callback action to be called on <see cref="EventProcessorClient.ProcessEventAsync" />.</param>
        /// <param name="onProcessError">A callback action to be called on <see cref="EventProcessorClient.ProcessErrorAsync" />.</param>
        ///
        public EventProcessorManager(string consumerGroup,
                                     string connectionString,
                                     PartitionManager partitionManager                    = null,
                                     EventProcessorClientOptions clientOptions            = null,
                                     Action <PartitionInitializingEventArgs> onInitialize = null,
                                     Action <PartitionClosingEventArgs> onStop            = null,
                                     Action <ProcessEventArgs> onProcessEvent             = null,
                                     Action <ProcessErrorEventArgs> onProcessError        = null)
        {
            ConnectionStringProperties connectionStringProperties = ConnectionStringParser.Parse(connectionString);

            FullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;
            EventHubName            = connectionStringProperties.EventHubName;
            ConsumerGroup           = consumerGroup;
            ConnectionFactory       = () => new EventHubConnection(connectionString);
            InnerPartitionManager   = partitionManager ?? new MockCheckPointStorage();

            // In case it has not been specified, set the maximum wait time to 2 seconds because the default
            // value (1 minute) would take too much time.

            ClientOptions = clientOptions?.Clone() ?? new EventProcessorClientOptions();

            if (ClientOptions.MaximumWaitTime == null)
            {
                ClientOptions.MaximumWaitTime = TimeSpan.FromSeconds(2);
            }

            OnInitialize   = onInitialize;
            OnStop         = onStop;
            OnProcessEvent = onProcessEvent;
            OnProcessError = onProcessError;

            EventProcessors = new List <EventProcessorClient>();
        }
        public async Task ClientCanConnectToEventHubsUsingArguments()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var clientOptions    = new EventHubClientOptions();
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                ConnectionStringProperties connectionProperties = ConnectionStringParser.Parse(connectionString);

                var credential = new SharedAccessSignatureCredential
                                 (
                    new SharedAccessSignature
                    (
                        $"{ clientOptions.TransportType.GetUriScheme() }://{ connectionProperties.Endpoint.Host }/{ connectionProperties.EventHubName }".ToLowerInvariant(),
                        connectionProperties.SharedAccessKeyName,
                        connectionProperties.SharedAccessKey,
                        TimeSpan.FromHours(4)
                    )
                                 );

                await using (var client = new EventHubClient(connectionProperties.Endpoint.Host, connectionProperties.EventHubName, credential))
                {
                    Assert.That(() => client.GetPropertiesAsync(), Throws.Nothing);
                }
            }
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the shared key properties are contained in this connection string, but not the Event Hub name.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Event Hub itself, it will contain the name of the desired Event Hub,
        ///   and can be used directly without passing the <paramref name="eventHubName" />.  The name of the Event Hub should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        public EventHubConnection(string connectionString,
                                  string eventHubName,
                                  EventHubConnectionOptions connectionOptions)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));

            connectionOptions = connectionOptions?.Clone() ?? new EventHubConnectionOptions();
            ValidateConnectionOptions(connectionOptions);

            ConnectionStringProperties connectionStringProperties = ConnectionStringParser.Parse(connectionString);

            ValidateConnectionProperties(connectionStringProperties, eventHubName, nameof(connectionString));

            var fullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;

            if (string.IsNullOrEmpty(eventHubName))
            {
                eventHubName = connectionStringProperties.EventHubName;
            }

            var sharedAccessSignature = new SharedAccessSignature
                                        (
                BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName),
                connectionStringProperties.SharedAccessKeyName,
                connectionStringProperties.SharedAccessKey
                                        );

            var sharedCredentials = new SharedAccessSignatureCredential(sharedAccessSignature);
            var tokenCredentials  = new EventHubTokenCredential(sharedCredentials, BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            EventHubName            = eventHubName;
            Options     = connectionOptions;
            InnerClient = CreateTransportClient(fullyQualifiedNamespace, eventHubName, tokenCredentials, connectionOptions);
        }
        /// <summary>
        ///   Performs the actions needed to validate the set of properties for connecting to the
        ///   Event Hubs service, as passed to this client during creation.
        /// </summary>
        ///
        /// <param name="properties">The set of properties parsed from the connection string associated this client.</param>
        /// <param name="eventHubName">The name of the Event Hub passed independent of the connection string, allowing easier use of a namespace-level connection string.</param>
        /// <param name="connectionStringArgumentName">The name of the argument associated with the connection string; to be used when raising <see cref="ArgumentException" /> variants.</param>
        ///
        /// <remarks>
        ///   In the case that the properties violate an invariant or otherwise represent a combination that
        ///   is not permissible, an appropriate exception will be thrown.
        /// </remarks>
        ///
        private static void ValidateConnectionProperties(ConnectionStringProperties properties,
                                                         string eventHubName,
                                                         string connectionStringArgumentName)
        {
            // The Event Hub name may only be specified in one of the possible forms, either as part of the
            // connection string or as a stand-alone parameter, but not both.  If specified in both to the same
            // value, then do not consider this a failure.

            if ((!string.IsNullOrEmpty(eventHubName)) &&
                (!string.IsNullOrEmpty(properties.EventHubName)) &&
                (!string.Equals(eventHubName, properties.EventHubName, StringComparison.InvariantCultureIgnoreCase)))
            {
                throw new ArgumentException(Resources.OnlyOneEventHubNameMayBeSpecified, connectionStringArgumentName);
            }

            // Ensure that each of the needed components are present for connecting.

            if ((string.IsNullOrEmpty(eventHubName)) && (string.IsNullOrEmpty(properties.EventHubName)) ||
                (string.IsNullOrEmpty(properties.Endpoint?.Host)) ||
                (string.IsNullOrEmpty(properties.SharedAccessKeyName)) ||
                (string.IsNullOrEmpty(properties.SharedAccessKey)))
            {
                throw new ArgumentException(Resources.MissingConnectionInformation, connectionStringArgumentName);
            }
        }
예제 #6
0
 /// <summary>
 ///   Performs the actions needed to validate the <see cref="ConnectionStringProperties" /> associated
 ///   with this client.
 /// </summary>
 ///
 /// <param name="properties">The set of properties parsed from the connection string associated this client.</param>
 /// <param name="connectionStringArgumentName">The name of the argument associated with the connection string; to be used when raising <see cref="ArgumentException" /> variants.</param>
 ///
 /// <remarks>
 ///   In the case that the prioperties violate an invariant or otherwise represent a combination that
 ///   is not permissible, an appropriate exception will be thrown.
 /// </remarks>
 ///
 internal virtual void ValidateConnectionStringProperties(ConnectionStringProperties properties,
                                                          string connectionStringArgumentName)
 {
     if ((String.IsNullOrEmpty(properties.Endpoint?.Host)) ||
         (String.IsNullOrEmpty(properties.EventHubPath)) ||
         (String.IsNullOrEmpty(properties.SharedAccessKeyName)) ||
         (String.IsNullOrEmpty(properties.SharedAccessKey)))
     {
         throw new ArgumentException(Resources.InvalidConnectionString, connectionStringArgumentName);
     }
 }
        public void ParseCorrectlyParsesANamespaceConnectionString()
        {
            var endpoint         = "test.endpoint.com";
            var sasKey           = "sasKey";
            var sasKeyName       = "sasName";
            var connectionString = $"Endpoint=sb://{ endpoint };SharedAccessKeyName={ sasKeyName };SharedAccessKey={ sasKey }";
            ConnectionStringProperties parsed = ConnectionStringParser.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.EventHubName, Is.Null, "The Event Hub path was not included in the connection string");
        }
        public void ParseDoesNotForceTokenOrdering(string connectionString,
                                                   string endpoint,
                                                   string eventHub,
                                                   string sasKeyName,
                                                   string sasKey)
        {
            ConnectionStringProperties parsed = ConnectionStringParser.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.EventHubName, Is.EqualTo(eventHub), "The Event Hub path should match.");
        }
예제 #9
0
        public async Task SmokeIdentityTestASample(IEventHubsIdentitySample sample)
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(2))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                ConnectionStringProperties properties = ConnectionStringParser.Parse(connectionString);

                Assert.That(async() => await sample.RunAsync(properties.Endpoint.Host,
                                                             scope.EventHubName,
                                                             TestEnvironment.EventHubsTenant,
                                                             TestEnvironment.EventHubsClient,
                                                             TestEnvironment.EventHubsSecret), Throws.Nothing);
            }
        }
        public async Task ClientCanConnectToEventHubsUsingSharedKeyCredential()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                ConnectionStringProperties properties = ConnectionStringParser.Parse(connectionString);
                var credential = new EventHubSharedKeyCredential(properties.SharedAccessKeyName, properties.SharedAccessKey);

                await using (var client = new EventHubClient(properties.Endpoint.Host, scope.EventHubName, credential))
                {
                    Assert.That(() => client.GetPropertiesAsync(), Throws.Nothing);
                }
            }
        }
예제 #11
0
        public void ParseIgnoresUnknownTokens()
        {
            var endpoint         = "test.endpoint.com";
            var eventHub         = "some-path";
            var sasKey           = "sasKey";
            var sasKeyName       = "sasName";
            var connectionString = $"Endpoint=sb://{ endpoint };SharedAccessKeyName={ sasKeyName };Unknown=INVALID;SharedAccessKey={ sasKey };EntityPath={ eventHub };Trailing=WHOAREYOU";
            ConnectionStringProperties parsed = ConnectionStringParser.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.EventHubName, Is.EqualTo(eventHub), "The Event Hub path should match.");
        }
예제 #12
0
        public void ParseCorrectlyParsesPartialConnectionStrings(string connectionString,
                                                                 string endpoint,
                                                                 string eventHub,
                                                                 string sasKeyName,
                                                                 string sasKey,
                                                                 string sharedAccessSignature)
        {
            ConnectionStringProperties parsed = ConnectionStringParser.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.SharedAccessSignature, Is.EqualTo(sharedAccessSignature), "The precomputed SAS should match.");
            Assert.That(parsed.EventHubName, Is.EqualTo(eventHub), "The Event Hub path should match.");
        }
예제 #13
0
        public void ParseCorrectlyParsesAnEventHubConnectionString()
        {
            var endpoint                      = "test.endpoint.com";
            var eventHub                      = "some-path";
            var sasKey                        = "sasKey";
            var sasKeyName                    = "sasName";
            var sharedAccessSignature         = "fakeSAS";
            var connectionString              = $"Endpoint=sb://{ endpoint };SharedAccessKeyName={ sasKeyName };SharedAccessKey={ sasKey };EntityPath={ eventHub };SharedAccessSignature={ sharedAccessSignature }";
            ConnectionStringProperties parsed = ConnectionStringParser.Parse(connectionString);

            Assert.That(parsed.Endpoint?.Host, Is.EqualTo(endpoint).Using((IComparer <string>)StringComparer.OrdinalIgnoreCase), "The endpoint host should match.");
            Assert.That(parsed.SharedAccessKeyName, Is.EqualTo(sasKeyName), "The SAS key name should match.");
            Assert.That(parsed.SharedAccessKey, Is.EqualTo(sasKey), "The SAS key value should match.");
            Assert.That(parsed.SharedAccessSignature, Is.EqualTo(sharedAccessSignature), "The precomputed SAS should match.");
            Assert.That(parsed.EventHubName, Is.EqualTo(eventHub), "The Event Hub path should match.");
        }
예제 #14
0
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            if (ValidateUserInput() && ValidateDatabaseSelection())
            {
                ConnectionStringProperties objConnectionString = new ConnectionStringProperties();

                objConnectionString.DataSource     = txtServerName.Text.Trim();
                objConnectionString.InitialCatalog = cmbSelectDatabase.SelectedText;
                objConnectionString.UserId         = txtUserName.Text.Trim();
                objConnectionString.Password       = txtPassword.Text.Trim();

                var connectionString = _connectionStringService.BuildConnectionString(objConnectionString, false);

                if (_dbConnectService.TestConnection(connectionString))
                {
                    Global.ConnectionString = connectionString;

                    MessageBox.Show("Test Connection Succeeded", "Poco Generator", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        public async Task ClientCanRetrievePartitionProperties(TransportType transportType)
        {
            var partitionCount = 4;

            await using (EventHubScope scope = await EventHubScope.CreateAsync(partitionCount))
            {
                var clientOptions    = new EventHubClientOptions();
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                ConnectionStringProperties connectionProperties = ConnectionStringParser.Parse(connectionString);

                var credential = new SharedAccessSignatureCredential
                                 (
                    new SharedAccessSignature
                    (
                        $"{ clientOptions.TransportType.GetUriScheme() }://{ connectionProperties.Endpoint.Host }/{ connectionProperties.EventHubName }".ToLowerInvariant(),
                        connectionProperties.SharedAccessKeyName,
                        connectionProperties.SharedAccessKey,
                        TimeSpan.FromHours(4)
                    )
                                 );

                await using (var client = new EventHubClient(connectionProperties.Endpoint.Host, connectionProperties.EventHubName, credential, new EventHubClientOptions {
                    TransportType = transportType
                }))
                {
                    var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(20));
                    EventHubProperties properties = await client.GetPropertiesAsync();

                    var partition = properties.PartitionIds.First();
                    PartitionProperties partitionProperties = await client.GetPartitionPropertiesAsync(partition, cancellation.Token);

                    Assert.That(partitionProperties, Is.Not.Null, "A set of partition properties should have been returned.");
                    Assert.That(partitionProperties.Id, Is.EqualTo(partition), "The partition identifier should match.");
                    Assert.That(partitionProperties.EventHubName, Is.EqualTo(connectionProperties.EventHubName).Using((IEqualityComparer <string>)StringComparer.InvariantCultureIgnoreCase), "The Event Hub path should match.");
                    Assert.That(partitionProperties.BeginningSequenceNumber, Is.Not.EqualTo(default(long)), "The beginning sequence number should have been populated.");
                    Assert.That(partitionProperties.LastEnqueuedSequenceNumber, Is.Not.EqualTo(default(long)), "The last sequence number should have been populated.");
                    Assert.That(partitionProperties.LastEnqueuedOffset, Is.Not.EqualTo(default(long)), "The last offset should have been populated.");
                }
            }
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Service Bus namespace.</param>
        /// <param name="options">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Service Bus entity itself, it will contain the name of the desired Service Bus entity,
        ///   and can be used directly without passing the  name="entityName" />.  The name of the Service Bus entity should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        internal ServiceBusConnection(
            string connectionString,
            ServiceBusClientOptions options)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));

            options = options?.Clone() ?? new ServiceBusClientOptions();

            ValidateConnectionOptions(options);
            ConnectionStringProperties connectionStringProperties = ConnectionStringParser.Parse(connectionString);

            if (string.IsNullOrEmpty(connectionStringProperties.Endpoint?.Host) ||
                string.IsNullOrEmpty(connectionStringProperties.SharedAccessKeyName) ||
                string.IsNullOrEmpty(connectionStringProperties.SharedAccessKey))
            {
                throw new ArgumentException(Resources.MissingConnectionInformation, nameof(connectionString));
            }

            FullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;
            TransportType           = options.TransportType;
            EntityPath   = connectionStringProperties.EntityPath;
            Options      = options;
            RetryOptions = options.RetryOptions;

            var sharedAccessSignature = new SharedAccessSignature
                                        (
                BuildAudienceResource(options.TransportType, FullyQualifiedNamespace, EntityPath),
                connectionStringProperties.SharedAccessKeyName,
                connectionStringProperties.SharedAccessKey
                                        );

            var sharedCredential = new SharedAccessSignatureCredential(sharedAccessSignature);
            var tokenCredential  = new ServiceBusTokenCredential(
                sharedCredential,
                BuildAudienceResource(TransportType, FullyQualifiedNamespace, EntityPath));

#pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for testing purposes.
            _innerClient = CreateTransportClient(tokenCredential, options);
#pragma warning restore CA2214 // Do not call overridable methods in constructors
        }
예제 #17
0
        /// <summary>
        ///   Performs the actions needed to validate the set of properties for connecting to the
        ///   Event Hubs service, as passed to this client during creation.
        /// </summary>
        ///
        /// <param name="properties">The set of properties parsed from the connection string associated this client.</param>
        /// <param name="eventHubPath">The path of the Event Hub passed independent of the connection string, allowing easier use of a namespace-level connection string.</param>
        /// <param name="connectionStringArgumentName">The name of the argument associated with the connection string; to be used when raising <see cref="ArgumentException" /> variants.</param>
        ///
        /// <remarks>
        ///   In the case that the prioperties violate an invariant or otherwise represent a combination that
        ///   is not permissible, an appropriate exception will be thrown.
        /// </remarks>
        ///
        private static void ValidateConnectionProperties(ConnectionStringProperties properties,
                                                         string eventHubPath,
                                                         string connectionStringArgumentName)
        {
            // The Event Hub path may only be specified in one of the possible forms, either as part of the
            // connection string or as a stand-alone parameter, but not both.

            if ((!String.IsNullOrEmpty(eventHubPath)) && (!String.IsNullOrEmpty(properties.EventHubPath)))
            {
                throw new ArgumentException(Resources.OnlyOneEventHubNameMayBeSpecified, connectionStringArgumentName);
            }

            // Ensure that each of the needed components are present for connecting.

            if ((String.IsNullOrEmpty(eventHubPath)) && (String.IsNullOrEmpty(properties.EventHubPath)) ||
                (String.IsNullOrEmpty(properties.Endpoint?.Host)) ||
                (String.IsNullOrEmpty(properties.SharedAccessKeyName)) ||
                (String.IsNullOrEmpty(properties.SharedAccessKey)))
            {
                throw new ArgumentException(Resources.MissingConnectionInformation, connectionStringArgumentName);
            }
        }
예제 #18
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the shared key properties are contained in this connection string, but not the Event Hub name.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Event Hub itself, it will contain the name of the desired Event Hub,
        ///   and can be used directly without passing the <paramref name="eventHubName" />.  The name of the Event Hub should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        public EventHubConnection(string connectionString,
                                  string eventHubName,
                                  EventHubConnectionOptions connectionOptions)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));

            connectionOptions = connectionOptions?.Clone() ?? new EventHubConnectionOptions();
            ValidateConnectionOptions(connectionOptions);

            ConnectionStringProperties connectionStringProperties = ConnectionStringParser.Parse(connectionString);

            ValidateConnectionProperties(connectionStringProperties, eventHubName, nameof(connectionString));

            var fullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;

            if (string.IsNullOrEmpty(eventHubName))
            {
                eventHubName = connectionStringProperties.EventHubName;
            }

            var sharedAccessSignature = new SharedAccessSignature
                                        (
                BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName),
                connectionStringProperties.SharedAccessKeyName,
                connectionStringProperties.SharedAccessKey
                                        );

            var sharedCredentials = new SharedAccessSignatureCredential(sharedAccessSignature);
            var tokenCredentials  = new EventHubTokenCredential(sharedCredentials, BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            EventHubName            = eventHubName;
            Options = connectionOptions;

#pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for testing purposes.
            InnerClient = CreateTransportClient(fullyQualifiedNamespace, eventHubName, tokenCredentials, connectionOptions);
#pragma warning restore CA2214 // Do not call overridable methods in constructors.
        }
예제 #19
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (ValidateUserInput() && ValidateDatabaseSelection())
            {
                ConnectionStringProperties objConnectionString = new ConnectionStringProperties();

                objConnectionString.DataSource     = txtServerName.Text.Trim();
                objConnectionString.InitialCatalog = ((DatabaseName)cmbSelectDatabase.SelectedItem).DbName;
                objConnectionString.UserId         = txtUserName.Text.Trim();
                objConnectionString.Password       = txtPassword.Text.Trim();

                var connectionString = _connectionStringService.BuildConnectionString(objConnectionString, true);

                if (_dbConnectService.TestConnection(connectionString))
                {
                    //Global.ConnectionString = connectionString;

                    LoadDataTypeMappings();

                    this.Close();
                }
            }
        }
        /// <summary>
        ///   Performs the actions needed to validate the set of connection string properties for connecting to the
        ///   Service Bus service.
        /// </summary>
        ///
        /// <param name="connectionStringProperties">The set of connection string properties to validate.</param>
        /// <param name="connectionStringArgumentName">The name of the argument associated with the connection string; to be used when raising <see cref="ArgumentException" /> variants.</param>
        ///
        /// <exception cref="ArgumentException">In the case that the properties violate an invariant or otherwise represent a combination that is not permissible, an appropriate exception will be thrown.</exception>
        ///
        private static void ValidateConnectionStringProperties(
            ConnectionStringProperties connectionStringProperties,
            string connectionStringArgumentName)
        {
            var hasSharedKey       = ((!string.IsNullOrEmpty(connectionStringProperties.SharedAccessKeyName)) && (!string.IsNullOrEmpty(connectionStringProperties.SharedAccessKey)));
            var hasSharedSignature = (!string.IsNullOrEmpty(connectionStringProperties.SharedAccessSignature));

            // Ensure that each of the needed components are present for connecting.

            if ((string.IsNullOrEmpty(connectionStringProperties.Endpoint?.Host)) ||
                ((!hasSharedKey) && (!hasSharedSignature)))
            {
                throw new ArgumentException(Resources.MissingConnectionInformation, connectionStringArgumentName);
            }

            // The connection string may contain a precomputed shared access signature OR a shared key name and value,
            // but not both.

            if (hasSharedKey && hasSharedSignature)
            {
                throw new ArgumentException(Resources.OnlyOneSharedAccessAuthorizationMayBeSpecified, connectionStringArgumentName);
            }
        }
        public string BuildConnectionString(ConnectionStringProperties connectionStringProperties, bool blnPartialConnectionString = false)
        {
            var settings = ConfigurationManager.ConnectionStrings["sqlConnectionString"];

            if (settings != null)
            {
                var connectString = settings.ConnectionString;

                var builder = new SqlConnectionStringBuilder(connectString);

                builder.DataSource = connectionStringProperties.DataSource;

                if (blnPartialConnectionString)
                {
                    builder.InitialCatalog = connectionStringProperties.InitialCatalog;
                }

                if (connectionStringProperties.AuthenticationType == Models.Enums.AuthenticationTypes.SQLServerAuthentication)
                {
                    builder.UserID   = connectionStringProperties.UserId;
                    builder.Password = connectionStringProperties.Password;
                }
                else
                {
                    builder.IntegratedSecurity = true;
                }

                builder.MultipleActiveResultSets = true;

                Global.ConnectionString = builder.ConnectionString;

                return(builder.ConnectionString);
            }

            return(string.Empty);
        }