string UtilityConnString(TestDatabase database) { string connString; if (!string.IsNullOrEmpty(database.ConnectionString)) { var helper = new ConnectionStringParser(database.ConnectionString); helper.RemovePartByName("DatabaseName"); helper.RemovePartByName("DBN"); helper.RemovePartByName("DatabaseFile"); helper.RemovePartByName("DBF"); connString = helper.GetConnectionString(); } else { string uid; string pwd; if (database.Login != null && !string.IsNullOrEmpty(database.Login.UserID)) { uid = database.Login.UserID; } else { uid = "dba"; } if (database.Login != null && !string.IsNullOrEmpty(database.Login.Password)) { pwd = database.Login.Password; } else { pwd = "sql"; } connString = string.Format("eng={0};uid={1};pwd={2};", database.Server, uid, pwd); } return "DBN=utility_db;" + connString; }
public void Should_parse_host_with_separate_port() { var parser = new ConnectionStringParser(new SettingsHolder()); var connectionConfiguration = parser.Parse("host=my.host.com;port=1234"); Assert.AreEqual(connectionConfiguration.HostConfiguration.Host, "my.host.com"); Assert.AreEqual(connectionConfiguration.HostConfiguration.Port, 1234); }
public void SutWithInvalidConnectionStringFormatReturnsEmpty( string invalidConnectionString, ConnectionStringParser sut) { var expected = Maybe.Empty<CmdApplicationConfiguration>(); var actual = sut.Parse(invalidConnectionString, SsmsCmdApplication.Application); Assert.Equal(expected, actual); }
public void SutWithValidConnectionStringFormatReturnsConfiguration( string validConnectionString, int expected, ConnectionStringParser sut) { var actual = sut.Parse(validConnectionString, SsmsCmdApplication.Application); Assert.Equal(expected, actual.First().Parameters.Count); }
public void Should_parse_list_of_hosts_without_ports() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=my.host.com,my.host2.com"); Assert.AreEqual(connectionConfiguration.Hosts.First().Host, "my.host.com"); Assert.AreEqual(connectionConfiguration.Hosts.Last().Host, "my.host2.com"); Assert.AreEqual(connectionConfiguration.Hosts.First().Port, 5672); Assert.AreEqual(connectionConfiguration.Hosts.Last().Port, 5672); }
public void ConnectionStringWithoutDatabaseReturnsDefaultText( string validConnectionStringWithoutDatabaseName, ConnectionStringParser sut) { var databaseParameterName = (Name)"-d"; var expected = databaseParameterName + " <default>"; var actual = sut.Parse(validConnectionStringWithoutDatabaseName, SsmsCmdApplication.Application); var databaseNameParameter = actual.Single().Parameters.Single(a => a.Name == databaseParameterName); Assert.Equal(expected, databaseNameParameter.GetValue()); }
public void Should_parse_host() { var parser = new ConnectionStringParser(new SettingsHolder()); var connectionConfiguration = parser.Parse("host=host.one:1001"); var hostConfiguration = connectionConfiguration.HostConfiguration; Assert.AreEqual(hostConfiguration.Host, "host.one"); Assert.AreEqual(hostConfiguration.Port, 1001); }
public void ParseCorrectlyParsesANamespaceConnectionString() { var endpoint = "test.endpoint.com"; var sasKey = "sasKey"; var sasKeyName = "sasName"; var connectionString = $"Endpoint=sb://{ endpoint };SharedAccessKeyName={ sasKeyName };SharedAccessKey={ sasKey }"; var 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.EventHubPath, 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) { var 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.EventHubPath, Is.EqualTo(eventHub), "The Event Hub path should match."); }
/// <summary> /// Initializes <see cref="MetadataExportAdapter"/>. /// </summary> public override void Initialize() { base.Initialize(); ConnectionStringParser <ConnectionStringParameterAttribute> parser = new ConnectionStringParser <ConnectionStringParameterAttribute>(); parser.ParseConnectionString(ConnectionString, this); if (string.IsNullOrWhiteSpace(ExportFilePath)) { ExportFilePath = Path.Combine("MetadataExports", $"{Name}.bin"); } }
public void ParseCorrectlyParsesPartialConnectionStrings(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."); }
public void ConnectionStringUserNamePasswordParserTest() { var connectionString = ConnectionStringParser.CreateConnectionString("test", "test", "test", "test", "test", "test"); var parsed = ConnectionStringParser.ParseConnectionString(connectionString); Assert.AreEqual("test", parsed.ConfigSetName); Assert.AreEqual("test", parsed.Password); Assert.AreEqual("test", parsed.Environment); Assert.AreEqual("test", parsed.UserName); Assert.AreEqual(false, parsed.UseAccessToken); Assert.AreEqual("test", parsed.Url); Assert.AreEqual("test", parsed.Domain); }
public void EnsureWellFormedConnectionStrings_Parsing_FailWithUnknownParameter() { var filesParser = ConnectionStringParser <FilesConnectionStringOptions> .FromConnectionString("ResourceManagerId=d5723e19-92ad-4531-adad-8611e6e05c8a;"); Assert.Throws <ArgumentException>(() => filesParser.Parse()); var dbParser = ConnectionStringParser <RavenConnectionStringOptions> .FromConnectionString("memory=true"); Assert.Throws <ArgumentException>(() => dbParser.Parse()); var embeddedParser = ConnectionStringParser <EmbeddedRavenConnectionStringOptions> .FromConnectionString("filesystem=test;"); Assert.Throws <ArgumentException>(() => embeddedParser.Parse()); }
private static void MoveFile(FileInfo fi) { string fileFullName = fi.FullName; string copyFileName = Path.Combine(COPY_PATH, Path.GetFileName(fileFullName)); if (UPLOAD_TYPE == 1) {//FTP ConnectionConfiguration ftpSetting = ConnectionStringParser.Parse(FTP_CONNECTION_STRING); FtpClient ftpClient = new FtpClient { Host = ftpSetting.UploadHost, Port = ftpSetting.UploadPort, Credentials = new NetworkCredential(ftpSetting.UploadUID, ftpSetting.UploadPWD) }; string fileName = Path.GetFileName(fileFullName); string filePath = Path.GetDirectoryName(fileFullName); filePath = filePath.Replace(Global.UPLOAD_PATH, ""); string copyFullName = Path.Combine(filePath, fileName); if (!ftpClient.DirectoryExists(filePath)) { ftpClient.CreateDirectory(filePath); } if (ftpClient.FileExists(filePath)) { ftpClient.DeleteFile(filePath); } using (Stream stream = ftpClient.OpenWrite(copyFullName, FtpDataType.Binary)) { byte[] oriBytes = File.ReadAllBytes(fileFullName); int offset = 0; int bufferSize = 0; while (offset < oriBytes.Length) { if (oriBytes.Length - 1 - offset < BUFFER_SIZE) { bufferSize = oriBytes.Length - offset; } else { bufferSize = BUFFER_SIZE; } stream.Write(oriBytes, offset, bufferSize); offset += bufferSize; } } } else { //网络驱动器 } }
public ServiceEndpointProvider(ServiceOptions options) { var connectionString = options.ConnectionString; if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentException(ConnectionStringNotFound); } _accessTokenLifetime = options.AccessTokenLifetime; // Version is ignored for aspnet signalr case (_endpoint, _accessKey, _, _port) = ConnectionStringParser.Parse(connectionString); }
public void Should_parse_list_of_hosts() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=host.one:1001,host.two:1002,host.three:1003"); var hosts = connectionConfiguration.Hosts; Assert.AreEqual(hosts.Count(), 3); Assert.AreEqual(hosts.ElementAt(0).Host, "host.one"); Assert.AreEqual(hosts.ElementAt(0).Port, 1001); Assert.AreEqual(hosts.ElementAt(1).Host, "host.two"); Assert.AreEqual(hosts.ElementAt(1).Port, 1002); Assert.AreEqual(hosts.ElementAt(2).Host, "host.three"); Assert.AreEqual(hosts.ElementAt(2).Port, 1003); }
public void ValidApplicationConnectionString(string expectedEndpoint, string connectionString) { var(accessKey, version, clientEndpoint) = ConnectionStringParser.Parse(connectionString); Assert.Equal(expectedEndpoint, accessKey.Endpoint); Assert.IsType <AadAccessKey>(accessKey); if (accessKey is AadAccessKey aadAccessKey) { Assert.IsType <ClientSecretCredential>(aadAccessKey.TokenCredential); } Assert.Null(version); Assert.Null(accessKey.Port); Assert.Null(clientEndpoint); }
internal void ValidMSIConnectionString(string expectedEndpoint, string connectionString) { var(accessKey, version, clientEndpoint) = ConnectionStringParser.Parse(connectionString); Assert.Equal(expectedEndpoint, accessKey.Endpoint); Assert.IsType <AadAccessKey>(accessKey); if (accessKey is AadAccessKey aadAccessKey) { Assert.IsType <ManagedIdentityCredential>(aadAccessKey.TokenCredential); } Assert.Null(version); Assert.Null(accessKey.Port); Assert.Null(clientEndpoint); }
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 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."); }
public ClientCommandDispatcherTests() { var eventBus = new EventBus(); var parser = new ConnectionStringParser(); var configuration = parser.Parse("host=localhost"); var hostSelectionStrategy = new RandomClusterHostSelectionStrategy <ConnectionFactoryInfo>(); var connectionFactory = new ConnectionFactoryWrapper(configuration, hostSelectionStrategy); connection = new PersistentConnection(connectionFactory, eventBus); var persistentChannelFactory = new PersistentChannelFactory(configuration, eventBus); dispatcher = new ClientCommandDispatcher(configuration, connection, persistentChannelFactory); connection.Initialize(); }
public KatushaRavenStore(string connectionName = "RavenDB") { var parser = ConnectionStringParser <RavenConnectionStringOptions> .FromConnectionStringName(connectionName); parser.Parse(); ApiKey = parser.ConnectionStringOptions.ApiKey; Url = parser.ConnectionStringOptions.Url; //RavenStore = new EmbeddableDocumentStore { DataDirectory = DependencyHelper.RootFolder + @"App_Data\MS.Katusha.RavenDB", UseEmbeddedHttpServer = true }; Initialize(); try { Create(); } catch { } }
public void SetUp() { var eventBus = new EventBus(); var logger = new ConsoleLogger(); var parser = new ConnectionStringParser(); var configuration = parser.Parse("host=localhost"); var hostSelectionStrategy = new RandomClusterHostSelectionStrategy <ConnectionFactoryInfo>(); var connectionFactory = new ConnectionFactoryWrapper(configuration, hostSelectionStrategy); connection = new PersistentConnection(connectionFactory, logger, eventBus); var persistentChannelFactory = new PersistentChannelFactory(logger, configuration, eventBus); dispatcher = new ClientCommandDispatcher(connection, persistentChannelFactory); }
public async Task ClientCanConnectToEventHubsUsingSharedKeyCredential() { await using (var scope = await EventHubScope.CreateAsync(1)) { var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName); var 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); } } }
public void ParseToleratesSpacesBetweenValues() { var endpoint = "test.endpoint.com"; var eventHub = "some-path"; var sasKey = "sasKey"; var sasKeyName = "sasName"; var connectionString = $"Endpoint = sb://{ endpoint };SharedAccessKeyName ={ sasKeyName };SharedAccessKey= { sasKey }; EntityPath = { eventHub }"; var 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.EventHubPath, Is.EqualTo(eventHub), "The Event Hub path should match."); }
public void SetUp() { routingTopology = new ConventionalRoutingTopology(true); receivedMessages = new BlockingCollection <IncomingMessage>(); var settings = new SettingsHolder(); settings.Set("NServiceBus.Routing.EndpointName", "endpoint"); var connectionString = Environment.GetEnvironmentVariable("RabbitMQTransport.ConnectionString"); ConnectionConfiguration config; if (connectionString != null) { var parser = new ConnectionStringParser(settings); config = parser.Parse(connectionString); } else { config = new ConnectionConfiguration(settings); config.Host = "localhost"; } connectionFactory = new ConnectionFactory(config); channelProvider = new ChannelProvider(connectionFactory, routingTopology, true); messageDispatcher = new MessageDispatcher(channelProvider); var purger = new QueuePurger(connectionFactory); messagePump = new MessagePump(connectionFactory, new MessageConverter(), "Unit test", channelProvider, purger, TimeSpan.FromMinutes(2), 3, 0); MakeSureQueueAndExchangeExists(ReceiverQueue); subscriptionManager = new SubscriptionManager(connectionFactory, routingTopology, ReceiverQueue); messagePump.Init(messageContext => { receivedMessages.Add(new IncomingMessage(messageContext.MessageId, messageContext.Headers, messageContext.Body)); return(TaskEx.CompletedTask); }, ErrorContext => Task.FromResult(ErrorHandleResult.Handled), new CriticalError(_ => TaskEx.CompletedTask), new PushSettings(ReceiverQueue, "error", true, TransportTransactionMode.ReceiveOnly) ).GetAwaiter().GetResult(); messagePump.Start(new PushRuntimeSettings(MaximumConcurrency)); }
public When_an_action_is_invoked_that_throws() { var parser = new ConnectionStringParser(); var configuration = parser.Parse("host=localhost"); var connection = Substitute.For <IPersistentConnection>(); var channelFactory = Substitute.For <IPersistentChannelFactory>(); channel = Substitute.For <IPersistentChannel>(); channelFactory.CreatePersistentChannel(connection).Returns(channel); channel.WhenForAnyArgs(x => x.InvokeChannelAction(null)) .Do(x => ((Action <IModel>)x[0])(null)); dispatcher = new ClientCommandDispatcher(configuration, connection, channelFactory); }
public void Should_Be_Able_To_Parse_ConnectionString_Without_Credentials_With_Port_And_VirtualHost() { /* Setup */ const string connectionString = "host:1234/virtualHost"; /* Test */ var config = ConnectionStringParser.Parse(connectionString); /* Assert */ Assert.Equal(expected: "guest", actual: config.Username); Assert.Equal(expected: "guest", actual: config.Password); Assert.Equal(expected: "virtualHost", actual: config.VirtualHost); Assert.Equal(expected: "host", actual: config.Hostnames[0]); Assert.Equal(expected: 1234, actual: config.Port); }
public void SetUp() { var parser = new ConnectionStringParser(); var configuration = parser.Parse("host=localhost"); var connection = MockRepository.GenerateStub <IPersistentConnection>(); var channelFactory = MockRepository.GenerateStub <IPersistentChannelFactory>(); channel = MockRepository.GenerateStub <IPersistentChannel>(); channelFactory.Stub(x => x.CreatePersistentChannel(connection)).Return(channel); channel.Stub(x => x.InvokeChannelAction(null)).IgnoreArguments().WhenCalled( x => ((Action <IModel>)x.Arguments[0])(null)); dispatcher = new ClientCommandDispatcher(configuration, connection, channelFactory); }
public async Task ItWorks() { var name = TestConfig.GetName("namespace"); var conn = new ConnectionStringParser(AsbTestConfig.ConnectionString); var newConn = new ConnectionStringParser($"{conn.Endpoint}{name}", conn.SharedAccessKeyName, conn.SharedAccessKey, conn.EntityPath); using (var activator = new BuiltinHandlerActivator()) { Configure.With(activator) .Transport(t => t.UseAzureServiceBus(newConn.GetConnectionString(), "test-queue")) .Start(); await Task.Delay(TimeSpan.FromSeconds(3)); } }
private static IDocumentStore GetDocumentStore( ConnectionStringParser<RavenConnectionStringOptions> connectionStringParser) { connectionStringParser.Parse(); string connectionStringApiKey = connectionStringParser.ConnectionStringOptions.ApiKey; string connectionStringUrl = connectionStringParser.ConnectionStringOptions.Url; var documentStore = new DocumentStore { ApiKey = connectionStringApiKey, Url = connectionStringUrl }; documentStore.Initialize(); InitDocumentStore(documentStore); return documentStore; }
public void CreateMeasurement(OutputMeasurement measurement) { MetaSignal metaSignal = new MetaSignal() { AnalyticProjectName = measurement.DevicePrefix, AnalyticInstanceName = measurement.DeviceSuffix, SignalType = measurement.SignalType, PointTag = measurement.PointTag, Description = measurement.Description }; string message = new ConnectionStringParser <SettingAttribute>().ComposeConnectionString(metaSignal); Subscriber.SendServerCommand((ServerCommand)ECAServerCommand.MetaSignal, message); }
private static IDocumentStore CreateStoreFromConnectionString(string connectionString) { var parser = ConnectionStringParser <RavenConnectionStringOptions> .FromConnectionString(connectionString); parser.Parse(); var options = parser.ConnectionStringOptions; return(new DocumentStore { Url = options.Url, Credentials = options.Credentials, Conventions = BuildDocumentConvention(), DefaultDatabase = options.DefaultDatabase ?? DatabaseName, }); }
protected void Application_ViewShown(object sender, ViewShownEventArgs e) { if (!Application.ConnectionString.Contains("XpoProvider")) { return; } ConnectionStringParser parser = new ConnectionStringParser(Application.ConnectionString); string provider = parser.GetPartByName("XpoProvider"); if (provider == "XmlDataSet") { ShowPerformanceWarning(); } }
static string GetConnectionString(XafApplication xafApplication) { if (!string.IsNullOrEmpty(xafApplication.ConnectionString)) { return(xafApplication.ConnectionString); } if (!Environment.Is64BitProcess) { return(XpoDefault.ConnectionString); } var connectionStringParser = new ConnectionStringParser(XpoDefault.ActiveConnectionString); connectionStringParser.UpdatePartByName("Provider", "Microsoft.ACE.OLEDB.12.0"); return(connectionStringParser.GetConnectionString()); }
static IDataStore CreateWebApiDataStoreFromString(string connectionString, AutoCreateOption autoCreateOption, out IDisposable[] objectsToDisposeOnDisconnect) { ConnectionStringParser parser = new ConnectionStringParser(connectionString); if (!parser.PartExists("uri")) { throw new ArgumentException("The connection string does not contain the 'uri' part."); } string uri = parser.GetPartByName("uri"); HttpClient client = new HttpClient(GetInsecureHandler()); client.BaseAddress = new Uri(uri); objectsToDisposeOnDisconnect = new IDisposable[] { client }; return(new WebApiDataStoreClient(client, autoCreateOption)); }
/// <summary> /// Initializes a new instance of the <see cref="SambaServiceDriver"/> class. /// </summary> /// <param name="fullPath">The working full path.</param> /// <param name="rootUrl">The root host url.</param> /// <param name="connectionString">The connection string.</param> /// <param name="maxDays">The maximum number of days to cache blob items for in the browser.</param> /// <param name="virtualPathRoute">When defined, Whether to use the default "media" route in the url independent of the blob container.</param> protected SambaServiceDriver(string fullPath, string rootUrl, string connectionString, int maxDays, string virtualPathRoute) { if (string.IsNullOrWhiteSpace(fullPath)) { throw new ArgumentNullException(nameof(fullPath)); } if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } this.VirtualPathRouteDisabled = string.IsNullOrEmpty(virtualPathRoute); var connectionStringParser = new ConnectionStringParser(); var connectionStringData = connectionStringParser.Decode(connectionString); // Full path must use `directorySeparatorChar` and ends with separator. this.rootFullPath = fullPath.Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar); if (this.rootFullPath.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) == false) { this.rootFullPath += System.IO.Path.DirectorySeparatorChar; } // SambaPath must be use `directorySeparatorChar` and do not end with separator. this.SambaPath = connectionStringData.SambaPath .Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar) .TrimEnd(System.IO.Path.DirectorySeparatorChar); this.sambaCredential = new NetworkCredential(connectionStringData.Username, connectionStringData.Password, connectionStringData.Domain); this.instanceKey = CreateInstanceKey(fullPath, rootUrl, connectionString, virtualPathRoute); this.MaxDays = maxDays; this.VirtualPathRoute = this.VirtualPathRouteDisabled ? null : virtualPathRoute; this.rootHostUrl = rootUrl; if (string.IsNullOrEmpty(this.rootHostUrl)) { this.rootHostUrl = $"/{this.VirtualPathRoute}"; } if (this.rootHostUrl.EndsWith("/") == false) { this.rootHostUrl += "/"; } this.rootFullPathUrlCache = null; this.LogHelper = new WrappedLogHelper(); this.MimeTypeResolver = new MimeTypeResolver(); }
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."); }
public void Should_correctly_parse_full_connection_string() { var parser = new ConnectionStringParser(new SettingsHolder()); var connectionConfiguration = parser.Parse(connectionString); Assert.AreEqual(connectionConfiguration.HostConfiguration.Host, "192.168.1.1"); Assert.AreEqual(connectionConfiguration.HostConfiguration.Port, 1234); Assert.AreEqual(connectionConfiguration.VirtualHost, "Copa"); Assert.AreEqual(connectionConfiguration.UserName, "Copa"); Assert.AreEqual(connectionConfiguration.Password, "abc_xyz"); Assert.AreEqual(connectionConfiguration.Port, 12345); Assert.AreEqual(connectionConfiguration.RequestedHeartbeat, 3); Assert.AreEqual(connectionConfiguration.PrefetchCount, 2); Assert.AreEqual(connectionConfiguration.UsePublisherConfirms, true); Assert.AreEqual(connectionConfiguration.MaxWaitTimeForConfirms, new TimeSpan(2, 3, 39)); //02:03:39 Assert.AreEqual(connectionConfiguration.RetryDelay, new TimeSpan(1, 2, 3)); //01:02:03 }
public static string Individualize(string queueName) { var parser = new ConnectionStringParser(); var individualQueueName = queueName; if (SafeRoleEnvironment.IsAvailable) { var index = parser.ParseIndexFrom(SafeRoleEnvironment.CurrentRoleInstanceId); var currentQueue = parser.ParseQueueNameFrom(queueName); if (!currentQueue.EndsWith("-" + index.ToString(CultureInfo.InvariantCulture))) //individualize can be applied multiple times { individualQueueName = currentQueue + (index > 0 ? "-" : "") + (index > 0 ? index.ToString(CultureInfo.InvariantCulture) : ""); } if (queueName.Contains("@")) individualQueueName += "@" + parser.ParseNamespaceFrom(queueName); } return individualQueueName; }
public void Should_parse_the_prefetch_count() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;prefetchcount=10"); Assert.AreEqual(10, connectionConfiguration.PrefetchCount); }
public void Should_parse_the_requestedHeartbeat() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;requestedHeartbeat=5"); Assert.AreEqual(5, connectionConfiguration.RequestedHeartbeat); }
/// <summary> /// Создает поставщика данных на основе строки соединения /// </summary> /// <param name="connectionString">Строка соединения с поставщиком данных</param> /// <param name="autoCreateOption">Опция автосоздания структуры базы данных</param> /// <param name="objectsToDisposeOnDisconnect">Объекты, требующие удаления после отключения соединения</param> /// <returns>Экземпляр поставщика данных OracleConnectionProviderEx</returns> public static new IDataStore CreateProviderFromString(string connectionString, AutoCreateOption autoCreateOption, out IDisposable[] objectsToDisposeOnDisconnect) { // Файл для записи скрипта string scriptPath = null; UpdateSchemaOptions updateOptions = UpdateSchemaOptions.Default; bool? insensitive = null; string indexTablespace = null; ConnectionStringParser parser = new ConnectionStringParser(connectionString); if (parser.PartExists(ScriptParameterName)) { scriptPath = parser.GetPartByName(ScriptParameterName); parser.RemovePartByName(ScriptParameterName); connectionString = parser.GetConnectionString(); } // Опции обновления if (parser.PartExists(UpdateOptionsParameterName)) { updateOptions = (UpdateSchemaOptions)Convert.ToInt32(parser.GetPartByName(UpdateOptionsParameterName)); parser.RemovePartByName(UpdateOptionsParameterName); connectionString = parser.GetConnectionString(); } // Регистронезависимость в условиях if (parser.PartExists(InsesnsitiveParameterName)) { insensitive = Convert.ToBoolean(parser.GetPartByName(InsesnsitiveParameterName)); parser.RemovePartByName(InsesnsitiveParameterName); connectionString = parser.GetConnectionString(); } // Табличное пространство для индексов if (parser.PartExists(IndexTablespaceParameterName)) { indexTablespace = parser.GetPartByName(IndexTablespaceParameterName); parser.RemovePartByName(IndexTablespaceParameterName); connectionString = parser.GetConnectionString(); } // Соединение IDbConnection connection = CreateConnection(connectionString); objectsToDisposeOnDisconnect = new IDisposable[] { connection }; return scriptPath == null && updateOptions == UpdateSchemaOptions.Default && !insensitive.HasValue && indexTablespace == null ? CreateProviderFromConnection(connection, autoCreateOption) : new OracleConnectionProviderEx(connection, autoCreateOption, scriptPath, updateOptions, insensitive, indexTablespace); }
private static bool IsMySql(ITypeInfo typeInfo) { var sequenceObjectObjectSpaceProvider = GetSequenceObjectObjectSpaceProvider(typeInfo.Type); if (sequenceObjectObjectSpaceProvider != null) { var helper = new ConnectionStringParser(sequenceObjectObjectSpaceProvider.ConnectionString); string providerType = helper.GetPartByName(DataStoreBase.XpoProviderTypeParameterName); return providerType == MySqlConnectionProvider.XpoProviderTypeString; } return false; }
public void Should_parse_the_retry_delay() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;retryDelay=00:00:10"); Assert.AreEqual(TimeSpan.FromSeconds(10), connectionConfiguration.RetryDelay); }
public void Should_parse_the_port() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;port=8181"); Assert.AreEqual(8181, connectionConfiguration.Hosts.First().Port); }
protected override void Configure(FeatureConfigurationContext context, string connectionString) { var useCallbackReceiver = context.Settings.Get<bool>(UseCallbackReceiverSettingKey); var maxConcurrencyForCallbackReceiver = context.Settings.Get<int>(MaxConcurrencyForCallbackReceiver); var queueName = GetLocalAddress(context.Settings); var callbackQueue = string.Format("{0}.{1}", queueName, RuntimeEnvironment.MachineName); var connectionConfiguration = new ConnectionStringParser(context.Settings).Parse(connectionString); MessageConverter messageConverter; if (context.Settings.HasSetting(CustomMessageIdStrategy)) { messageConverter = new MessageConverter(context.Settings.Get<Func<BasicDeliverEventArgs, string>>(CustomMessageIdStrategy)); } else { messageConverter = new MessageConverter(); } string hostDisplayName; if (!context.Settings.TryGet("NServiceBus.HostInformation.DisplayName", out hostDisplayName))//this was added in 5.1.2 of the core { hostDisplayName = RuntimeEnvironment.MachineName; } var consumerTag = string.Format("{0} - {1}", hostDisplayName, context.Settings.EndpointName()); var receiveOptions = new ReceiveOptions(workQueue => { //if this isn't the main queue we shouldn't use callback receiver if (!useCallbackReceiver || workQueue != queueName) { return SecondaryReceiveSettings.Disabled(); } return SecondaryReceiveSettings.Enabled(callbackQueue, maxConcurrencyForCallbackReceiver); }, messageConverter, connectionConfiguration.PrefetchCount, connectionConfiguration.DequeueTimeout * 1000, context.Settings.GetOrDefault<bool>("Transport.PurgeOnStartup"), consumerTag); context.Container.RegisterSingleton(connectionConfiguration); context.Container.ConfigureComponent(builder => new RabbitMqDequeueStrategy( builder.Build<IManageRabbitMqConnections>(), SetupCircuitBreaker(builder.Build<CriticalError>()), receiveOptions), DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<OpenPublishChannelBehavior>(DependencyLifecycle.InstancePerCall); context.Pipeline.Register<OpenPublishChannelBehavior.Registration>(); context.Container.ConfigureComponent<RabbitMqMessageSender>(DependencyLifecycle.InstancePerCall); if (useCallbackReceiver) { context.Container.ConfigureProperty<RabbitMqMessageSender>(p => p.CallbackQueue, callbackQueue); context.Container.ConfigureComponent<CallbackQueueCreator>(DependencyLifecycle.InstancePerCall) .ConfigureProperty(p => p.Enabled, true) .ConfigureProperty(p => p.CallbackQueueAddress, Address.Parse(callbackQueue)); context.Pipeline.Register<ForwardCallbackQueueHeaderBehavior.Registration>(); } context.Container.ConfigureComponent<ChannelProvider>(DependencyLifecycle.InstancePerCall) .ConfigureProperty(p => p.UsePublisherConfirms, connectionConfiguration.UsePublisherConfirms) .ConfigureProperty(p => p.MaxWaitTimeForConfirms, connectionConfiguration.MaxWaitTimeForConfirms); context.Container.ConfigureComponent<RabbitMqDequeueStrategy>(DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<RabbitMqMessagePublisher>(DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<RabbitMqSubscriptionManager>(DependencyLifecycle.SingleInstance) .ConfigureProperty(p => p.EndpointQueueName, queueName); context.Container.ConfigureComponent<RabbitMqQueueCreator>(DependencyLifecycle.InstancePerCall); if (context.Settings.HasSetting<IRoutingTopology>()) { context.Container.RegisterSingleton(context.Settings.Get<IRoutingTopology>()); } else { var durable = GetDurableMessagesEnabled(context.Settings); IRoutingTopology topology; DirectRoutingTopology.Conventions conventions; if (context.Settings.TryGet(out conventions)) { topology = new DirectRoutingTopology(conventions, durable); } else { topology = new ConventionalRoutingTopology(durable); } context.Container.RegisterSingleton(topology); } if (context.Settings.HasSetting("IManageRabbitMqConnections")) { context.Container.ConfigureComponent(context.Settings.Get<Type>("IManageRabbitMqConnections"), DependencyLifecycle.SingleInstance); } else { context.Container.ConfigureComponent<RabbitMqConnectionManager>(DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(builder => new RabbitMqConnectionFactory(builder.Build<ConnectionConfiguration>()), DependencyLifecycle.InstancePerCall); } }
public void Should_throw_if_given_badly_formatted_max_wait_time_for_confirms() { var parser = new ConnectionStringParser(); var formatException = Assert.Throws<FormatException>(() => parser.Parse("host=localhost;maxWaitTimeForConfirms=00:0d0:10")); Assert.AreEqual("00:0d0:10 is not a valid value for TimeSpan.",formatException.Message); }
public void Should_throw_if_given_badly_formatted_retry_delay() { var parser = new ConnectionStringParser(); var formatException = Assert.Throws<FormatException>(() => parser.Parse("host=localhost;retryDelay=00:0d0:10")); Assert.AreEqual("00:0d0:10 is not a valid value for TimeSpan.", formatException.Message); }
public void Should_throw_on_malformed_string() { var parser = new ConnectionStringParser(); parser.Parse("not a well formed name value pair;"); }
public void Setup() { parser = new ConnectionStringParser(new SettingsHolder()); defaults = new ConnectionConfiguration(); }
public void Should_fail_if_host_is_not_present() { var parser = new ConnectionStringParser(); parser.Parse("virtualHost=Copa;username=Copa;password=abc_xyz;port=12345;requestedHeartbeat=3"); }
public void Setup() { parser = new ConnectionStringParser(); }
static MSSqlConnectionProvider DataStore(string connectionString) { var connectionStringParser = new ConnectionStringParser(connectionString); var userid = connectionStringParser.GetPartByName("UserId"); var password = connectionStringParser.GetPartByName("password"); string connectionStr; if (!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(password)) connectionStr = MSSqlConnectionProvider.GetConnectionString(connectionStringParser.GetPartByName("Data Source"), userid, password, "master"); else { connectionStr = MSSqlConnectionProvider.GetConnectionString(connectionStringParser.GetPartByName("Data Source"), "master"); } return (MSSqlConnectionProvider)XpoDefault.GetConnectionProvider(connectionStr, AutoCreateOption.None); }
private ConnectionOptions ParseConnectionString (string connectionString) { pool = null; ConnectionStringParser parser = new ConnectionStringParser (); ConnectionOptions newOptions = new ConnectionOptions (); parser.Parse (connectionString, newOptions); // can throw an exception newOptions.Verify (); // can throw an exception return newOptions; }
public void Should_parse_the_hostname() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=myHost"); Assert.AreEqual("myHost", connectionConfiguration.Hosts.First().Host); }
public void Should_parse_the_virtual_hostname() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;virtualHost=myVirtualHost"); Assert.AreEqual("myVirtualHost", connectionConfiguration.VirtualHost); }
public void Should_parse_the_username() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;username=test"); Assert.AreEqual("test", connectionConfiguration.UserName); }
public void Should_parse_the_password() { var parser = new ConnectionStringParser(); var connectionConfiguration = parser.Parse("host=localhost;password=test"); Assert.AreEqual("test", connectionConfiguration.Password); }