From 9006c29ef6fab8bb0236462168e1b0695957e8f6 Mon Sep 17 00:00:00 2001 From: michaelahojna Date: Wed, 16 Nov 2022 10:14:49 +0100 Subject: [PATCH] feat: Initialize C# client without InfluxDBClientFactory (#388) --- CHANGELOG.md | 7 + Client.Legacy.Test/AbstractFluxClientTest.cs | 2 +- .../AbstractItFluxClientTest.cs | 2 +- Client.Legacy.Test/FluxClientPingTest.cs | 4 +- Client.Legacy.Test/FluxClientQueryTest.cs | 4 +- Client.Legacy.Test/FluxClientTest.cs | 6 +- Client.Legacy.Test/ItFluxClientTest.cs | 4 +- Client.Legacy/FluxClient.cs | 32 ++ Client.Legacy/FluxClientFactory.cs | 6 + Client.Legacy/README.md | 14 +- Client.Linq.Test/InfluxDBQueryVariableTest.cs | 4 +- Client.Linq.Test/InfluxDBQueryVisitorTest.cs | 5 +- Client.Linq.Test/ItInfluxDBQueryableTest.cs | 2 +- Client.Linq/README.md | 4 +- Client.Test/AbstractItClientTest.cs | 4 +- Client.Test/ApiClientTest.cs | 18 +- Client.Test/GzipHandlerTest.cs | 2 +- Client.Test/InfluxDbClientFactoryTest.cs | 257 ++++++++++ Client.Test/InfluxDbClientTest.cs | 51 +- Client.Test/ItDeleteApiTest.cs | 32 +- Client.Test/ItInfluxDBClientTest.cs | 16 +- Client.Test/ItMonitoringAlertingTest.cs | 2 +- Client.Test/ItTasksApiTest.cs | 4 +- Client.Test/ItWriteApiAsyncTest.cs | 10 +- Client.Test/ItWriteApiRaceTest.cs | 16 +- Client.Test/ItWriteManyMeasurements.cs | 7 +- Client.Test/ItWriteQueryApiTest.cs | 82 +-- Client.Test/QueryApiSyncTest.cs | 33 +- Client.Test/QueryApiTest.cs | 31 +- Client.Test/RetryAttemptTest.cs | 30 +- Client.Test/WriteApiAsyncTest.cs | 49 +- Client.Test/WriteApiTest.cs | 96 ++-- Client/InfluxDBClient.cs | 83 ++- Client/InfluxDBClientFactory.cs | 24 +- Client/InfluxDBClientOptions.cs | 477 +++++++++++++++--- Client/Internal/ApiClient.cs | 4 +- Client/README.md | 188 +++---- Client/WriteOptions.cs | 119 ++++- Client/Writes/PointSettings.cs | 18 + Examples/CustomDomainMapping.cs | 19 +- Examples/CustomDomainMappingAndLinq.cs | 19 +- Examples/ExampleBlazor/Data/ClientSettings.cs | 12 +- ...FactoryExample.cs => FluxClientExample.cs} | 8 +- Examples/FluxClientPocoExample.cs | 6 +- Examples/FluxClientSimpleExample.cs | 4 +- Examples/FluxExample.cs | 6 +- Examples/FluxRawExample.cs | 6 +- Examples/InfluxDB18Example.cs | 8 +- Examples/InvokableScripts.cs | 16 +- Examples/ManagementExample.cs | 4 +- Examples/ParametrizedQuery.cs | 17 +- Examples/PlatformExample.cs | 161 +++--- Examples/PocoQueryWriteExample.cs | 20 +- Examples/QueryLinqCloud.cs | 20 +- Examples/RecordRowExample.cs | 2 +- Examples/RunExamples.cs | 32 +- Examples/SynchronousQuery.cs | 4 +- Examples/WriteApiAsyncExample.cs | 12 +- Examples/WriteEventHandlerExample.cs | 37 +- README.md | 16 +- 60 files changed, 1527 insertions(+), 651 deletions(-) rename Examples/{FluxClientFactoryExample.cs => FluxClientExample.cs} (81%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1971adc18..1f54c0a88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ ## 4.8.0 [unreleased] +:warning: The client can be created without `InfluxDBClientFactory`: + + using var client = new InfluxDBClient("http://localhost:8086", "my-token"); + +### Features +1. [#388](https://github.com/influxdata/influxdb-client-csharp/pull/388): Initialize C# client without `InfluxDBClientFactory` + ### CI 1. [#416](https://github.com/influxdata/influxdb-client-csharp/pull/416): Add build for `.NET 7.0` diff --git a/Client.Legacy.Test/AbstractFluxClientTest.cs b/Client.Legacy.Test/AbstractFluxClientTest.cs index fd730b690..f76042486 100644 --- a/Client.Legacy.Test/AbstractFluxClientTest.cs +++ b/Client.Legacy.Test/AbstractFluxClientTest.cs @@ -21,7 +21,7 @@ public class AbstractFluxClientTest : AbstractMockServerTest [SetUp] public new void SetUp() { - FluxClient = FluxClientFactory.Create(MockServerUrl); + FluxClient = new FluxClient(MockServerUrl); } [TearDown] diff --git a/Client.Legacy.Test/AbstractItFluxClientTest.cs b/Client.Legacy.Test/AbstractItFluxClientTest.cs index d2519b37e..435ab23b5 100644 --- a/Client.Legacy.Test/AbstractItFluxClientTest.cs +++ b/Client.Legacy.Test/AbstractItFluxClientTest.cs @@ -23,7 +23,7 @@ private async Task SetUpAsync() var options = new FluxConnectionOptions(influxUrl); - FluxClient = FluxClientFactory.Create(options); + FluxClient = new FluxClient(options); await InfluxDbQuery("CREATE DATABASE " + DatabaseName, DatabaseName); } diff --git a/Client.Legacy.Test/FluxClientPingTest.cs b/Client.Legacy.Test/FluxClientPingTest.cs index 921a080ba..ae7577b65 100644 --- a/Client.Legacy.Test/FluxClientPingTest.cs +++ b/Client.Legacy.Test/FluxClientPingTest.cs @@ -40,7 +40,7 @@ public async Task NotRunningServer() public async Task WithAuthentication() { FluxClient = - FluxClientFactory.Create(new FluxConnectionOptions(MockServerUrl, "my-user", + new FluxClient(new FluxConnectionOptions(MockServerUrl, "my-user", "my-password".ToCharArray())); MockServer.Given(Request.Create() @@ -56,7 +56,7 @@ public async Task WithAuthentication() [Test] public async Task WithBasicAuthentication() { - FluxClient = FluxClientFactory.Create(new FluxConnectionOptions(MockServerUrl, "my-user", + FluxClient = new FluxClient(new FluxConnectionOptions(MockServerUrl, "my-user", "my-password".ToCharArray(), FluxConnectionOptions.AuthenticationType.BasicAuthentication)); var auth = System.Text.Encoding.UTF8.GetBytes("my-user:my-password"); diff --git a/Client.Legacy.Test/FluxClientQueryTest.cs b/Client.Legacy.Test/FluxClientQueryTest.cs index 1095c3e6d..3b98255ee 100644 --- a/Client.Legacy.Test/FluxClientQueryTest.cs +++ b/Client.Legacy.Test/FluxClientQueryTest.cs @@ -230,7 +230,7 @@ public async Task UserAgentHeader() public async Task WithAuthentication() { FluxClient = - FluxClientFactory.Create(new FluxConnectionOptions(MockServerUrl, "my-user", + new FluxClient(new FluxConnectionOptions(MockServerUrl, "my-user", "my-password".ToCharArray())); MockServer.Given(Request.Create() @@ -248,7 +248,7 @@ public async Task WithAuthentication() [Test] public async Task WithBasicAuthentication() { - FluxClient = FluxClientFactory.Create(new FluxConnectionOptions(MockServerUrl, "my-user", + FluxClient = new FluxClient(new FluxConnectionOptions(MockServerUrl, "my-user", "my-password".ToCharArray(), FluxConnectionOptions.AuthenticationType.BasicAuthentication)); var auth = System.Text.Encoding.UTF8.GetBytes("my-user:my-password"); diff --git a/Client.Legacy.Test/FluxClientTest.cs b/Client.Legacy.Test/FluxClientTest.cs index fb059bae4..ae42b5fca 100644 --- a/Client.Legacy.Test/FluxClientTest.cs +++ b/Client.Legacy.Test/FluxClientTest.cs @@ -16,7 +16,7 @@ public class FluxClientTest [SetUp] public void SetUp() { - _fluxClient = FluxClientFactory.Create("http://localhost:8093"); + _fluxClient = new FluxClient("http://localhost:8093"); } [Test] @@ -42,9 +42,9 @@ public void ProxyDefaultConfigured() TimeSpan.FromSeconds(60), webProxy: webProxy); - var fluxClient = FluxClientFactory.Create(options); + var client = new FluxClient(options); - Assert.AreEqual(webProxy, GetRestClient(fluxClient).Options.Proxy); + Assert.AreEqual(webProxy, GetRestClient(client).Options.Proxy); } [Test] diff --git a/Client.Legacy.Test/ItFluxClientTest.cs b/Client.Legacy.Test/ItFluxClientTest.cs index a97b0486b..58fab3aee 100644 --- a/Client.Legacy.Test/ItFluxClientTest.cs +++ b/Client.Legacy.Test/ItFluxClientTest.cs @@ -213,9 +213,9 @@ public async Task CallbackWhenConnectionRefuse() { var options = new FluxConnectionOptions("http://localhost:8003"); - var fluxClient = FluxClientFactory.Create(options); + var client = new FluxClient(options); - await fluxClient.QueryAsync(FromFluxDatabase + " |> last()", + await client.QueryAsync(FromFluxDatabase + " |> last()", record => { }, error => CountdownEvent.Signal()); diff --git a/Client.Legacy/FluxClient.cs b/Client.Legacy/FluxClient.cs index cfb772459..0d88e335f 100644 --- a/Client.Legacy/FluxClient.cs +++ b/Client.Legacy/FluxClient.cs @@ -126,6 +126,38 @@ public class FluxClient : AbstractQueryClient, IFluxClient { private readonly LoggingHandler _loggingHandler; + /// + /// Create a instance of the Flux client. The url could be a connection string with various configurations. + /// + /// e.g.: "http://localhost:8086?timeout=5000&logLevel=BASIC + /// The following options are supported: + /// + /// org - default destination organization for writes and queries + /// bucket - default destination bucket for writes + /// token - the token to use for the authorization + /// logLevel (default - NONE) - rest client verbosity level + /// timeout (default - 10000) - The timespan to wait before the HTTP request times out in milliseconds + /// allowHttpRedirects (default - false) - Configure automatically following HTTP 3xx redirects + /// verifySsl (default - true) - Ignore Certificate Validation Errors when false + /// + /// Options for logLevel: + /// + /// Basic - Logs request and response lines. + /// Body - Logs request and response lines including headers and body (if present). Note that applying the `Body` LogLevel will disable chunking while streaming and will load the whole response into memory. + /// Headers - Logs request and response lines including headers. + /// None - Disable logging. + /// + /// + /// + /// the connectionString to connect to InfluxDB + public FluxClient(string connectionString) : this(new FluxConnectionOptions(connectionString)) + { + } + + /// + /// Create a instance of the Flux client. + /// + /// the connection configuration public FluxClient(FluxConnectionOptions options) : base(new FluxResultMapper()) { _loggingHandler = new LoggingHandler(LogLevel.None); diff --git a/Client.Legacy/FluxClientFactory.cs b/Client.Legacy/FluxClientFactory.cs index c7e004048..b2cf21d9f 100644 --- a/Client.Legacy/FluxClientFactory.cs +++ b/Client.Legacy/FluxClientFactory.cs @@ -1,3 +1,5 @@ +using System; + namespace InfluxDB.Client.Flux { /// @@ -10,6 +12,8 @@ public class FluxClientFactory /// /// the connectionString to connect to InfluxDB /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'FluxClient' initializer instead.", false)] public static FluxClient Create(string connectionString) { var options = new FluxConnectionOptions(connectionString); @@ -22,6 +26,8 @@ public static FluxClient Create(string connectionString) /// /// the connection configuration /// + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'FluxClient' initializer instead.", false)] public static FluxClient Create(FluxConnectionOptions options) { return new FluxClient(options); diff --git a/Client.Legacy/README.md b/Client.Legacy/README.md index 6ae667ee8..00696b852 100644 --- a/Client.Legacy/README.md +++ b/Client.Legacy/README.md @@ -31,9 +31,9 @@ The `FluxClientFactory` creates an instance of a `FluxClient` client that can be // client creation var options = new FluxConnectionOptions("http://127.0.0.1:8086"); -using var fluxClient = FluxClientFactory.Create(options); +using var client = new FluxClient(options); -fluxClient.QueryAsync(...) +client.QueryAsync(...) ... ``` #### Authenticate requests @@ -43,9 +43,9 @@ fluxClient.QueryAsync(...) // client creation var options = new FluxConnectionOptions("http://127.0.0.1:8086", "my-user", "my-password".ToCharArray()); -using var fluxClient = FluxClientFactory.Create(options); +using var client = new FluxClient(options); -fluxClient.QueryAsync(...) +client.QueryAsync(...) ... ``` @@ -55,9 +55,9 @@ fluxClient.QueryAsync(...) var options = new FluxConnectionOptions("http://127.0.0.1:8086", "my-user", "my-password".ToCharArray(), FluxConnectionOptions.AuthenticationType.BasicAuthentication); -using var fluxClient = FluxClientFactory.Create(options); +using var client = new FluxClient(options); -fluxClient.QueryAsync(...) +client.QueryAsync(...) ... ``` @@ -123,7 +123,7 @@ The Requests and Responses can be logged by changing the LogLevel. LogLevel valu applying the `Body` LogLevel will disable chunking while streaming and will load the whole response into memory. ```c# -fluxClient.SetLogLevel(LogLevel.Body) +client.SetLogLevel(LogLevel.Body) ``` ## Version diff --git a/Client.Linq.Test/InfluxDBQueryVariableTest.cs b/Client.Linq.Test/InfluxDBQueryVariableTest.cs index a11ce86fe..a7d80c6be 100644 --- a/Client.Linq.Test/InfluxDBQueryVariableTest.cs +++ b/Client.Linq.Test/InfluxDBQueryVariableTest.cs @@ -20,7 +20,7 @@ public class InfluxDbQueryVariableTest : AbstractTest [SetUp] public new Task SetUp() { - _client = InfluxDBClientFactory.Create(GetInfluxDb2Url(), "my-token"); + _client = new InfluxDBClient(GetInfluxDb2Url(), "my-token"); _client.SetLogLevel(LogLevel.Body); return Task.CompletedTask; } @@ -28,7 +28,7 @@ public class InfluxDbQueryVariableTest : AbstractTest [OneTimeSetUp] public async Task OneTimeSetUp() { - _client = InfluxDBClientFactory.Create(GetInfluxDb2Url(), "my-token"); + _client = new InfluxDBClient(GetInfluxDb2Url(), "my-token"); _client.SetLogLevel(LogLevel.Body); _dateTime = DateTime.UtcNow; diff --git a/Client.Linq.Test/InfluxDBQueryVisitorTest.cs b/Client.Linq.Test/InfluxDBQueryVisitorTest.cs index 34bc2bdbb..93a5ccf1c 100644 --- a/Client.Linq.Test/InfluxDBQueryVisitorTest.cs +++ b/Client.Linq.Test/InfluxDBQueryVisitorTest.cs @@ -33,10 +33,7 @@ public class InfluxDBQueryVisitorTest : AbstractTest [OneTimeSetUp] public void InitQueryApi() { - var options = new InfluxDBClientOptions.Builder() - .Url("http://localhost:8086") - .AuthenticateToken("my-token") - .Build(); + var options = new InfluxDBClientOptions("http://localhost:8086") { Token = "my-token" }; var queryService = new Mock("http://localhost:8086/api/v2"); _queryApi = new Mock(options, queryService.Object, new FluxResultMapper()).Object; } diff --git a/Client.Linq.Test/ItInfluxDBQueryableTest.cs b/Client.Linq.Test/ItInfluxDBQueryableTest.cs index fc9f9c514..581b8f629 100644 --- a/Client.Linq.Test/ItInfluxDBQueryableTest.cs +++ b/Client.Linq.Test/ItInfluxDBQueryableTest.cs @@ -18,7 +18,7 @@ public class ItInfluxDBQueryableTest : AbstractTest [SetUp] public new async Task SetUp() { - _client = InfluxDBClientFactory.Create(GetInfluxDb2Url(), "my-token"); + _client = new InfluxDBClient(GetInfluxDb2Url(), "my-token"); _client.SetLogLevel(LogLevel.Body); // DateTime(2020, 10, 15, 8, 20, 15, DateTimeKind.Utc) diff --git a/Client.Linq/README.md b/Client.Linq/README.md index e59d9188c..193951a9e 100644 --- a/Client.Linq/README.md +++ b/Client.Linq/README.md @@ -64,7 +64,7 @@ using InfluxDB.Client.Linq; The LINQ query depends on `QueryApiSync`, you could create an instance of `QueryApiSync` by: ```c# -var client = InfluxDBClientFactory.Create("http://localhost:8086", "my-token"); +var client = new InfluxDBClient("http://localhost:8086", "my-token"); var queryApi = client.GetQueryApiSync(); ``` @@ -1170,7 +1170,7 @@ private class InfluxPoint The LINQ driver also supports asynchronous querying. For asynchronous queries you have to initialize `InfluxDBQueryable` with asynchronous version of [QueryApi](/Client/QueryApi.cs) and transform `IQueryable` to `IAsyncEnumerable`: ```c# -var client = InfluxDBClientFactory.Create("http://localhost:8086", "my-token"); +var client = new InfluxDBClient("http://localhost:8086", "my-token"); var queryApi = client.GetQueryApi(); var query = from s in InfluxDBQueryable.Queryable("my-bucket", "my-org", queryApi) diff --git a/Client.Test/AbstractItClientTest.cs b/Client.Test/AbstractItClientTest.cs index 75b5dcffa..32de6ed79 100644 --- a/Client.Test/AbstractItClientTest.cs +++ b/Client.Test/AbstractItClientTest.cs @@ -18,11 +18,11 @@ public class AbstractItClientTest : AbstractTest if (!TestContext.CurrentContext.Test.Properties.ContainsKey("basic_auth")) { - Client = InfluxDBClientFactory.Create(InfluxDbUrl, "my-token"); + Client = new InfluxDBClient(InfluxDbUrl, "my-token"); } else { - Client = InfluxDBClientFactory.Create(InfluxDbUrl, "my-user", "my-password".ToCharArray()); + Client = new InfluxDBClient(InfluxDbUrl, "my-user", "my-password"); } } diff --git a/Client.Test/ApiClientTest.cs b/Client.Test/ApiClientTest.cs index e4cffc0f6..4b4ffbcce 100644 --- a/Client.Test/ApiClientTest.cs +++ b/Client.Test/ApiClientTest.cs @@ -15,10 +15,10 @@ public class ApiClientTest [SetUp] public void SetUp() { - var options = new InfluxDBClientOptions.Builder() - .Url("http://localhost:8086") - .AuthenticateToken("my-token".ToCharArray()) - .Build(); + var options = new InfluxDBClientOptions("http://localhost:8086") + { + Token = "my-token" + }; _apiClient = new ApiClient(options, new LoggingHandler(LogLevel.Body), new GzipHandler()); } @@ -51,11 +51,11 @@ public void ProxyDefaultConfigured() { var webProxy = new WebProxy("my-proxy", 8088); - var options = new InfluxDBClientOptions.Builder() - .Url("http://localhost:8086") - .AuthenticateToken("my-token".ToCharArray()) - .Proxy(webProxy) - .Build(); + var options = new InfluxDBClientOptions("http://localhost:8086") + { + Token = "my-token", + WebProxy = webProxy + }; _apiClient = new ApiClient(options, new LoggingHandler(LogLevel.Body), new GzipHandler()); diff --git a/Client.Test/GzipHandlerTest.cs b/Client.Test/GzipHandlerTest.cs index d47078d94..5222f580f 100644 --- a/Client.Test/GzipHandlerTest.cs +++ b/Client.Test/GzipHandlerTest.cs @@ -15,7 +15,7 @@ public class GzipHandlerTest : AbstractMockServerTest [SetUp] public new void SetUp() { - _client = InfluxDBClientFactory.Create(MockServerUrl); + _client = new InfluxDBClient(MockServerUrl); } [Test] diff --git a/Client.Test/InfluxDbClientFactoryTest.cs b/Client.Test/InfluxDbClientFactoryTest.cs index 6543488d0..21fdbc5d5 100644 --- a/Client.Test/InfluxDbClientFactoryTest.cs +++ b/Client.Test/InfluxDbClientFactoryTest.cs @@ -24,6 +24,18 @@ public void TearDown() [Test] public void CreateInstance() + { + _client = new InfluxDBClient("http://localhost:9999"); + + Assert.IsNotNull(_client); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual(false, options.AllowHttpRedirects); + } + + [Test] + [Obsolete("Obsolete")] + public void CreateInstanceFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999"); @@ -35,6 +47,18 @@ public void CreateInstance() [Test] public void CreateInstanceVerifySsl() + { + _client = new InfluxDBClient("http://localhost:9999"); + + Assert.IsNotNull(_client); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual(true, options.VerifySsl); + } + + [Test] + [Obsolete("Obsolete")] + public void CreateInstanceVerifySslFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999"); @@ -46,6 +70,15 @@ public void CreateInstanceVerifySsl() [Test] public void CreateInstanceUsername() + { + _client = new InfluxDBClient("http://localhost:9999", "user", "secret"); + + Assert.IsNotNull(_client); + } + + [Test] + [Obsolete("Obsolete")] + public void CreateInstanceUsernameFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999", "user", "secret".ToCharArray()); @@ -54,6 +87,15 @@ public void CreateInstanceUsername() [Test] public void CreateInstanceToken() + { + _client = new InfluxDBClient("http://localhost:9999", "xyz"); + + Assert.IsNotNull(_client); + } + + [Test] + [Obsolete("Obsolete")] + public void CreateInstanceTokenFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999", "xyz"); @@ -62,6 +104,16 @@ public void CreateInstanceToken() [Test] public void CreateInstanceEmptyToken() + { + var empty = Assert.Throws(() => + new InfluxDBClient("http://localhost:9999?", "")); + Assert.NotNull(empty); + Assert.AreEqual("Expecting a non-empty string for token", empty.Message); + } + + [Test] + [Obsolete("Obsolete")] + public void CreateInstanceEmptyTokenFactory() { var empty = Assert.Throws(() => InfluxDBClientFactory.Create("http://localhost:9999?", "")); @@ -71,6 +123,26 @@ public void CreateInstanceEmptyToken() [Test] public void LoadFromConnectionString() + { + _client = new InfluxDBClient("http://localhost:9999?" + + "timeout=1000&logLevel=HEADERS&token=my-token&bucket=my-bucket&org=my-org&allowHttpRedirects=true"); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual("http://localhost:9999/", options.Url); + Assert.AreEqual("my-org", options.Org); + Assert.AreEqual("my-bucket", options.Bucket); + Assert.AreEqual("my-token".ToCharArray(), options.Token); + Assert.AreEqual(true, options.AllowHttpRedirects); + Assert.AreEqual(LogLevel.Headers, options.LogLevel); + Assert.AreEqual(LogLevel.Headers, _client.GetLogLevel()); + + var apiClient = GetDeclaredField(_client.GetType(), _client, "_apiClient"); + Assert.AreEqual(1_000, apiClient.RestClientOptions.MaxTimeout); + } + + [Test] + [Obsolete("Obsolete")] + public void LoadFromConnectionStringFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1000&logLevel=HEADERS&token=my-token&bucket=my-bucket&org=my-org&allowHttpRedirects=true"); @@ -90,6 +162,25 @@ public void LoadFromConnectionString() [Test] public void LoadFromConnectionStringUnitsMillisecondsSeconds() + { + _client = new InfluxDBClient("http://localhost:9999?" + + "timeout=1ms&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org"); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual("http://localhost:9999/", options.Url); + Assert.AreEqual("my-org", options.Org); + Assert.AreEqual("my-bucket", options.Bucket); + Assert.AreEqual("my-token".ToCharArray(), options.Token); + Assert.AreEqual(LogLevel.Headers, options.LogLevel); + Assert.AreEqual(LogLevel.Headers, _client.GetLogLevel()); + + var apiClient = GetDeclaredField(_client.GetType(), _client, "_apiClient"); + Assert.AreEqual(1, apiClient.RestClientOptions.MaxTimeout); + } + + [Test] + [Obsolete("Obsolete")] + public void LoadFromConnectionStringUnitsMillisecondsSecondsFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1ms&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org"); @@ -108,6 +199,25 @@ public void LoadFromConnectionStringUnitsMillisecondsSeconds() [Test] public void LoadFromConnectionStringUnitsMinutes() + { + _client = new InfluxDBClient("http://localhost:9999?" + + "timeout=1ms&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org"); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual("http://localhost:9999/", options.Url); + Assert.AreEqual("my-org", options.Org); + Assert.AreEqual("my-bucket", options.Bucket); + Assert.AreEqual("my-token".ToCharArray(), options.Token); + Assert.AreEqual(LogLevel.Headers, options.LogLevel); + Assert.AreEqual(LogLevel.Headers, _client.GetLogLevel()); + + var apiClient = GetDeclaredField(_client.GetType(), _client, "_apiClient"); + Assert.AreEqual(1, apiClient.RestClientOptions.MaxTimeout); + } + + [Test] + [Obsolete("Obsolete")] + public void LoadFromConnectionStringUnitsMinutesFactory() { _client = InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1ms&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org"); @@ -125,7 +235,19 @@ public void LoadFromConnectionStringUnitsMinutes() } [Test] + [Obsolete("Obsolete")] public void LoadFromConnectionNotValidDuration() + { + var ioe = Assert.Throws(() => new InfluxDBClient("http://localhost:9999?" + + "timeout=x&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org")); + + Assert.NotNull(ioe); + Assert.AreEqual("'x' is not a valid duration", ioe.Message); + } + + [Test] + [Obsolete("Obsolete")] + public void LoadFromConnectionNotValidDurationFactory() { var ioe = Assert.Throws(() => InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=x&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org")); @@ -136,6 +258,17 @@ public void LoadFromConnectionNotValidDuration() [Test] public void LoadFromConnectionUnknownUnit() + { + var ioe = Assert.Throws(() => new InfluxDBClient("http://localhost:9999?" + + "timeout=1y&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org")); + + Assert.NotNull(ioe); + Assert.AreEqual("unknown unit for '1y'", ioe.Message); + } + + [Test] + [Obsolete("Obsolete")] + public void LoadFromConnectionUnknownUnitFactory() { var ioe = Assert.Throws(() => InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1y&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org")); @@ -145,6 +278,7 @@ public void LoadFromConnectionUnknownUnit() } [Test] + [Obsolete("Obsolete")] public void LoadFromConfiguration() { CopyAppConfig(); @@ -171,6 +305,33 @@ public void LoadFromConfiguration() Assert.AreEqual("${SensorVersion}", defaultTags["version"]); } + [Test] + public void LoadFromConfigurationOptions() + { + CopyAppConfig(); + + _client = new InfluxDBClient(InfluxDBClientOptions.LoadConfig()); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual("http://localhost:9999/", options.Url); + Assert.AreEqual("my-org", options.Org); + Assert.AreEqual("my-bucket", options.Bucket); + Assert.AreEqual("my-token".ToCharArray(), options.Token); + Assert.AreEqual(LogLevel.Body, options.LogLevel); + Assert.AreEqual(LogLevel.Body, _client.GetLogLevel()); + + var apiClient = GetDeclaredField(_client.GetType(), _client, "_apiClient"); + Assert.AreEqual(10_000, apiClient.RestClientOptions.MaxTimeout); + + var defaultTags = GetDeclaredField>(options.PointSettings.GetType(), + options.PointSettings, "_defaultTags"); + + Assert.AreEqual(4, defaultTags.Count); + Assert.AreEqual("132-987-655", defaultTags["id"]); + Assert.AreEqual("California Miner", defaultTags["customer"]); + Assert.AreEqual("${SensorVersion}", defaultTags["version"]); + } + [Test] public void LoadFromConfigurationWithoutUrl() { @@ -197,6 +358,29 @@ public void LoadFromConfigurationNotExist() [Test] public void V1Configuration() + { + _client = new InfluxDBClient("http://localhost:8086", "my-username", + "my-password", "database", "week"); + + var options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual("http://localhost:8086/", options.Url); + Assert.AreEqual("-", options.Org); + Assert.AreEqual("database/week", options.Bucket); + Assert.AreEqual("my-username:my-password".ToCharArray(), options.Token); + + _client.Dispose(); + _client = new InfluxDBClient("http://localhost:8086", null, null, "database", null); + + options = GetDeclaredField(_client.GetType(), _client, "_options"); + Assert.AreEqual("http://localhost:8086/", options.Url); + Assert.AreEqual("-", options.Org); + Assert.AreEqual("database/", options.Bucket); + Assert.AreEqual(":".ToCharArray(), options.Token); + } + + [Test] + [Obsolete("Obsolete")] + public void V1ConfigurationFactory() { _client = InfluxDBClientFactory.CreateV1("http://localhost:8086", "my-username", "my-password".ToCharArray(), "database", "week"); @@ -219,6 +403,22 @@ public void V1Configuration() [Test] public void Timeout() + { + var options = new InfluxDBClientOptions("http://localhost:8086") + { + Token = "my-token", + Timeout = TimeSpan.FromSeconds(20) + }; + + _client = new InfluxDBClient(options); + + var apiClient = GetDeclaredField(_client.GetType(), _client, "_apiClient"); + Assert.AreEqual(20_000, apiClient.RestClientOptions.MaxTimeout); + } + + [Test] + [Obsolete("Obsolete")] + public void TimeoutFactory() { var options = new InfluxDBClientOptions.Builder() .Url("http://localhost:8086") @@ -234,6 +434,14 @@ public void Timeout() [Test] public void AnonymousSchema() + { + var options = new InfluxDBClientOptions("http://localhost:9999"); + Assert.AreEqual(InfluxDBClientOptions.AuthenticationScheme.Anonymous, options.AuthScheme); + } + + [Test] + [Obsolete("Obsolete")] + public void AnonymousSchemaFactory() { var options = new InfluxDBClientOptions.Builder() .Url("http://localhost:9999") @@ -272,6 +480,55 @@ public void Certificates() T6z0Vdk7uW9/wzv45vzjES8a8AAFvEkaRS4JBoTCW69mc8RFR89Vp9axRHY/3ohQ 8pS9K00FLMTObb8qlW31LfKpCUSxHmU00BhGPduMYQF28Xj02zQ5UaeGOnSO5EjU pG0N7yqaVwGv9jYQfmnnD7M5LYVweEZ3OzCbfZuNJ4+EHNdZKcJiu2TaOsyxK25q +AJvDAFTSr5A9GSjJ3OyIeKoI8Q6xuaQBitpZR90P/Ah/Ymg490rpXavk"; + + var certificateCollection = new X509CertificateCollection + { new X509Certificate2(Convert.FromBase64String(testingPem)) }; + + var options = new InfluxDBClientOptions("http://localhost:8086") + { + Token = "my-token", + ClientCertificates = certificateCollection + }; + + _client = new InfluxDBClient(options); + + var apiClient = GetDeclaredField(_client.GetType(), _client, "_apiClient"); + Assert.AreEqual(certificateCollection, apiClient.RestClientOptions.ClientCertificates); + } + + [Test] + [Obsolete("Obsolete")] + public void CertificatesFactory() + { + const string testingPem = @"MIIFZjCCA04CCQCMEn5e+4xmLTANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJV +UzEQMA4GA1UECAwHTmV3WW9yazEQMA4GA1UEBwwHTmV3WW9yazEdMBsGA1UECgwU +SW5mbHV4REJQeXRob25DbGllbnQxDzANBgNVBAsMBkNsaWVudDESMBAGA1UEAwwJ +bG9jYWxob3N0MB4XDTIwMDcyMDA2MzA0OVoXDTQ3MTIwNjA2MzA0OVowdTELMAkG +A1UEBhMCVVMxEDAOBgNVBAgMB05ld1lvcmsxEDAOBgNVBAcMB05ld1lvcmsxHTAb +BgNVBAoMFEluZmx1eERCUHl0aG9uQ2xpZW50MQ8wDQYDVQQLDAZDbGllbnQxEjAQ +BgNVBAMMCWxvY2FsaG9zdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB +AMoqURng8JwLYe4IHyIAGlI80utBLq6XbDETY93Pr6ZdHePr2jM+UIfFtdkpqdJw +56ZxnJPtM1kDQJTsGfkf0/ePKZpnunNk+lkz9l5uQPVcujydplhJgJeHEj49s3Yy +mWYetcR1Oejnqxgh+9Ev79r1Napu3s80SACPgvTP45CLp1hOGFySRaW7jcG3i+V4 +ljQWVAEse9Vy3e7E1EY2p6z/Zvj2UVOMqdHsivR1XLy5hts5ubIqOqvOCPocJ+0/ +m0AjwCXO4QPy7pLAAa7DA9rWDpzx8jpdfe54NOHuj4SVP45+PPsWvvkN2ZOkC/vb +zz4DcYVwIqtqej8mvO2kkPIFLdRSKUc5N3xmdvF5awBGfHhb4l/KIDlhRle+L9kF +LxRgkmBb2FFfL0/GtQlpH0bHHwPij4jPcOY+ueLKmAMgwWdqYae0HS01F7nYeZuP +StDG+YuCjglOH8xugcV9GBXrRTijyjuml4st3Wl4tPpQClmdoZ2LXp5h/6Zq1aoc +QlraKjwuTuzQBBHIFh9KXLZANLtMLpGGepFSMqE6YIWl17gi/2NruP8MGXNk+7GM +ylczKu/Ny67qQ8JCnRLSNUXPg18LjU2voLuzgXWtuTUgRnQBdir6ZB5Bwc2zi0vx +DNl0yzDhGNFdR5Rng5lAcmclA4QWi7Oc4h/OLN0ma0UzAgMBAAEwDQYJKoZIhvcN +AQELBQADggIBADsWOWIMvynE2Iwtpv471kROYdqrj6Zj5P8Ye5/0lqedRxIYWDsc +XDii+ePem+cMhnty8tAqCeHIdBUN86ibP+oqlwySbvdvW121RfedsWpa+TPC+Rnj +8n5w0urVNpnYuep2f8SOpQ1WdXFMLIsKqcnV5KK3/rxOAUY9cNVumA55/terQMOZ +RSGfjtoKVkMSOxNlaj4frLNy+I7nyWYrZ9UmUirvGLce5LJ1nrmo2I46FA0XDwu8 +xJqe4mB3GT/t9kFujd3Q/MtgD4J/MjWBfSYV0vlzI+VuoRctikw2SWQckQWNlIhs +LPafo6D+lOxJtH58WksCxdb8C8sBbRl+irv/ZAlvIiOkmcpHcOQ7AbLTtosZs6nX +p0ptWENlTM3lkt/Xma8txWXfe29tlf/9oheqXKdYunRyvFPL/gBjjR/VWzIS5sT5 +T6z0Vdk7uW9/wzv45vzjES8a8AAFvEkaRS4JBoTCW69mc8RFR89Vp9axRHY/3ohQ +8pS9K00FLMTObb8qlW31LfKpCUSxHmU00BhGPduMYQF28Xj02zQ5UaeGOnSO5EjU +pG0N7yqaVwGv9jYQfmnnD7M5LYVweEZ3OzCbfZuNJ4+EHNdZKcJiu2TaOsyxK25q AJvDAFTSr5A9GSjJ3OyIeKoI8Q6xuaQBitpZR90P/Ah/Ymg490rpXavk"; var certificateCollection = new X509CertificateCollection diff --git a/Client.Test/InfluxDbClientTest.cs b/Client.Test/InfluxDbClientTest.cs index 8e3a1725a..c2b5bfa8d 100644 --- a/Client.Test/InfluxDbClientTest.cs +++ b/Client.Test/InfluxDbClientTest.cs @@ -31,7 +31,7 @@ public class InfluxDbClientTest : AbstractMockServerTest [SetUp] public new void SetUp() { - _client = InfluxDBClientFactory.Create(MockServerUrl); + _client = new InfluxDBClient(MockServerUrl); } [Test] @@ -185,7 +185,7 @@ public void TrailingSlashInUrl() request.RequestMessage.AbsoluteUrl); _client.Dispose(); - _client = InfluxDBClientFactory.Create(MockServerUrl + "/"); + _client = new InfluxDBClient(MockServerUrl + "/"); using (var writeApi = _client.GetWriteApi()) { @@ -198,8 +198,10 @@ public void TrailingSlashInUrl() request.RequestMessage.AbsoluteUrl); _client.Dispose(); - _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder().Url(MockServerUrl) - .AuthenticateToken("my-token").Build()); + _client = new InfluxDBClient(new InfluxDBClientOptions(MockServerUrl) + { + Token = "my-token" + }); using (var writeApi = _client.GetWriteApi()) { @@ -212,8 +214,10 @@ public void TrailingSlashInUrl() request.RequestMessage.AbsoluteUrl); _client.Dispose(); - _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder().Url(MockServerUrl + "/") - .AuthenticateToken("my-token").Build()); + _client = new InfluxDBClient(new InfluxDBClientOptions(MockServerUrl + "/") + { + Token = "my-token" + }); using (var writeApi = _client.GetWriteApi()) { @@ -256,11 +260,11 @@ public void CreateService() public async Task RedirectToken() { _client.Dispose(); - _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder() - .Url(MockServerUrl) - .AuthenticateToken("my-token") - .AllowRedirects(true) - .Build()); + _client = new InfluxDBClient(new InfluxDBClientOptions(MockServerUrl) + { + Token = "my-token", + AllowHttpRedirects = true + }); var anotherServer = WireMockServer.Start(new WireMockServerSettings { @@ -292,11 +296,12 @@ public async Task RedirectToken() public async Task RedirectCookie() { _client.Dispose(); - _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder() - .Url(MockServerUrl) - .Authenticate("my-username", "my-password".ToCharArray()) - .AllowRedirects(true) - .Build()); + _client = new InfluxDBClient(new InfluxDBClientOptions(MockServerUrl) + { + Username = "my-username", + Password = "my-password", + AllowHttpRedirects = true + }); var anotherServer = WireMockServer.Start(new WireMockServerSettings { @@ -331,9 +336,7 @@ public async Task RedirectCookie() public async Task Anonymous() { _client.Dispose(); - _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder() - .Url(MockServerUrl) - .Build()); + _client = new InfluxDBClient(new InfluxDBClientOptions(MockServerUrl)); MockServer .Given(Request.Create().UsingGet()) @@ -385,10 +388,10 @@ public async Task CustomCertificateValidationCallback() var reached = false; _client.Dispose(); - _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder() - .Url(mockServerSsl.Urls[0]) - .RemoteCertificateValidationCallback((sender, certificate, chain, errors) => reached = true) - .Build()); + _client = new InfluxDBClient(new InfluxDBClientOptions(mockServerSsl.Urls[0]) + { + VerifySslCallback = (sender, certificate, chain, errors) => reached = true + }); mockServerSsl.Given(Request.Create().WithPath("/ping").UsingGet()) .RespondWith(Response.Create().WithStatusCode(204) @@ -422,7 +425,7 @@ public void TestMocking() public void RedactedAuthorizationHeader() { _client.Dispose(); - _client = InfluxDBClientFactory.Create(MockServerUrl, "my-token"); + _client = new InfluxDBClient(MockServerUrl, "my-token"); var writer = new StringWriter(); Trace.Listeners.Add(new TextWriterTraceListener(writer)); diff --git a/Client.Test/ItDeleteApiTest.cs b/Client.Test/ItDeleteApiTest.cs index 3888116cc..fcd19f988 100644 --- a/Client.Test/ItDeleteApiTest.cs +++ b/Client.Test/ItDeleteApiTest.cs @@ -41,9 +41,13 @@ public class ItDeleteApiTest : AbstractItClientTest _token = authorization.Token; Client.Dispose(); - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl).AuthenticateToken(_token) - .Org(_organization.Id).Bucket(_bucket.Id).Build(); - Client = InfluxDBClientFactory.Create(options); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = _token, + Org = _organization.Id, + Bucket = _bucket.Id + }; + Client = new InfluxDBClient(options); _queryApi = Client.GetQueryApi(); } @@ -127,15 +131,19 @@ private void WriteData() Environment.SetEnvironmentVariable("point-datacenter", "LA"); ConfigurationManager.AppSettings["point-sensor.version"] = "1.23a"; - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl) - .AuthenticateToken(_token) - .AddDefaultTag("id", "132-987-655") - .AddDefaultTag("customer", "California Miner") - .AddDefaultTag("env-var", "${env.point-datacenter}") - .AddDefaultTag("sensor-version", "${point-sensor.version}") - .Build(); - - Client = InfluxDBClientFactory.Create(options); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = _token, + DefaultTags = new Dictionary + { + { "id", "132-987-655" }, + { "customer", "California Miner" }, + { "env-var", "${env.point-datacenter}" }, + { "sensor-version", "${point-sensor.version}" } + } + }; + + Client = new InfluxDBClient(options); var point = PointData.Measurement("h2o_feet").Tag("location", "east").Field("water_level", 1); var point2 = PointData.Measurement("h2o_feet").Tag("location", "west").Field("water_level", 2); diff --git a/Client.Test/ItInfluxDBClientTest.cs b/Client.Test/ItInfluxDBClientTest.cs index 145c3d7bd..792251d40 100644 --- a/Client.Test/ItInfluxDBClientTest.cs +++ b/Client.Test/ItInfluxDBClientTest.cs @@ -11,6 +11,7 @@ namespace InfluxDB.Client.Test public class ItInfluxDBClientTest : AbstractItClientTest { [Test] + [Obsolete("Obsolete")] public async Task Health() { var health = await Client.HealthAsync(); @@ -22,9 +23,10 @@ public async Task Health() } [Test] + [Obsolete("Obsolete")] public async Task HealthNotRunningInstance() { - var clientNotRunning = InfluxDBClientFactory.Create("http://localhost:8099"); + var clientNotRunning = new InfluxDBClient("http://localhost:8099"); var health = await clientNotRunning.HealthAsync(); Assert.IsNotNull(health); @@ -45,7 +47,7 @@ public async Task Ping() [Test] public async Task PingNotRunningInstance() { - var clientNotRunning = InfluxDBClientFactory.Create("http://localhost:8099"); + var clientNotRunning = new InfluxDBClient("http://localhost:8099"); Assert.IsFalse(await clientNotRunning.PingAsync()); @@ -61,7 +63,7 @@ public async Task Version() [Test] public void VersionNotRunningInstance() { - var clientNotRunning = InfluxDBClientFactory.Create("http://localhost:8099"); + var clientNotRunning = new InfluxDBClient("http://localhost:8099"); var ex = Assert.ThrowsAsync(async () => await clientNotRunning.VersionAsync()); @@ -97,7 +99,7 @@ public async Task Onboarding() var url = $"http://{GetOrDefaultEnvironmentVariable("INFLUXDB_2_ONBOARDING_IP", "localhost")}:" + $"{GetOrDefaultEnvironmentVariable("INFLUXDB_2_ONBOARDING_PORT", "9990")}"; - using (var client = InfluxDBClientFactory.Create(url)) + using (var client = new InfluxDBClient(url)) { Assert.IsTrue(await client.IsOnboardingAllowedAsync()); } @@ -120,7 +122,7 @@ public async Task Onboarding() Assert.IsNotEmpty(onboarding.Auth.Id); Assert.IsNotEmpty(onboarding.Auth.Token); - using (var client = InfluxDBClientFactory.Create(url, onboarding.Auth.Token)) + using (var client = new InfluxDBClient(url, onboarding.Auth.Token)) { var user = await client.GetUsersApi().MeAsync(); @@ -164,7 +166,7 @@ public async Task Ready() [Test] public async Task ReadyNotRunningInstance() { - var clientNotRunning = InfluxDBClientFactory.Create("http://localhost:8099"); + var clientNotRunning = new InfluxDBClient("http://localhost:8099"); var ready = await clientNotRunning.ReadyAsync(); Assert.IsNull(ready); @@ -177,7 +179,7 @@ public async Task UseUsernamePassword() { Client.Dispose(); - Client = InfluxDBClientFactory.Create(InfluxDbUrl, "my-user", "my-password".ToCharArray()); + Client = new InfluxDBClient(InfluxDbUrl, "my-user", "my-password"); var measurement = $"mem_{DateTimeOffset.Now.ToUnixTimeSeconds()}"; await Client diff --git a/Client.Test/ItMonitoringAlertingTest.cs b/Client.Test/ItMonitoringAlertingTest.cs index 43cfca52d..a0d7773fc 100644 --- a/Client.Test/ItMonitoringAlertingTest.cs +++ b/Client.Test/ItMonitoringAlertingTest.cs @@ -21,7 +21,7 @@ public class ItMonitoringAlertingTest : AbstractMockServerTest [SetUp] public new void SetUp() { - _client = InfluxDBClientFactory.Create(GetInfluxDb2Url(), "my-token"); + _client = new InfluxDBClient(GetInfluxDb2Url(), "my-token"); } [TearDown] diff --git a/Client.Test/ItTasksApiTest.cs b/Client.Test/ItTasksApiTest.cs index d13422a9c..89412991f 100644 --- a/Client.Test/ItTasksApiTest.cs +++ b/Client.Test/ItTasksApiTest.cs @@ -21,7 +21,7 @@ public class ItTasksApiTest : AbstractItClientTest var authorization = await AddAuthorization(_organization); Client.Dispose(); - Client = InfluxDBClientFactory.Create(InfluxDbUrl, authorization.Token); + Client = new InfluxDBClient(InfluxDbUrl, authorization.Token); _tasksApi = Client.GetTasksApi(); @@ -297,7 +297,7 @@ public async Task FindTasksByOrganization() public async Task FindTasksByUser() { Client.Dispose(); - Client = InfluxDBClientFactory.Create(InfluxDbUrl, "my-user", "my-password".ToCharArray()); + Client = new InfluxDBClient(InfluxDbUrl, "my-user", "my-password"); _tasksApi = Client.GetTasksApi(); var user = (await Client.GetUsersApi().FindUsersAsync(name: "my-user"))[0]; diff --git a/Client.Test/ItWriteApiAsyncTest.cs b/Client.Test/ItWriteApiAsyncTest.cs index 77c222206..6cfb6323e 100644 --- a/Client.Test/ItWriteApiAsyncTest.cs +++ b/Client.Test/ItWriteApiAsyncTest.cs @@ -44,9 +44,13 @@ public class ItWriteApiAsyncTest : AbstractItClientTest _token = authorization.Token; Client.Dispose(); - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl).AuthenticateToken(_token) - .Org(_organization.Id).Bucket(_bucket.Id).Build(); - Client = InfluxDBClientFactory.Create(options); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = _token, + Org = _organization.Id, + Bucket = _bucket.Id + }; + Client = new InfluxDBClient(options); _writeApi = Client.GetWriteApiAsync(); } diff --git a/Client.Test/ItWriteApiRaceTest.cs b/Client.Test/ItWriteApiRaceTest.cs index a232ef0af..77444bc32 100644 --- a/Client.Test/ItWriteApiRaceTest.cs +++ b/Client.Test/ItWriteApiRaceTest.cs @@ -48,9 +48,13 @@ private async Task> CreateBuckets(int count = 1) .CreateAuthorizationAsync(await FindMyOrg(), permissions); Client.Dispose(); - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl).AuthenticateToken(authorization.Token) - .Org(organization.Id).Bucket(buckets[0].Id).Build(); - Client = InfluxDBClientFactory.Create(options); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = authorization.Token, + Org = organization.Id, + Bucket = buckets[0].Id + }; + Client = new InfluxDBClient(options); return buckets; } @@ -93,7 +97,7 @@ public async Task Race() [Test] public async Task BatchConsistency() { - var options = WriteOptions.CreateNew().BatchSize(1_555).FlushInterval(10_000).Build(); + var options = new WriteOptions { BatchSize = 1_555, FlushInterval = 10_000 }; var batches = new List(); await StressfulWriteAndValidate(1, 5, options, (sender, eventArgs) => @@ -127,7 +131,7 @@ public async Task MultipleBuckets() [Test] public async Task MultipleBucketsWithFlush() { - var writeOptions = WriteOptions.CreateNew().FlushInterval(100).Build(); + var writeOptions = new WriteOptions { FlushInterval = 100 }; await StressfulWriteAndValidate(writeOptions: writeOptions); } @@ -139,7 +143,7 @@ private async Task StressfulWriteAndValidate(int writerCount = 4, int secondsCou using var countdownEvent = new CountdownEvent(1); using var writeApi = Client - .GetWriteApi(writeOptions ?? WriteOptions.CreateNew().FlushInterval(20_000).Build()); + .GetWriteApi(writeOptions ?? new WriteOptions { FlushInterval = 20_000 }); writeApi.EventHandler += eventHandler; var writers = new List(); diff --git a/Client.Test/ItWriteManyMeasurements.cs b/Client.Test/ItWriteManyMeasurements.cs index 757814b75..b17c6e10b 100644 --- a/Client.Test/ItWriteManyMeasurements.cs +++ b/Client.Test/ItWriteManyMeasurements.cs @@ -41,9 +41,8 @@ public void SetUp() [Test] public async Task Write() { - var m_client = InfluxDBClientFactory.Create("http://localhost:9999", "my-token"); - var api = m_client.GetWriteApi(WriteOptions.CreateNew().BatchSize(MaxBarsPerRequest).FlushInterval(10_000) - .Build()); + var client = new InfluxDBClient("http://localhost:9999", "my-token"); + var api = client.GetWriteApi(new WriteOptions { BatchSize = MaxBarsPerRequest, FlushInterval = 10_000 }); var start = 0; for (;;) @@ -69,7 +68,7 @@ public async Task Write() Trace.WriteLine("Flushing data..."); - m_client.Dispose(); + client.Dispose(); Trace.WriteLine("Finished"); } diff --git a/Client.Test/ItWriteQueryApiTest.cs b/Client.Test/ItWriteQueryApiTest.cs index ebb10d1dd..56ec9e237 100644 --- a/Client.Test/ItWriteQueryApiTest.cs +++ b/Client.Test/ItWriteQueryApiTest.cs @@ -45,9 +45,13 @@ public class ItWriteQueryApiTest : AbstractItClientTest _token = authorization.Token; Client.Dispose(); - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl).AuthenticateToken(_token) - .Org(_organization.Id).Bucket(_bucket.Id).Build(); - Client = InfluxDBClientFactory.Create(options); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = _token, + Org = _organization.Id, + Bucket = _bucket.Id + }; + Client = new InfluxDBClient(options); _queryApi = Client.GetQueryApi(); } @@ -85,7 +89,7 @@ public async Task DefaultTagsConfiguration() .AuthenticateToken(_token) .Build(); - Client = InfluxDBClientFactory.Create(options); + Client = new InfluxDBClient(options); var measurement1 = new H20Measurement { @@ -122,15 +126,19 @@ public async Task DefaultTagsMeasurement() Environment.SetEnvironmentVariable("measurement-datacenter", "LA"); ConfigurationManager.AppSettings["measurement-sensor.version"] = "1.23a"; - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl) - .AuthenticateToken(_token) - .AddDefaultTag("id", "132-987-655") - .AddDefaultTag("customer", "California Miner") - .AddDefaultTag("env-var", "${env.measurement-datacenter}") - .AddDefaultTag("sensor-version", "${measurement-sensor.version}") - .Build(); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = _token, + DefaultTags = new Dictionary + { + { "id", "132-987-655" }, + { "customer", "California Miner" }, + { "env-var", "${env.measurement-datacenter}" }, + { "sensor-version", "${measurement-sensor.version}" } + } + }; - Client = InfluxDBClientFactory.Create(options); + Client = new InfluxDBClient(options); var measurement1 = new H20Measurement { @@ -168,15 +176,19 @@ public async Task DefaultTagsPoint() Environment.SetEnvironmentVariable("point-datacenter", "LA"); ConfigurationManager.AppSettings["point-sensor.version"] = "1.23a"; - var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl) - .AuthenticateToken(_token) - .AddDefaultTag("id", "132-987-655") - .AddDefaultTag("customer", "California Miner") - .AddDefaultTag("env-var", "${env.point-datacenter}") - .AddDefaultTag("sensor-version", "${point-sensor.version}") - .Build(); + var options = new InfluxDBClientOptions(InfluxDbUrl) + { + Token = _token, + DefaultTags = new Dictionary + { + { "id", "132-987-655" }, + { "customer", "California Miner" }, + { "env-var", "${env.point-datacenter}" }, + { "sensor-version", "${point-sensor.version}" } + } + }; - Client = InfluxDBClientFactory.Create(options); + Client = new InfluxDBClient(options); var point = PointData.Measurement("h2o_feet").Tag("location", "west").Field("water_level", 1); @@ -244,7 +256,7 @@ public async Task Flush() { var bucketName = _bucket.Name; - var writeOptions = WriteOptions.CreateNew().BatchSize(10).FlushInterval(100_000).Build(); + var writeOptions = new WriteOptions { BatchSize = 10, FlushInterval = 100_000 }; _writeApi = Client.GetWriteApi(writeOptions); var listener = new WriteApiTest.EventListener(_writeApi); @@ -276,7 +288,7 @@ public async Task FlushByCount() { var bucketName = _bucket.Name; - var writeOptions = WriteOptions.CreateNew().BatchSize(6).FlushInterval(500_000).Build(); + var writeOptions = new WriteOptions { BatchSize = 6, FlushInterval = 500_000 }; _writeApi = Client.GetWriteApi(writeOptions); @@ -318,7 +330,7 @@ public async Task FlushByOne() { var bucketName = _bucket.Name; - var writeOptions = WriteOptions.CreateNew().BatchSize(1).FlushInterval(500_000).Build(); + var writeOptions = new WriteOptions { BatchSize = 1, FlushInterval = 500_000 }; _writeApi = Client.GetWriteApi(writeOptions); @@ -362,7 +374,7 @@ public async Task FlushByTime() { var bucketName = _bucket.Name; - var writeOptions = WriteOptions.CreateNew().BatchSize(10).FlushInterval(500).Build(); + var writeOptions = new WriteOptions { BatchSize = 10, FlushInterval = 500 }; _writeApi = Client.GetWriteApi(writeOptions); var listener = new WriteApiTest.EventListener(_writeApi); @@ -400,7 +412,7 @@ public async Task Jitter() { var bucketName = _bucket.Name; - var writeOptions = WriteOptions.CreateNew().BatchSize(1).JitterInterval(5_000).Build(); + var writeOptions = new WriteOptions { BatchSize = 1, JitterInterval = 5_000 }; _writeApi = Client.GetWriteApi(writeOptions); @@ -468,7 +480,7 @@ public async Task PartialWrite() { var bucketName = _bucket.Name; - _writeApi = Client.GetWriteApi(WriteOptions.CreateNew().BatchSize(2).Build()); + _writeApi = Client.GetWriteApi(new WriteOptions { BatchSize = 2 }); const string records = "h2o_feet,location=coyote_creek level\\ water_level=1.0 1\n" + "h2o_feet,location=coyote_hill level\\ water_level=2.0 2x"; @@ -488,7 +500,7 @@ public async Task SimpleWriteAndDisposing() { // Using WriteApi { - var client = InfluxDBClientFactory.Create(InfluxDbUrl, _token); + var client = new InfluxDBClient(InfluxDbUrl, _token); using (var writeApi = client.GetWriteApi()) { @@ -501,19 +513,15 @@ public async Task SimpleWriteAndDisposing() // Using both { - using (var client = InfluxDBClientFactory.Create(InfluxDbUrl, _token)) - { - using (var writeApi = client.GetWriteApi()) - { - writeApi.WriteRecord("temperature,location=north value=70.0 2", WritePrecision.Ns, _bucket.Name, - _organization.Id); - } - } + using var client = new InfluxDBClient(InfluxDbUrl, _token); + using var writeApi = client.GetWriteApi(); + writeApi.WriteRecord("temperature,location=north value=70.0 2", WritePrecision.Ns, _bucket.Name, + _organization.Id); } // Using without { - var client = InfluxDBClientFactory.Create(InfluxDbUrl, _token); + var client = new InfluxDBClient(InfluxDbUrl, _token); var writeApi = client.GetWriteApi(); writeApi.WriteRecord("temperature,location=north value=80.0 3", WritePrecision.Ns, _bucket.Name, @@ -888,7 +896,7 @@ public async Task WriteTooManyData() { Level = i, Time = DateTime.UnixEpoch.Add(TimeSpan.FromSeconds(i)), Location = "Europe" }); var successEvents = new List(); - _writeApi = Client.GetWriteApi(WriteOptions.CreateNew().BatchSize(batchSize).FlushInterval(10_000).Build()); + _writeApi = Client.GetWriteApi(new WriteOptions { BatchSize = batchSize, FlushInterval = 10_000 }); _writeApi.EventHandler += (sender, args) => { successEvents.Add(args as WriteSuccessEvent); }; var start = 0; diff --git a/Client.Test/QueryApiSyncTest.cs b/Client.Test/QueryApiSyncTest.cs index 3cf02143c..7a4fbf4f3 100644 --- a/Client.Test/QueryApiSyncTest.cs +++ b/Client.Test/QueryApiSyncTest.cs @@ -9,7 +9,7 @@ namespace InfluxDB.Client.Test [TestFixture] public class QueryApiSyncTest : AbstractMockServerTest { - private InfluxDBClient _influxDbClient; + private InfluxDBClient _client; private QueryApiSync _queryApiSync; private const string Data = @@ -23,21 +23,20 @@ public class QueryApiSyncTest : AbstractMockServerTest [SetUp] public new void SetUp() { - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Org("my-org") - .Build(); - - _influxDbClient = InfluxDBClientFactory.Create(options); - _queryApiSync = _influxDbClient.GetQueryApiSync(); + var options = new InfluxDBClientOptions(MockServerUrl) + { + Token = "token", + Org = "my-org" + }; + + _client = new InfluxDBClient(options); + _queryApiSync = _client.GetQueryApiSync(); } [TearDown] public void TearDown() { - _influxDbClient?.Dispose(); + _client?.Dispose(); } [Test] @@ -72,16 +71,12 @@ public void FluxTable() [Test] public void RequiredOrgQuerySync() { - _influxDbClient.Dispose(); + _client.Dispose(); - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Build(); + var options = new InfluxDBClientOptions(MockServerUrl) { Token = "token" }; - _influxDbClient = InfluxDBClientFactory.Create(options); - _queryApiSync = _influxDbClient.GetQueryApiSync(); + _client = new InfluxDBClient(options); + _queryApiSync = _client.GetQueryApiSync(); var ae = Assert.Throws(() => _queryApiSync.QuerySync("from(...")); diff --git a/Client.Test/QueryApiTest.cs b/Client.Test/QueryApiTest.cs index 91ad4f74d..ec3cc5417 100644 --- a/Client.Test/QueryApiTest.cs +++ b/Client.Test/QueryApiTest.cs @@ -16,7 +16,7 @@ namespace InfluxDB.Client.Test [TestFixture] public class QueryApiTest : AbstractMockServerTest { - private InfluxDBClient _influxDbClient; + private InfluxDBClient _client; private QueryApi _queryApi; private const string Data = @@ -30,21 +30,16 @@ public class QueryApiTest : AbstractMockServerTest [SetUp] public new void SetUp() { - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Org("my-org") - .Build(); - - _influxDbClient = InfluxDBClientFactory.Create(options); - _queryApi = _influxDbClient.GetQueryApi(); + var options = new InfluxDBClientOptions(MockServerUrl) { Token = "token", Org = "my-org" }; + + _client = new InfluxDBClient(options); + _queryApi = _client.GetQueryApi(); } [TearDown] public void TearDown() { - _influxDbClient?.Dispose(); + _client?.Dispose(); } [Test] @@ -108,16 +103,12 @@ public async Task QueryAsyncEnumerable() [Test] public void RequiredOrgQueryAsync() { - _influxDbClient.Dispose(); + _client.Dispose(); - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Build(); + var options = new InfluxDBClientOptions(MockServerUrl) { Token = "token" }; - _influxDbClient = InfluxDBClientFactory.Create(options); - _queryApi = _influxDbClient.GetQueryApi(); + _client = new InfluxDBClient(options); + _queryApi = _client.GetQueryApi(); var ae = Assert.ThrowsAsync(async () => await _queryApi.QueryAsync("from(...")); @@ -134,7 +125,7 @@ public async Task LoggedContentType() var writer = new StringWriter(); Trace.Listeners.Add(new TextWriterTraceListener(writer)); - _influxDbClient.SetLogLevel(LogLevel.Headers); + _client.SetLogLevel(LogLevel.Headers); MockServer .Given(Request.Create().WithPath("/api/v2/query").UsingPost()) diff --git a/Client.Test/RetryAttemptTest.cs b/Client.Test/RetryAttemptTest.cs index e17eaeb84..1e85f614f 100644 --- a/Client.Test/RetryAttemptTest.cs +++ b/Client.Test/RetryAttemptTest.cs @@ -11,7 +11,7 @@ namespace InfluxDB.Client.Test [TestFixture] public class RetryAttemptTest { - private readonly WriteOptions _default = WriteOptions.CreateNew().Build(); + private readonly WriteOptions _default = new WriteOptions(); [Test] public void ErrorType() @@ -49,7 +49,7 @@ public void RetryableHttpErrorCodes() [Test] public void MaxRetries() { - var options = WriteOptions.CreateNew().MaxRetries(5).Build(); + var options = new WriteOptions { MaxRetries = 5 }; var retry = new RetryAttempt(new HttpException("", 429), 1, _default); Assert.IsTrue(retry.IsRetry()); @@ -86,12 +86,13 @@ public void HeaderHasPriority() [Test] public void ExponentialBase() { - var options = WriteOptions.CreateNew() - .RetryInterval(5_000) - .ExponentialBase(5) - .MaxRetries(4) - .MaxRetryDelay(int.MaxValue) - .Build(); + var options = new WriteOptions + { + RetryInterval = 5_000, + ExponentialBase = 5, + MaxRetries = 4, + MaxRetryDelay = int.MaxValue + }; var retry = new RetryAttempt(new HttpException("", 429), 1, options); var retryInterval = retry.GetRetryInterval(); @@ -137,12 +138,13 @@ public void ExponentialBase() [Test] public void MaxRetryDelay() { - var options = WriteOptions.CreateNew() - .RetryInterval(2_000) - .ExponentialBase(2) - .MaxRetries(10) - .MaxRetryDelay(50_000) - .Build(); + var options = new WriteOptions + { + RetryInterval = 2_000, + ExponentialBase = 2, + MaxRetries = 10, + MaxRetryDelay = 50_000 + }; var retry = new RetryAttempt(new HttpException("", 429), 1, options); Assert.GreaterOrEqual(retry.GetRetryInterval(), 2_000); diff --git a/Client.Test/WriteApiAsyncTest.cs b/Client.Test/WriteApiAsyncTest.cs index 47f3dc9d4..76a8a16f6 100644 --- a/Client.Test/WriteApiAsyncTest.cs +++ b/Client.Test/WriteApiAsyncTest.cs @@ -16,18 +16,18 @@ namespace InfluxDB.Client.Test [TestFixture] public class WriteApiAsyncTest : AbstractMockServerTest { - private InfluxDBClient _influxDbClient; + private InfluxDBClient _client; [SetUp] public new void SetUp() { - _influxDbClient = InfluxDBClientFactory.Create(MockServerUrl, "token"); + _client = new InfluxDBClient(MockServerUrl, "token"); } [TearDown] public new void ResetServer() { - _influxDbClient.Dispose(); + _client.Dispose(); } [Test] @@ -37,7 +37,7 @@ public async Task GroupPointsByPrecisionSame() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); await writeApi.WritePointsAsync(new List { PointData.Measurement("h2o").Tag("location", "coyote_creek").Field("water_level", 9.0D) @@ -62,7 +62,7 @@ public async Task GroupPointsByPrecisionDifferent() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); await writeApi.WritePointsAsync(new List { PointData.Measurement("h2o").Tag("location", "coyote_creek").Field("water_level", 9.0D) @@ -93,7 +93,7 @@ public async Task SplitPointList() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); var points = new List { @@ -141,7 +141,7 @@ public async Task WriteRecordsWithIRestResponse() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); var response = await writeApi.WriteRecordsAsyncWithIRestResponse( new[] { "h2o,location=coyote_creek water_level=9 1" }, WritePrecision.Ms, "my-bucket", "my-org"); @@ -160,7 +160,7 @@ public async Task WritePointsWithIRestResponse() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); var responses = await writeApi.WritePointsAsyncWithIRestResponse( new[] { @@ -190,7 +190,7 @@ public async Task WriteMeasurementsWithIRestResponse() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); var response = await writeApi.WriteMeasurementsAsyncWithIRestResponse( new[] { @@ -211,16 +211,12 @@ public async Task WriteMeasurementsWithIRestResponse() [Test] public void RequiredOrgBucketWriteApiAsync() { - _influxDbClient.Dispose(); + _client.Dispose(); - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Build(); + var options = new InfluxDBClientOptions(MockServerUrl) { Token = "token" }; - _influxDbClient = InfluxDBClientFactory.Create(options); - var writeApi = _influxDbClient.GetWriteApiAsync(); + _client = new InfluxDBClient(options); + var writeApi = _client.GetWriteApiAsync(); var ae = Assert.ThrowsAsync(async () => await writeApi.WriteRecordAsync( @@ -246,19 +242,18 @@ public async Task UseDefaultOrganizationAndBucket() .Given(Request.Create().WithPath("/api/v2/write").UsingPost()) .RespondWith(CreateResponse("{}")); - _influxDbClient.Dispose(); + _client.Dispose(); - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Bucket("my-bucket") - .Org("my-org") - .Build(); + var options = new InfluxDBClientOptions(MockServerUrl) + { + Token = "token", + Bucket = "my-bucket", + Org = "my-org" + }; - _influxDbClient = InfluxDBClientFactory.Create(options); + _client = new InfluxDBClient(options); - var writeApi = _influxDbClient.GetWriteApiAsync(); + var writeApi = _client.GetWriteApiAsync(); await writeApi.WriteRecordsAsyncWithIRestResponse(new[] { "mem,location=a level=1.0 1" }); await writeApi.WritePointsAsyncWithIRestResponse(new[] { PointData.Measurement("h2o").Field("water_level", 9.0D) }); diff --git a/Client.Test/WriteApiTest.cs b/Client.Test/WriteApiTest.cs index cd9014943..71a44fb45 100644 --- a/Client.Test/WriteApiTest.cs +++ b/Client.Test/WriteApiTest.cs @@ -21,19 +21,19 @@ public class WriteApiTest : AbstractMockServerTest [SetUp] public new void SetUp() { - _influxDbClient = InfluxDBClientFactory.Create(MockServerUrl, "token"); - _writeApi = _influxDbClient.GetWriteApi(WriteOptions.CreateNew().RetryInterval(1_000).Build()); + _client = new InfluxDBClient(MockServerUrl, "token"); + _writeApi = _client.GetWriteApi(new WriteOptions { RetryInterval = 1_000 }); } [TearDown] public new void ResetServer() { - _influxDbClient.Dispose(); + _client.Dispose(); _writeApi.Dispose(); } private WriteApi _writeApi; - private InfluxDBClient _influxDbClient; + private InfluxDBClient _client; private IResponseBuilder CreateResponse(string error, int status) { @@ -101,23 +101,23 @@ internal EventListener WaitToSuccess() [Test] public void DisposeCallFromInfluxDbClientToWriteApi() { - var writeApi = _influxDbClient.GetWriteApi(); + var writeApi = _client.GetWriteApi(); Assert.False(writeApi.Disposed); - _influxDbClient.Dispose(); + _client.Dispose(); Assert.True(writeApi.Disposed); } [Test] public void DisposedClientRemovedFromApis() { - var writeApi = _influxDbClient.GetWriteApi(); + var writeApi = _client.GetWriteApi(); Assert.False(writeApi.Disposed); writeApi.Dispose(); Assert.True(writeApi.Disposed); - _influxDbClient.Dispose(); + _client.Dispose(); // nothing bad happens } @@ -306,12 +306,14 @@ public void RetryOnNetworkError() MockServer.Stop(); _writeApi.Dispose(); - var options = WriteOptions.CreateNew() - .BatchSize(1) - .MaxRetryDelay(2_000) - .MaxRetries(3) - .Build(); - _writeApi = _influxDbClient.GetWriteApi(options); + var options = new WriteOptions + { + BatchSize = 1, + MaxRetryDelay = 2_000, + MaxRetries = 3 + }; + + _writeApi = _client.GetWriteApi(options); var listener = new EventListener(_writeApi); @@ -352,12 +354,14 @@ public void RetryContainsMessage() .WillSetStateTo("RetryWithRetryAfter Finished") .RespondWith(CreateResponse("{}")); - var options = WriteOptions.CreateNew() - .BatchSize(1) - .RetryInterval(100) - .MaxRetries(1) - .Build(); - _writeApi = _influxDbClient.GetWriteApi(options); + var options = new WriteOptions + { + BatchSize = 1, + RetryInterval = 100, + MaxRetries = 1 + }; + + _writeApi = _client.GetWriteApi(options); var listener = new EventListener(_writeApi); @@ -382,8 +386,8 @@ public void TwiceDispose() _writeApi.Dispose(); _writeApi.Dispose(); - _influxDbClient.Dispose(); - _influxDbClient.Dispose(); + _client.Dispose(); + _client.Dispose(); } [Test] @@ -421,7 +425,8 @@ public void UserAgentHeader() } [Test] - public void WriteOptionsDefaults() + [Obsolete("Obsolete")] + public void WriteOptionsDefaultsBuilder() { var options = WriteOptions.CreateNew().Build(); @@ -432,7 +437,19 @@ public void WriteOptionsDefaults() } [Test] - public void WriteOptionsCustom() + public void WriteOptionsDefaults() + { + var options = new WriteOptions(); + + Assert.AreEqual(5_000, options.RetryInterval); + Assert.AreEqual(5, options.MaxRetries); + Assert.AreEqual(125_000, options.MaxRetryDelay); + Assert.AreEqual(2, options.ExponentialBase); + } + + [Test] + [Obsolete("Obsolete")] + public void WriteOptionsCustomBuilder() { var options = WriteOptions.CreateNew() .RetryInterval(1_250) @@ -447,6 +464,23 @@ public void WriteOptionsCustom() Assert.AreEqual(2, options.ExponentialBase); } + [Test] + public void WriteOptionsCustom() + { + var options = new WriteOptions + { + RetryInterval = 1_250, + MaxRetries = 25, + MaxRetryDelay = 1_800_000, + ExponentialBase = 2 + }; + + Assert.AreEqual(1_250, options.RetryInterval); + Assert.AreEqual(25, options.MaxRetries); + Assert.AreEqual(1_800_000, options.MaxRetryDelay); + Assert.AreEqual(2, options.ExponentialBase); + } + [Test] public void WriteRuntimeException() { @@ -475,16 +509,12 @@ public void WriteRuntimeException() [Test] public void RequiredOrgBucketWriteApi() { - _influxDbClient.Dispose(); + _client.Dispose(); - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(MockServerUrl) - .AuthenticateToken("token") - .Build(); + var options = new InfluxDBClientOptions(MockServerUrl) { Token = "token" }; - _influxDbClient = InfluxDBClientFactory.Create(options); - _writeApi = _influxDbClient.GetWriteApi(WriteOptions.CreateNew().RetryInterval(1_000).Build()); + _client = new InfluxDBClient(options); + _writeApi = _client.GetWriteApi(new WriteOptions { RetryInterval = 1_000 }); var ae = Assert.Throws(() => _writeApi.WriteRecord("h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1", @@ -539,7 +569,7 @@ public void WritesToDifferentBuckets() public void WritesToDifferentBucketsJitter() { _writeApi.Dispose(); - _writeApi = _influxDbClient.GetWriteApi(WriteOptions.CreateNew().JitterInterval(1_000).Build()); + _writeApi = _client.GetWriteApi(new WriteOptions { JitterInterval = 1_000 }); var listener = new EventListener(_writeApi); diff --git a/Client/InfluxDBClient.cs b/Client/InfluxDBClient.cs index 9069f1ce3..d990b15bc 100644 --- a/Client/InfluxDBClient.cs +++ b/Client/InfluxDBClient.cs @@ -233,7 +233,86 @@ public class InfluxDBClient : AbstractRestClient, IInfluxDBClient private readonly Subject _disposeNotification = new Subject(); - protected internal InfluxDBClient(InfluxDBClientOptions options) + /// + /// Create a instance of the InfluxDB 2.x client. The url could be a connection string with various configurations. + /// + /// e.g.: "http://localhost:8086?timeout=5000&logLevel=BASIC + /// The following options are supported: + /// + /// org - default destination organization for writes and queries + /// bucket - default destination bucket for writes + /// token - the token to use for the authorization + /// logLevel (default - NONE) - rest client verbosity level + /// timeout (default - 10000) - The timespan to wait before the HTTP request times out in milliseconds + /// allowHttpRedirects (default - false) - Configure automatically following HTTP 3xx redirects + /// verifySsl (default - true) - Ignore Certificate Validation Errors when false + /// + /// Options for logLevel: + /// + /// Basic - Logs request and response lines. + /// Body - Logs request and response lines including headers and body (if present). Note that applying the `Body` LogLevel will disable chunking while streaming and will load the whole response into memory. + /// Headers - Logs request and response lines including headers. + /// None - Disable logging. + /// + /// + /// + /// connection string with various configurations + public InfluxDBClient(string url) : + this(new InfluxDBClientOptions(url)) + { + } + + /// + /// Create a instance of the InfluxDB 2.x client. + /// + /// the url to connect to the InfluxDB 2.x + /// the username to use in the basic auth + /// the password to use in the basic auth + public InfluxDBClient(string url, string username, string password) : + this(new InfluxDBClientOptions(url) + { + Username = username, + Password = password + }) + { + } + + /// + /// Create a instance of the InfluxDB 2.x client. + /// + /// the url to connect to the InfluxDB 2.x + /// the token to use for the authorization + public InfluxDBClient(string url, string token) : + this(new InfluxDBClientOptions(url) + { + Token = token + }) + { + } + + /// + /// Create a instance of the InfluxDB 2.x client to connect into InfluxDB 1.8. + /// + /// the url to connect to the InfluxDB 1.8 + /// authorization username + /// authorization password + /// database name + /// retention policy + public InfluxDBClient(string url, string username, string password, string database, string retentionPolicy) : + this(new InfluxDBClientOptions(url) + { + Org = "-", + Token = $"{username}:{password}", + Bucket = $"{database}/{retentionPolicy}" + }) + { + } + + /// + /// Create a instance of the InfluxDB 2.x client. + /// + /// the connection configuration + public InfluxDBClient(InfluxDBClientOptions options) { Arguments.CheckNotNull(options, nameof(options)); @@ -357,7 +436,7 @@ IWriteApi IInfluxDBClient.GetWriteApi(IDomainObjectMapper mapper) /// the new client instance for the Write API public WriteApi GetWriteApi(IDomainObjectMapper mapper = null) { - return GetWriteApi(WriteOptions.CreateNew().Build(), mapper); + return GetWriteApi(new WriteOptions(), mapper); } /// diff --git a/Client/InfluxDBClientFactory.cs b/Client/InfluxDBClientFactory.cs index a70125895..e8bb6081b 100644 --- a/Client/InfluxDBClientFactory.cs +++ b/Client/InfluxDBClientFactory.cs @@ -1,3 +1,4 @@ +using System; using System.Threading.Tasks; using InfluxDB.Client.Api.Domain; using InfluxDB.Client.Core; @@ -10,6 +11,10 @@ public static class InfluxDBClientFactory /// Create a instance of the InfluxDB 2.x client that is configured via App.config. /// /// client + /// Deprecated - please use use object initializer + /// together with + /// + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient Create() { var options = InfluxDBClientOptions.Builder @@ -28,6 +33,8 @@ public static InfluxDBClient Create() /// /// connection string with various configurations /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient Create(string connectionString) { var options = InfluxDBClientOptions.Builder @@ -45,6 +52,8 @@ public static InfluxDBClient Create(string connectionString) /// the username to use in the basic auth /// the password to use in the basic auth /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient Create(string url, string username, char[] password) { var options = InfluxDBClientOptions.Builder @@ -62,6 +71,8 @@ public static InfluxDBClient Create(string url, string username, char[] password /// the url to connect to the InfluxDB 2.x /// the token to use for the authorization /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient Create(string url, char[] token) { var options = InfluxDBClientOptions.Builder @@ -79,6 +90,8 @@ public static InfluxDBClient Create(string url, char[] token) /// the url to connect to the InfluxDB 2.x /// the token to use for the authorization /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient Create(string url, string token) { var options = InfluxDBClientOptions.Builder @@ -99,6 +112,8 @@ public static InfluxDBClient Create(string url, string token) /// database name /// retention policy /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient CreateV1(string url, string username, char[] password, string database, string retentionPolicy) { @@ -120,6 +135,8 @@ public static InfluxDBClient CreateV1(string url, string username, char[] passwo /// /// the connection configuration /// client + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'InfluxDBClient' initializer instead.", false)] public static InfluxDBClient Create(InfluxDBClientOptions options) { Arguments.CheckNotNull(options, nameof(options)); @@ -162,11 +179,8 @@ public static async Task Onboarding(string url, OnboardingRe Arguments.CheckNonEmptyString(url, nameof(url)); Arguments.CheckNotNull(onboarding, nameof(onboarding)); - - using (var client = new InfluxDBClient(InfluxDBClientOptions.Builder.CreateNew().Url(url).Build())) - { - return await client.OnboardingAsync(onboarding).ConfigureAwait(false); - } + using var client = new InfluxDBClient(new InfluxDBClientOptions(url)); + return await client.OnboardingAsync(onboarding).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/Client/InfluxDBClientOptions.cs b/Client/InfluxDBClientOptions.cs index 9a79142ce..539e2d986 100644 --- a/Client/InfluxDBClientOptions.cs +++ b/Client/InfluxDBClientOptions.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Configuration; using System.Net; using System.Net.Security; @@ -23,29 +24,373 @@ public class InfluxDBClientOptions RegexOptions.CultureInvariant | RegexOptions.RightToLeft); - public string Url { get; } - public LogLevel LogLevel { get; } + private string _token; + private string _url; + private TimeSpan _timeout; + private LogLevel _logLevel; + private string _username; + private string _password; + private IWebProxy _webProxy; + private bool _allowHttpRedirects; + private bool _verifySsl; + private X509CertificateCollection _clientCertificates; - public AuthenticationScheme AuthScheme { get; } - public char[] Token { get; } - public string Username { get; } - public char[] Password { get; } + /// + /// Set the url to connect the InfluxDB. + /// + public string Url + { + get => _url; + private set + { + Arguments.CheckNonEmptyString(value, "Url"); + _url = value; + } + } + + /// + /// Set the timespan to wait before the HTTP request times out. + /// + public TimeSpan Timeout + { + get => _timeout; + set + { + Arguments.CheckNotNull(value, "Timeout"); + _timeout = value; + } + } + + /// + /// Set the log level for the request and response information. + /// + /// Basic - Logs request and response lines. + /// Body - Logs request and response lines including headers and body (if present). Note that applying the `Body` LogLevel will disable chunking while streaming and will load the whole response into memory. + /// Headers - Logs request and response lines including headers. + /// None - Disable logging. + /// + /// + public LogLevel LogLevel + { + get => _logLevel; + set + { + Arguments.CheckNotNull(value, "LogLevel"); + _logLevel = value; + } + } + + /// + /// The scheme uses to Authentication. + /// + public AuthenticationScheme AuthScheme { get; private set; } + + /// + /// Setup authorization by . + /// + public string Token + { + get => _token; + set + { + _token = value; + Arguments.CheckNonEmptyString(_token, "token"); - public string Org { get; } - public string Bucket { get; } + AuthScheme = AuthenticationScheme.Token; + } + } - public TimeSpan Timeout { get; } + /// + /// Setup authorization by . + /// + public string Username + { + get => _username; + set + { + Arguments.CheckNonEmptyString(value, "Username"); + _username = value; - public IWebProxy WebProxy { get; } - public bool AllowHttpRedirects { get; } + if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(Password)) + { + AuthScheme = AuthenticationScheme.Session; + } + } + } + + /// + /// Setup authorization by . + /// + public string Password + { + get => _password; + set + { + Arguments.CheckNotNull(value, "Password"); + _password = value; + + if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(_password)) + { + AuthScheme = AuthenticationScheme.Session; + } + } + } + /// + /// Specify the default destination organization for writes and queries. + /// + public string Org { get; set; } + + /// + /// Specify the default destination bucket for writes. + /// + public string Bucket { get; set; } + + /// + /// Specify the WebProxy instance to use by the WebRequest to connect to external InfluxDB. + /// + public IWebProxy WebProxy + { + get => _webProxy; + set + { + Arguments.CheckNotNull(value, "WebProxy"); + _webProxy = value; + } + } + + /// + /// Configure automatically following HTTP 3xx redirects. + /// + public bool AllowHttpRedirects + { + get => _allowHttpRedirects; + set + { + Arguments.CheckNotNull(value, "AllowHttpRedirects"); + _allowHttpRedirects = value; + } + } + + /// + /// Ignore Certificate Validation Errors when `false`. + /// + public bool VerifySsl + { + get => _verifySsl; + set + { + Arguments.CheckNotNull(value, "VerifySsl"); + _verifySsl = value; + } + } + + /// + /// Callback function for handling the remote SSL Certificate Validation. + /// The callback takes precedence over `VerifySsl`. + /// + public RemoteCertificateValidationCallback VerifySslCallback { get; set; } + + /// + /// Set X509CertificateCollection to be sent with HTTP requests + /// + public X509CertificateCollection ClientCertificates + { + get => _clientCertificates; + set + { + Arguments.CheckNotNull(value, "ClientCertificates"); + _clientCertificates = value; + } + } + + /// + /// The setting for store data point: default values, threshold, ... + /// public PointSettings PointSettings { get; } - public bool VerifySsl { get; } + /// + /// Default tags that will be use for writes by Point and POJO. + /// + public Dictionary DefaultTags + { + get => PointSettings.DefaultTags; + set => PointSettings.DefaultTags = value; + } + + /// + /// Add default tag that will be use for writes by Point and POJO. + /// + /// The expressions can be: + /// + /// "California Miner" - static value + /// "${version}" - application settings + /// "${env.hostname}" - environment property + /// + /// + /// + /// the tag name + /// the tag value expression + public void AddDefaultTag(string tagName, string expression) + { + Arguments.CheckNotNull(tagName, nameof(tagName)); + PointSettings.AddDefaultTag(tagName, expression); + } + + /// + /// Add default tags that will be use for writes by Point and POJO. + /// + /// + /// tags dictionary + public void AddDefaultTags(Dictionary tags) + { + foreach (var tag in tags) + { + Arguments.CheckNotNull(tag.Key, "TagName"); + PointSettings.AddDefaultTag(tag.Key, tag.Value); + } + } + + /// + /// Create an instance of InfluxDBClientOptions. The url could be a connection string with various configurations. + /// + /// e.g.: "http://localhost:8086?timeout=5000&logLevel=BASIC + /// The following options are supported: + /// + /// Timeout - timespan to wait before the HTTP request times out + /// LogLevel - log level for the request and response information + /// Token - setup authorization by + /// Username - with Password property setup authorization by + /// Password - with Username property setup authorization by + /// Org - specify the default destination organization for writes and queries + /// Bucket - specify the default destination bucket for writes + /// WebProxy - specify the WebProxy instance to use by the WebRequest to connect to external InfluxDB. + /// AllowHttpRedirects - configure automatically following HTTP 3xx redirects + /// VerifySsl - ignore Certificate Validation Errors when `false` + /// VerifySslCallback - callback function for handling the remote SSL Certificate Validation. The callback takes precedence over `VerifySsl` + /// ClientCertificates - set X509CertificateCollection to be sent with HTTP requests + /// DefaultTags - tags that will be use for writes by Point and POJO + /// + /// + /// + /// url to connect the InfluxDB + public InfluxDBClientOptions(string url) + { + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentException("The url to connect the InfluxDB has to be defined."); + } + + var uri = new Uri(url); + + Url = uri.GetLeftPart(UriPartial.Path); + if (string.IsNullOrEmpty(Url)) + { + throw new ArgumentException("The url to connect the InfluxDB has to be defined."); + } + + var query = HttpUtility.ParseQueryString(uri.Query); + Org = query.Get("org"); + Bucket = query.Get("bucket"); + AllowHttpRedirects = Convert.ToBoolean(query.Get("allowHttpRedirects")); + + var verifySslValue = query.Get("verifySsl"); + var token = query.Get("token"); + var logLevel = query.Get("logLevel"); + var timeout = query.Get("timeout"); + + VerifySsl = Convert.ToBoolean(string.IsNullOrEmpty(verifySslValue) ? "true" : verifySslValue); + + if (!string.IsNullOrWhiteSpace(token)) + { + Token = token; + } + + if (!string.IsNullOrWhiteSpace(logLevel)) + { + Enum.TryParse(logLevel, true, out LogLevel logLevelValue); + LogLevel = logLevelValue; + } - public RemoteCertificateValidationCallback VerifySslCallback { get; } + if (!string.IsNullOrWhiteSpace(timeout)) + { + Timeout = ToTimeout(timeout); + } - public X509CertificateCollection ClientCertificates { get; } + if (Timeout == TimeSpan.Zero || Timeout == TimeSpan.FromMilliseconds(0)) + { + Timeout = TimeSpan.FromSeconds(10); + } + + PointSettings = new PointSettings(); + } + + /// + /// Configure InfluxDBClientOptions via App.config. + /// + /// Name of configuration section. Useful for tests. + /// + public static InfluxDBClientOptions LoadConfig(string sectionName = "influx2") + { + var config = (Influx2)ConfigurationManager.GetSection(sectionName); + if (config == null) + { + const string message = "The configuration doesn't contains a 'influx2' section. " + + "The minimal configuration should contains an url of InfluxDB. " + + "For more details see: " + + "https://github.com/influxdata/influxdb-client-csharp/blob/master/Client/README.md#client-configuration-file"; + + throw new ConfigurationErrorsException(message); + } + + var url = config.Url; + var org = config.Org; + var bucket = config.Bucket; + var token = config.Token; + var logLevel = config.LogLevel; + var timeout = config.Timeout; + var allowHttpRedirects = config.AllowHttpRedirects; + var verifySsl = config.VerifySsl; + + var influxDbClientOptions = new InfluxDBClientOptions(url) + { + Org = org, + Bucket = bucket, + AllowHttpRedirects = allowHttpRedirects, + VerifySsl = verifySsl + }; + + if (!string.IsNullOrWhiteSpace(token)) + { + influxDbClientOptions.Token = token; + } + + if (!string.IsNullOrWhiteSpace(logLevel)) + { + Enum.TryParse(logLevel, true, out LogLevel logLevelValue); + influxDbClientOptions.LogLevel = logLevelValue; + } + + if (!string.IsNullOrWhiteSpace(timeout)) + { + influxDbClientOptions.Timeout = ToTimeout(timeout); + } + + if (influxDbClientOptions.Timeout == TimeSpan.Zero || + influxDbClientOptions.Timeout == TimeSpan.FromMilliseconds(0)) + { + influxDbClientOptions.Timeout = TimeSpan.FromSeconds(10); + } + + var tags = config.Tags; + if (tags != null) + { + foreach (Influx2.TagElement o in tags) + influxDbClientOptions.PointSettings.AddDefaultTag(o.Name, o.Value); + } + + return influxDbClientOptions; + } private InfluxDBClientOptions(Builder builder) { @@ -54,23 +399,68 @@ private InfluxDBClientOptions(Builder builder) Url = builder.UrlString; LogLevel = builder.LogLevelValue; AuthScheme = builder.AuthScheme; - Token = builder.Token; - Username = builder.Username; - Password = builder.Password; + + switch (builder.AuthScheme) + { + case AuthenticationScheme.Token: + Token = builder.Token; + break; + case AuthenticationScheme.Session: + Username = builder.Username; + Password = builder.Password; + break; + } Org = builder.OrgString; Bucket = builder.BucketString; - Timeout = builder.Timeout; - - WebProxy = builder.WebProxy; AllowHttpRedirects = builder.AllowHttpRedirects; - PointSettings = builder.PointSettings; - VerifySsl = builder.VerifySslCertificates; VerifySslCallback = builder.VerifySslCallback; - ClientCertificates = builder.CertificateCollection; + + if (builder.WebProxy != null) + { + WebProxy = builder.WebProxy; + } + + if (builder.CertificateCollection != null) + { + ClientCertificates = builder.CertificateCollection; + } + } + + private static TimeSpan ToTimeout(string value) + { + var matcher = DurationRegex.Match(value); + if (!matcher.Success) + { + throw new InfluxException($"'{value}' is not a valid duration"); + } + + var amount = matcher.Groups["Amount"].Value; + var unit = matcher.Groups["Unit"].Value; + + TimeSpan duration; + switch (string.IsNullOrWhiteSpace(unit) ? "ms" : unit.ToLower()) + { + case "ms": + duration = TimeSpan.FromMilliseconds(double.Parse(amount)); + break; + + case "s": + duration = TimeSpan.FromSeconds(double.Parse(amount)); + break; + + case "m": + duration = TimeSpan.FromMinutes(double.Parse(amount)); + break; + + default: + throw new InfluxException($"unknown unit for '{value}'"); + } + + return duration; } /// @@ -103,9 +493,9 @@ public sealed class Builder internal LogLevel LogLevelValue; internal AuthenticationScheme AuthScheme; - internal char[] Token; + internal string Token; internal string Username; - internal char[] Password; + internal string Password; internal TimeSpan Timeout; internal string OrgString; @@ -180,7 +570,7 @@ public Builder Authenticate(string username, AuthScheme = AuthenticationScheme.Session; Username = username; - Password = password; + Password = new string(password); return this; } @@ -195,7 +585,7 @@ public Builder AuthenticateToken(char[] token) Arguments.CheckNotNull(token, "token"); AuthScheme = AuthenticationScheme.Token; - Token = token; + Token = new string(token); return this; } @@ -419,39 +809,6 @@ private Builder Configure(string url, string org, string bucket, string token, s return this; } - private TimeSpan ToTimeout(string value) - { - var matcher = DurationRegex.Match(value); - if (!matcher.Success) - { - throw new InfluxException($"'{value}' is not a valid duration"); - } - - var amount = matcher.Groups["Amount"].Value; - var unit = matcher.Groups["Unit"].Value; - - TimeSpan duration; - switch (string.IsNullOrWhiteSpace(unit) ? "ms" : unit.ToLower()) - { - case "ms": - duration = TimeSpan.FromMilliseconds(double.Parse(amount)); - break; - - case "s": - duration = TimeSpan.FromSeconds(double.Parse(amount)); - break; - - case "m": - duration = TimeSpan.FromMinutes(double.Parse(amount)); - break; - - default: - throw new InfluxException($"unknown unit for '{value}'"); - } - - return duration; - } - /// /// Build an instance of InfluxDBClientOptions. /// diff --git a/Client/Internal/ApiClient.cs b/Client/Internal/ApiClient.cs index e8b4a5a5b..696cc114d 100644 --- a/Client/Internal/ApiClient.cs +++ b/Client/Internal/ApiClient.cs @@ -85,7 +85,7 @@ internal void BeforeIntercept(RestRequest request) if (InfluxDBClientOptions.AuthenticationScheme.Token.Equals(_options.AuthScheme)) { - request.AddHeader("Authorization", "Token " + new string(_options.Token)); + request.AddHeader("Authorization", $"Token {_options.Token}"); } else if (InfluxDBClientOptions.AuthenticationScheme.Session.Equals(_options.AuthScheme)) { @@ -116,7 +116,7 @@ private void InitToken() { var header = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes( - _options.Username + ":" + new string(_options.Password))); + _options.Username + ":" + _options.Password)); var request = new RestRequest("/api/v2/signin", Method.Post) .AddHeader("Authorization", header); diff --git a/Client/README.md b/Client/README.md index 5ae4de90a..83e23b9b4 100644 --- a/Client/README.md +++ b/Client/README.md @@ -59,13 +59,13 @@ namespace Examples { private static readonly string Token = ""; - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)"; - var queryApi = influxDBClient.GetQueryApi(); + var queryApi = client.GetQueryApi(); // // QueryData @@ -78,8 +78,6 @@ namespace Examples Console.WriteLine($"{record.GetTime()}: {record.GetValueByKey("_value")}"); }); }); - - influxDBClient.Dispose(); } } } @@ -99,13 +97,13 @@ namespace Examples { private static readonly string Token = ""; - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)"; - var queryApi = influxDBClient.GetQueryApi(); + var queryApi = client.GetQueryApi(); // // QueryData @@ -115,8 +113,6 @@ namespace Examples { Console.WriteLine($"{temperature.Location}: {temperature.Value} at {temperature.Time}"); }); - - influxDBClient.Dispose(); } [Measurement("temperature")] @@ -148,13 +144,13 @@ namespace Examples { private static readonly string Token = ""; - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)"; - var queryApi = influxDBClient.GetQueryApi(); + var queryApi = client.GetQueryApi(); // // QueryData @@ -178,8 +174,6 @@ namespace Examples // Console.WriteLine("Query completed"); }, "org_id"); - - influxDBClient.Dispose(); } } } @@ -199,13 +193,13 @@ namespace Examples { private static readonly string Token = ""; - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)"; - var queryApi = influxDBClient.GetQueryApi(); + var queryApi = client.GetQueryApi(); // // QueryData @@ -217,8 +211,6 @@ namespace Examples // Console.WriteLine($"{temperature.Location}: {temperature.Value} at {temperature.Time}"); }, org: "org_id"); - - influxDBClient.Dispose(); } [Measurement("temperature")] @@ -249,13 +241,13 @@ namespace Examples { private static readonly string Token = ""; - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)"; - var queryApi = influxDBClient.GetQueryApi(); + var queryApi = client.GetQueryApi(); // // QueryData @@ -263,8 +255,6 @@ namespace Examples var csv = await queryApi.QueryRawAsync(flux, org: "org_id"); Console.WriteLine($"CSV response: {csv}"); - - influxDBClient.Dispose(); } } } @@ -283,13 +273,13 @@ namespace Examples { private static readonly string Token = ""; - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)"; - var queryApi = influxDBClient.GetQueryApi(); + var queryApi = client.GetQueryApi(); // // QueryData @@ -301,8 +291,6 @@ namespace Examples // Console.WriteLine($"Response: {line}"); }, org: "org_id"); - - influxDBClient.Dispose(); } } } @@ -320,9 +308,9 @@ namespace Examples { public static class SynchronousQuery { - public static void Main(string[] args) + public static void Main() { - using var client = InfluxDBClientFactory.Create("http://localhost:9999", "my-token"); + using var client = new InfluxDBClient("http://localhost:9999", "my-token"); const string query = "from(bucket:\"my-bucket\") |> range(start: 0)"; @@ -393,14 +381,14 @@ namespace Examples { private static readonly string Token = ""; - public static void Main(string[] args) + public static void Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); // // Write Data // - using (var writeApi = influxDBClient.GetWriteApi()) + using (var writeApi = client.GetWriteApi()) { // // Write by POCO @@ -409,8 +397,6 @@ namespace Examples writeApi.WriteMeasurement(temperature, WritePrecision.Ns, "bucket_name", "org_id"); } - - influxDBClient.Dispose(); } [Measurement("temperature")] @@ -442,14 +428,14 @@ namespace Examples { private static readonly string Token = ""; - public static void Main(string[] args) + public static void Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); // // Write Data // - using (var writeApi = influxDBClient.GetWriteApi()) + using (var writeApi = client.GetWriteApi()) { // // Write by Data Point @@ -461,8 +447,6 @@ namespace Examples writeApi.WritePoint(point, "bucket_name", "org_id"); } - - influxDBClient.Dispose(); } } } @@ -484,14 +468,14 @@ namespace Examples { private static readonly string Token = ""; - public static void Main(string[] args) + public static void Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); // // Write Data // - using (var writeApi = influxDBClient.GetWriteApi()) + using (var writeApi = client.GetWriteApi()) { // // Write by Data Point @@ -511,8 +495,6 @@ namespace Examples writeApi.WritePoint(pointB, "bucket_name", "org_id"); } - - influxDBClient.Dispose(); } } } @@ -533,14 +515,14 @@ namespace Examples { private static readonly string Token = ""; - public static void Main(string[] args) + public static void Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); // // Write Data // - using (var writeApi = influxDBClient.GetWriteApi()) + using (var writeApi = client.GetWriteApi()) { // // @@ -548,8 +530,6 @@ namespace Examples // writeApi.WriteRecord("temperature,location=north value=60.0", WritePrecision.Ns,"bucket_name", "org_id"); } - - influxDBClient.Dispose(); } } } @@ -578,15 +558,15 @@ namespace Examples [Column(IsTimestamp = true)] public DateTime Time { get; set; } } - public static async Task Main(string[] args) + public static async Task Main() { - var influxDbClient = InfluxDBClientFactory.Create("http://localhost:8086", - "my-user", "my-password".ToCharArray()); + using var client = new InfluxDBClient("http://localhost:8086", + "my-user", "my-password"); // // Write Data // - var writeApiAsync = influxDbClient.GetWriteApiAsync(); + var writeApiAsync = client.GetWriteApiAsync(); // // @@ -627,8 +607,6 @@ namespace Examples Console.WriteLine($"{record.GetTime()}: {record.GetValue()}"); }); }); - - influxDbClient.Dispose(); } } } @@ -676,14 +654,17 @@ In a [configuration file](#client-configuration-file) you are able to specify de ##### Via API ```c# -var options = new InfluxDBClientOptions.Builder() - .Url(url) - .AuthenticateToken(token) - .AddDefaultTag("id", "132-987-655") - .AddDefaultTag("customer", "California Miner") - .AddDefaultTag("hostname", "${env.Hostname}") - .AddDefaultTag("sensor-version", "${SensorVersion}") - .Build() +var options = new InfluxDBClientOptions(Url) +{ + Token = token, + DefaultTags = new Dictionary + { + {"id", "132-987-655"}, + {"customer", "California Miner"}, + } +}; +options.AddDefaultTag("hostname", "${env.Hostname}") +options.AddDefaultTags(new Dictionary{{ "sensor-version", "${SensorVersion}" }}) ``` Both of configurations will produce the Line protocol: @@ -775,16 +756,14 @@ namespace Examples { private static readonly string Token = ""; - public static void Main(string[] args) + public static void Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); // // Delete data // - await influxDB.GetDeleteApi().Delete(DateTime.UtcNow.AddMinutes(-1), DateTime.Now, "", "bucket", "org"); - - influxDBClient.Dispose(); + await client.GetDeleteApi().Delete(DateTime.UtcNow.AddMinutes(-1), DateTime.Now, "", "bucket", "org"); } } } @@ -823,13 +802,13 @@ namespace Examples { public static class ManagementExample { - public static async Task Main(string[] args) + public static async Task Main() { const string url = "http://localhost:8086"; const string token = "my-token"; const string org = "my-org"; - using var client = InfluxDBClientFactory.Create(url, token); + using var client = new InfluxDBClient(url, token); // Find ID of Organization with specified name (PermissionAPI requires ID of Organization). var orgId = (await client.GetOrganizationsApi().FindOrganizationsAsync(org: org)).First().Id; @@ -1026,15 +1005,15 @@ namespace Examples const string token = "my-token"; const string bucket = "my-bucket"; const string organization = "my-org"; - var options = new InfluxDBClientOptions.Builder() - .Url(host) - .AuthenticateToken(token.ToCharArray()) - .Org(organization) - .Bucket(bucket) - .Build(); + var options = new InfluxDBClientOptions(host) + { + Token = token, + Org = organization, + Bucket = bucket + }; var converter = new DomainEntityConverter(); - var client = InfluxDBClientFactory.Create(options); + using var client = new InfluxDBClient(options); // // Prepare data to write @@ -1095,8 +1074,6 @@ namespace Examples // Print result // sensors.ForEach(it => Console.WriteLine(it.ToString())); - - client.Dispose(); } } } @@ -1146,7 +1123,7 @@ The `Timeout` supports `ms`, `s` and `m` as unit. Default is milliseconds. and then: ```c# -var influxDBClient = InfluxDBClientFactory.Create(); +var client = InfluxDBClientFactory.Create(); ``` ### Client connection string @@ -1154,8 +1131,7 @@ var influxDBClient = InfluxDBClientFactory.Create(); A client can be constructed using a connection string that can contain the InfluxDBClientOptions parameters encoded into the URL. ```c# -var influxDBClient = InfluxDBClientFactory - .Create("http://localhost:8086?timeout=5000&logLevel=BASIC") +var client = new InfluxDBClient("http://localhost:8086?timeout=5000&logLevel=BASIC"); ``` The following options are supported: @@ -1180,41 +1156,31 @@ influxDBClient.EnableGzip(); ### How to use WebProxy -The `WebProxy` could be configured via `InfluxDBClientOptions.Builder`: +You can configure the client to tunnel requests through an HTTP proxy. The `WebProxy` could be +configured via `InfluxDBClientOptions` parameter `WebProxy`: ```c# -var options = new InfluxDBClientOptions.Builder() - .Url("http://localhost:8086") - .AuthenticateToken("my-token".ToCharArray()) - .Proxy(new WebProxy("http://proxyserver:80/", true)) - .Build(); +var options = new InfluxDBClientOptions("http://localhost:8086") +{ + Token = "my-token", + WebProxy = new WebProxy("http://proxyserver:80/", true) +}; -var client = InfluxDBClientFactory.Create(options); +var client = new InfluxDBClient(options); ``` -### Proxy and redirects configuration - -You can configure the client to tunnel requests through an HTTP proxy. To configure the proxy use `Proxy` configuration option: - - ```csharp -var options = new InfluxDBClientOptions.Builder() - .Url("http://localhost:8086") - .AuthenticateToken("my-token") - .Proxy(new WebProxy("http://proxyserver:80/", true)) - .Build(); - -using var client = InfluxDBClientFactory.Create(options); -``` +### Redirects configuration Client automatically **doesn't** follows HTTP redirects. You can enable redirects by `AllowRedirects` configuration option: ```csharp -var options = new InfluxDBClientOptions.Builder() - .Url("http://localhost:8086") - .AllowRedirects(true) - .Build(); +var options = new InfluxDBClientOptions("http://localhost:8086") +{ + Token = "my-token", + AllowRedirects = true +}; -using var client = InfluxDBClientFactory.Create(options); +using var client = new InfluxDBClient(options); ``` > :warning: Due to a security reason `Authorization` header is not forwarded when redirect leads to a different domain. @@ -1226,7 +1192,7 @@ The Requests and Responses can be logged by changing the LogLevel. LogLevel valu applying the `Body` LogLevel will disable chunking while streaming and will load the whole response into memory. ```c# -influxDBClient.SetLogLevel(LogLevel.Body) +client.SetLogLevel(LogLevel.Body) ``` #### Check the server status and version diff --git a/Client/WriteOptions.cs b/Client/WriteOptions.cs index 4b88e1ba5..f4d3a64d7 100644 --- a/Client/WriteOptions.cs +++ b/Client/WriteOptions.cs @@ -1,3 +1,4 @@ +using System; using System.Reactive.Concurrency; using InfluxDB.Client.Core; @@ -27,23 +28,56 @@ public class WriteOptions private const int DefaultMaxRetryDelay = 125_000; private const int DefaultExponentialBase = 2; + private int _batchSize; + private int _flushInterval; + private int _jitterInterval; + private int _retryInterval; + private int _maxRetries; + private int _maxRetryDelay; + private int _exponentialBase; + private IScheduler _writeScheduler; + /// /// The number of data point to collect in batch. /// /// - internal int BatchSize { get; } + public int BatchSize + { + get => _batchSize; + set + { + Arguments.CheckPositiveNumber(value, "batchSize"); + _batchSize = value; + } + } /// /// The time to wait at most (milliseconds). /// /// - internal int FlushInterval { get; } + public int FlushInterval + { + get => _flushInterval; + set + { + Arguments.CheckPositiveNumber(value, "flushInterval"); + _flushInterval = value; + } + } /// /// The batch flush jitter interval value (milliseconds). /// /// - internal int JitterInterval { get; } + public int JitterInterval + { + get => _jitterInterval; + set + { + Arguments.CheckNotNegativeNumber(value, "jitterInterval"); + _jitterInterval = value; + } + } /// /// The time to wait before retry unsuccessful write (milliseconds). @@ -55,31 +89,98 @@ public class WriteOptions /// /// /// - public int RetryInterval { get; } + public int RetryInterval + { + get => _retryInterval; + set + { + Arguments.CheckPositiveNumber(value, "retryInterval"); + _retryInterval = value; + } + } /// /// The number of max retries when write fails. /// /// - public int MaxRetries { get; } + public int MaxRetries + { + get => _maxRetries; + set + { + Arguments.CheckPositiveNumber(value, "MaxRetries"); + _maxRetries = value; + } + } /// /// The maximum delay between each retry attempt in milliseconds. /// /// - public int MaxRetryDelay { get; } + public int MaxRetryDelay + { + get => _maxRetryDelay; + set + { + Arguments.CheckPositiveNumber(value, "MaxRetryDelay"); + _maxRetryDelay = value; + } + } /// /// The base for the exponential retry delay. /// /// - public int ExponentialBase { get; } + public int ExponentialBase + { + get => _exponentialBase; + set + { + Arguments.CheckPositiveNumber(value, "ExponentialBase"); + _exponentialBase = value; + } + } /// /// Set the scheduler which is used for write data points. /// /// - internal IScheduler WriteScheduler { get; } + public IScheduler WriteScheduler + { + get => _writeScheduler; + set + { + Arguments.CheckNotNull(value, "Write scheduler"); + _writeScheduler = value; + } + } + + /// + /// Create an instance of WriteOptions. + /// + /// WriteOptions properties and their default values: + /// + /// BatchSize: 1000 + /// FlushInterval: 1000(ms) + /// JitterInterval: 0 + /// RetryInterval: 5000(ms) + /// MaxRetries: 5 + /// MaxRetryDelay: 125_000 + /// ExponentialBase: 2 + /// + /// + /// + public WriteOptions() + { + _batchSize = DefaultBatchSize; + _flushInterval = DefaultFlushInterval; + _jitterInterval = DefaultJitterInterval; + _retryInterval = DefaultRetryInterval; + _maxRetries = DefaultMaxRetries; + _maxRetryDelay = DefaultMaxRetryDelay; + _exponentialBase = DefaultExponentialBase; + _writeScheduler = ThreadPoolScheduler.Instance; + } private WriteOptions(Builder builder) { @@ -225,6 +326,8 @@ public Builder WriteScheduler(IScheduler writeScheduler) /// Build an instance of WriteOptions. /// /// + /// Deprecated - please use use object initializer + [Obsolete("This method is deprecated. Call 'WriteOptions' initializer instead.", false)] public WriteOptions Build() { return new WriteOptions(this); diff --git a/Client/Writes/PointSettings.cs b/Client/Writes/PointSettings.cs index cbb06ccad..dff996ceb 100644 --- a/Client/Writes/PointSettings.cs +++ b/Client/Writes/PointSettings.cs @@ -28,6 +28,24 @@ public class PointSettings RegexOptions.CultureInvariant | RegexOptions.RightToLeft); + /// + /// Default tags that will be use for writes by Point and POJO. + /// + public Dictionary DefaultTags + { + get => (Dictionary)GetDefaultTags(); + set + { + Arguments.CheckNotNull(value, "DefaultTags"); + _defaultTags.Clear(); + foreach (var tag in value) + { + Arguments.CheckNotNull(tag.Key, "TagName"); + _defaultTags[tag.Key] = tag.Value; + } + } + } + /// /// Add default tag. /// diff --git a/Examples/CustomDomainMapping.cs b/Examples/CustomDomainMapping.cs index 3f8901ba6..1fac3d6d2 100644 --- a/Examples/CustomDomainMapping.cs +++ b/Examples/CustomDomainMapping.cs @@ -88,21 +88,22 @@ public PointData ConvertToPointData(T entity, WritePrecision precision) } } - public static async Task Main(string[] args) + public static async Task Main() { const string host = "http://localhost:9999"; const string token = "my-token"; const string bucket = "my-bucket"; const string organization = "my-org"; - var options = new InfluxDBClientOptions.Builder() - .Url(host) - .AuthenticateToken(token.ToCharArray()) - .Org(organization) - .Bucket(bucket) - .Build(); + + var options = new InfluxDBClientOptions(host) + { + Token = token, + Org = organization, + Bucket = bucket + }; var converter = new DomainEntityConverter(); - var client = InfluxDBClientFactory.Create(options); + using var client = new InfluxDBClient(options); // // Prepare data to write @@ -163,8 +164,6 @@ await client.GetWriteApiAsync(converter) // Print result // sensors.ForEach(it => Console.WriteLine(it.ToString())); - - client.Dispose(); } } } \ No newline at end of file diff --git a/Examples/CustomDomainMappingAndLinq.cs b/Examples/CustomDomainMappingAndLinq.cs index 8d31760fd..b71b7cb70 100644 --- a/Examples/CustomDomainMappingAndLinq.cs +++ b/Examples/CustomDomainMappingAndLinq.cs @@ -160,21 +160,22 @@ public string GetNamedFieldName(MemberInfo memberInfo, object value) } } - public static async Task Main(string[] args) + public static async Task Main() { const string host = "http://localhost:9999"; const string token = "my-token"; const string bucket = "my-bucket"; const string organization = "my-org"; - var options = new InfluxDBClientOptions.Builder() - .Url(host) - .AuthenticateToken(token.ToCharArray()) - .Org(organization) - .Bucket(bucket) - .Build(); + + var options = new InfluxDBClientOptions(host) + { + Token = token, + Org = organization, + Bucket = bucket + }; var converter = new DomainEntityConverter(); - var client = InfluxDBClientFactory.Create(options); + using var client = new InfluxDBClient(options); // // Prepare data to write @@ -308,8 +309,6 @@ where s.Properties.Any(a => a.Name == "width" && a.Value == 160) Console.WriteLine(); Console.WriteLine(influxQuery._Query); - - client.Dispose(); } } } \ No newline at end of file diff --git a/Examples/ExampleBlazor/Data/ClientSettings.cs b/Examples/ExampleBlazor/Data/ClientSettings.cs index ec04a4084..81586a768 100644 --- a/Examples/ExampleBlazor/Data/ClientSettings.cs +++ b/Examples/ExampleBlazor/Data/ClientSettings.cs @@ -21,12 +21,12 @@ public Client(string? url, string? token, string? org) public InfluxDBClient GetClient(double timespanSeconds = 10) { - var options = new InfluxDBClientOptions.Builder() - .Url(Url) - .AuthenticateToken(Token) - .TimeOut(TimeSpan.FromSeconds(timespanSeconds)) - .Build(); + var options = new InfluxDBClientOptions(Url) + { + Token = Token, + Timeout = TimeSpan.FromSeconds(timespanSeconds) + }; - return InfluxDBClientFactory.Create(options); + return new InfluxDBClient(options); } } \ No newline at end of file diff --git a/Examples/FluxClientFactoryExample.cs b/Examples/FluxClientExample.cs similarity index 81% rename from Examples/FluxClientFactoryExample.cs rename to Examples/FluxClientExample.cs index 8b8da8773..bb9bd7da8 100644 --- a/Examples/FluxClientFactoryExample.cs +++ b/Examples/FluxClientExample.cs @@ -4,20 +4,20 @@ namespace Examples { - public static class FluxClientFactoryExample + public static class FluxClientExample { - public static async Task Main(string[] args) + public static async Task Main() { var options = new FluxConnectionOptions("http://127.0.0.1:8086"); - using var fluxClient = FluxClientFactory.Create(options); + using var client = new FluxClient(options); var fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" + " |> range(start: -1d)" + " |> sample(n: 5, pos: 1)"; - await fluxClient.QueryAsync(fluxQuery, record => + await client.QueryAsync(fluxQuery, record => { // process the flux query records Console.WriteLine(record.GetTime() + ": " + record.GetValue()); diff --git a/Examples/FluxClientPocoExample.cs b/Examples/FluxClientPocoExample.cs index b7b30f2a8..cdd56d15d 100644 --- a/Examples/FluxClientPocoExample.cs +++ b/Examples/FluxClientPocoExample.cs @@ -6,11 +6,11 @@ namespace Examples { public static class FluxClientPocoExample { - public static async Task Main(string[] args) + public static async Task Main() { var options = new FluxConnectionOptions("http://127.0.0.1:8086"); - using var fluxClient = FluxClientFactory.Create(options); + using var client = new FluxClient(options); var fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" @@ -18,7 +18,7 @@ public static async Task Main(string[] args) + " |> sample(n: 5, pos: 1)"; ////Example of additional result stream processing on client side - await fluxClient.QueryAsync(fluxQuery, cpu => + await client.QueryAsync(fluxQuery, cpu => { // process the flux query records Console.WriteLine(cpu.ToString()); diff --git a/Examples/FluxClientSimpleExample.cs b/Examples/FluxClientSimpleExample.cs index 6e193e9b5..4216d553c 100644 --- a/Examples/FluxClientSimpleExample.cs +++ b/Examples/FluxClientSimpleExample.cs @@ -6,12 +6,12 @@ namespace Examples { public static class FluxClientSimpleExample { - public static async Task Main(string[] args) + public static async Task Main() { Console.WriteLine("Start"); var options = new FluxConnectionOptions("http://127.0.0.1:8086", TimeSpan.FromSeconds(20)); - using var client = FluxClientFactory.Create(options); + using var client = new FluxClient(options); var fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" diff --git a/Examples/FluxExample.cs b/Examples/FluxExample.cs index be97e401d..7afc11fb0 100644 --- a/Examples/FluxExample.cs +++ b/Examples/FluxExample.cs @@ -6,16 +6,16 @@ namespace Examples { public static class FluxExample { - public static async Task Main(string[] args) + public static async Task Main() { - using var fluxClient = FluxClientFactory.Create("http://localhost:8086/"); + using var client = new FluxClient("http://localhost:8086/"); var fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" + " |> range(start: -1d)" + " |> sample(n: 5, pos: 1)"; - await fluxClient.QueryAsync(fluxQuery, record => + await client.QueryAsync(fluxQuery, record => { // process the flux query records Console.WriteLine(record.GetTime() + ": " + record.GetValue()); diff --git a/Examples/FluxRawExample.cs b/Examples/FluxRawExample.cs index d6f60db02..609723dc8 100644 --- a/Examples/FluxRawExample.cs +++ b/Examples/FluxRawExample.cs @@ -6,16 +6,16 @@ namespace Examples { public static class FluxRawExample { - public static async Task Main(string[] args) + public static async Task Main() { - using var fluxClient = FluxClientFactory.Create("http://localhost:8086/"); + using var client = new FluxClient("http://localhost:8086/"); var fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" + " |> range(start: -1d)" + " |> sample(n: 5, pos: 1)"; - await fluxClient.QueryRawAsync(fluxQuery, line => + await client.QueryRawAsync(fluxQuery, line => { // process the flux query result record Console.WriteLine(line); diff --git a/Examples/InfluxDB18Example.cs b/Examples/InfluxDB18Example.cs index a719e8e86..97cd996a9 100644 --- a/Examples/InfluxDB18Example.cs +++ b/Examples/InfluxDB18Example.cs @@ -7,14 +7,14 @@ namespace Examples { public class InfluxDB18Example { - public static async Task Main(string[] args) + public static async Task Main() { const string database = "telegraf"; const string retentionPolicy = "autogen"; - var client = InfluxDBClientFactory.CreateV1("http://localhost:8086", + using var client = new InfluxDBClient("http://localhost:8086", "username", - "password".ToCharArray(), + "password", database, retentionPolicy); @@ -39,8 +39,6 @@ public static async Task Main(string[] args) Console.WriteLine( $"{record.GetTime()} {record.GetMeasurement()}: {record.GetField()} {record.GetValue()}"); }); - - client.Dispose(); } } } \ No newline at end of file diff --git a/Examples/InvokableScripts.cs b/Examples/InvokableScripts.cs index 730b63d42..a00750dd1 100644 --- a/Examples/InvokableScripts.cs +++ b/Examples/InvokableScripts.cs @@ -15,21 +15,21 @@ namespace Examples /// public static class InvokableScripts { - public static async Task Main(string[] args) + public static async Task Main() { const string host = "https://us-west-2-1.aws.cloud2.influxdata.com"; const string token = "my-token"; const string bucket = "my-bucket"; const string organization = "my-org"; - var options = new InfluxDBClientOptions.Builder() - .Url(host) - .AuthenticateToken(token.ToCharArray()) - .Org(organization) - .Bucket(bucket) - .Build(); + var options = new InfluxDBClientOptions(host) + { + Token = token, + Org = organization, + Bucket = bucket + }; - using var client = InfluxDBClientFactory.Create(options); + using var client = new InfluxDBClient(options); client.SetLogLevel(LogLevel.Body); // diff --git a/Examples/ManagementExample.cs b/Examples/ManagementExample.cs index 0cf43c32d..b7357f96c 100644 --- a/Examples/ManagementExample.cs +++ b/Examples/ManagementExample.cs @@ -9,13 +9,13 @@ namespace Examples { public static class ManagementExample { - public static async Task Main(string[] args) + public static async Task Main() { const string url = "http://localhost:8086"; const string token = "my-token"; const string org = "my-org"; - using var client = InfluxDBClientFactory.Create(url, token); + using var client = new InfluxDBClient(url, token); // Find ID of Organization with specified name (PermissionAPI requires ID of Organization). var orgId = (await client.GetOrganizationsApi().FindOrganizationsAsync(org: org)).First().Id; diff --git a/Examples/ParametrizedQuery.cs b/Examples/ParametrizedQuery.cs index 0fc9dd219..a2e04928d 100644 --- a/Examples/ParametrizedQuery.cs +++ b/Examples/ParametrizedQuery.cs @@ -18,17 +18,16 @@ public static class ParametrizedQuery private const string Org = "my-org"; private const string Bucket = "my-bucket"; - public static async Task Main(string[] args) + public static async Task Main() { - var options = InfluxDBClientOptions.Builder - .CreateNew() - .Url(Url) - .AuthenticateToken(Token) - .Bucket(Bucket) - .Org(Org) - .Build(); + var options = new InfluxDBClientOptions(Url) + { + Token = Token, + Org = Org, + Bucket = Bucket + }; - using var client = InfluxDBClientFactory.Create(options); + using var client = new InfluxDBClient(options); // // Prepare Data diff --git a/Examples/PlatformExample.cs b/Examples/PlatformExample.cs index 150d13491..11036586c 100644 --- a/Examples/PlatformExample.cs +++ b/Examples/PlatformExample.cs @@ -27,106 +27,113 @@ public override string ToString() } } - public static async Task Main(string[] args) + public static async Task Main() { - var influxDB = InfluxDBClientFactory.Create("http://localhost:9999", - "my-user", "my-password".ToCharArray()); - - var organizationClient = influxDB.GetOrganizationsApi(); - - var medicalGMBH = await organizationClient - .CreateOrganizationAsync("Medical Corp " + - DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", - CultureInfo.InvariantCulture)); + using (var client = new InfluxDBClient("http://localhost:9999", + "my-user", "my-password")) + { + var organizationClient = client.GetOrganizationsApi(); + var medicalGMBH = await organizationClient + .CreateOrganizationAsync("Medical Corp " + + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", + CultureInfo.InvariantCulture)); - // - // Create New Bucket with retention 1h - // - var temperatureBucket = - await influxDB.GetBucketsApi().CreateBucketAsync("temperature-sensors", medicalGMBH.Id); - - // - // Add Permissions to read and write to the Bucket - // - var resource = new PermissionResource - { Type = PermissionResource.TypeBuckets, OrgID = medicalGMBH.Id, Id = temperatureBucket.Id }; + // + // Create New Bucket with retention 1h + // + var temperatureBucket = + await client.GetBucketsApi().CreateBucketAsync("temperature-sensors", medicalGMBH.Id); - var readBucket = new Permission(Permission.ActionEnum.Read, resource); - var writeBucket = new Permission(Permission.ActionEnum.Write, resource); + // + // Add Permissions to read and write to the Bucket + // + var resource = new PermissionResource + { Type = PermissionResource.TypeBuckets, OrgID = medicalGMBH.Id, Id = temperatureBucket.Id }; - var authorization = await influxDB.GetAuthorizationsApi() - .CreateAuthorizationAsync(medicalGMBH, new List { readBucket, writeBucket }); + var readBucket = new Permission(Permission.ActionEnum.Read, resource); + var writeBucket = new Permission(Permission.ActionEnum.Write, resource); - Console.WriteLine($"The token to write to temperature-sensors bucket is: {authorization.Token}"); + var authorization = await client.GetAuthorizationsApi() + .CreateAuthorizationAsync(medicalGMBH, new List { readBucket, writeBucket }); - influxDB.Dispose(); + Console.WriteLine($"The token to write to temperature-sensors bucket is: {authorization.Token}"); + } // // Create new client with specified authorization token // - influxDB = InfluxDBClientFactory.Create("http://localhost:9999", authorization.Token); + using (var client = new InfluxDBClient("http://localhost:9999", + "my-user", "my-password")) + { + var writeOptions = new WriteOptions + { + BatchSize = 5000, + FlushInterval = 1000, + JitterInterval = 1000, + RetryInterval = 5000 + }; - var writeOptions = WriteOptions - .CreateNew() - .BatchSize(5000) - .FlushInterval(1000) - .JitterInterval(1000) - .RetryInterval(5000) - .Build(); + var organizationClient = client.GetOrganizationsApi(); - // - // Write data - // - using (var writeClient = influxDB.GetWriteApi(writeOptions)) - { - // - // Write by POCO - // - var temperature = new Temperature { Location = "south", Value = 62D, Time = DateTime.UtcNow }; - writeClient.WriteMeasurement(temperature, WritePrecision.Ns, "temperature-sensors", medicalGMBH.Id); + var medicalGMBH = await organizationClient + .CreateOrganizationAsync("Medical Corp " + + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", + CultureInfo.InvariantCulture)); + + var temperatureBucket = await client.GetBucketsApi().FindBucketByNameAsync("temperature-sensors"); // - // Write by Point + // Write data // - var point = PointData.Measurement("temperature") - .Tag("location", "west") - .Field("value", 55D) - .Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns); - writeClient.WritePoint(point, "temperature-sensors", medicalGMBH.Id); + using (var writeClient = client.GetWriteApi(writeOptions)) + { + // + // Write by POCO + // + var temperature = new Temperature { Location = "south", Value = 62D, Time = DateTime.UtcNow }; + writeClient.WriteMeasurement(temperature, WritePrecision.Ns, "temperature-sensors", medicalGMBH.Id); + + // + // Write by Point + // + var point = PointData.Measurement("temperature") + .Tag("location", "west") + .Field("value", 55D) + .Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns); + writeClient.WritePoint(point, "temperature-sensors", medicalGMBH.Id); + + // + // Write by LineProtocol + // + var record = "temperature,location=north value=60.0"; + writeClient.WriteRecord(record, WritePrecision.Ns, "temperature-sensors", medicalGMBH.Id); + + writeClient.Flush(); + Thread.Sleep(2000); + } // - // Write by LineProtocol + // Read data // - var record = "temperature,location=north value=60.0"; - writeClient.WriteRecord(record, WritePrecision.Ns, "temperature-sensors", medicalGMBH.Id); - - writeClient.Flush(); - Thread.Sleep(2000); - } - - // - // Read data - // - var fluxTables = await influxDB.GetQueryApi() - .QueryAsync("from(bucket:\"temperature-sensors\") |> range(start: 0)", medicalGMBH.Id); - fluxTables.ForEach(fluxTable => - { - var fluxRecords = fluxTable.Records; - fluxRecords.ForEach(fluxRecord => + var fluxTables = await client.GetQueryApi() + .QueryAsync("from(bucket:\"temperature-sensors\") |> range(start: 0)", medicalGMBH.Id); + fluxTables.ForEach(fluxTable => { - Console.WriteLine($"{fluxRecord.GetTime()}: {fluxRecord.GetValue()}"); + var fluxRecords = fluxTable.Records; + fluxRecords.ForEach(fluxRecord => + { + Console.WriteLine($"{fluxRecord.GetTime()}: {fluxRecord.GetValue()}"); + }); }); - }); - - // - // Delete data - // - await influxDB.GetDeleteApi().Delete(DateTime.UtcNow.AddMinutes(-1), DateTime.Now, "", temperatureBucket, - medicalGMBH); - influxDB.Dispose(); + // + // Delete data + // + await client.GetDeleteApi().Delete(DateTime.UtcNow.AddMinutes(-1), DateTime.Now, "", temperatureBucket, + medicalGMBH); + } } } } \ No newline at end of file diff --git a/Examples/PocoQueryWriteExample.cs b/Examples/PocoQueryWriteExample.cs index aba518dea..687dfbe83 100644 --- a/Examples/PocoQueryWriteExample.cs +++ b/Examples/PocoQueryWriteExample.cs @@ -30,7 +30,7 @@ public override string ToString() } } - public static async Task Main(string[] args) + public static async Task Main() { // // Initialize Client @@ -39,13 +39,15 @@ public static async Task Main(string[] args) const string token = "my-token"; const string bucket = "my-bucket"; const string organization = "my-org"; - var options = new InfluxDBClientOptions.Builder() - .Url(host) - .AuthenticateToken(token.ToCharArray()) - .Org(organization) - .Bucket(bucket) - .Build(); - var client = InfluxDBClientFactory.Create(options); + + var options = new InfluxDBClientOptions(host) + { + Token = token, + Org = organization, + Bucket = bucket + }; + + using var client = new InfluxDBClient(options); // // Prepare data to write @@ -92,8 +94,6 @@ await client.GetWriteApiAsync() // Print result // list.ForEach(it => Console.WriteLine(it.ToString())); - - client.Dispose(); } } } \ No newline at end of file diff --git a/Examples/QueryLinqCloud.cs b/Examples/QueryLinqCloud.cs index 9654f72f8..d6d51f772 100644 --- a/Examples/QueryLinqCloud.cs +++ b/Examples/QueryLinqCloud.cs @@ -141,22 +141,22 @@ public string GetNamedFieldName(MemberInfo memberInfo, object value) } } - public static void Main(string[] args) + public static void Main() { const string host = "https://us-west-2-1.aws.cloud2.influxdata.com"; const string token = "..."; const string bucket = "linq_bucket"; const string organization = "jakub_bednar"; - var options = new InfluxDBClientOptions.Builder() - .Url(host) - .AuthenticateToken(token.ToCharArray()) - .Org(organization) - .Bucket(bucket) - .Build(); + + var options = new InfluxDBClientOptions(host) + { + Token = token, + Org = organization, + Bucket = bucket + }; var converter = new DomainEntityConverter(); - var client = InfluxDBClientFactory.Create(options) - .EnableGzip(); + using var client = new InfluxDBClient(options).EnableGzip(); // // Query Data to Domain object @@ -199,8 +199,6 @@ public static void Main(string[] args) Console.WriteLine(); Console.WriteLine("> query:"); Console.WriteLine(influxQuery._Query); - - client.Dispose(); } } } \ No newline at end of file diff --git a/Examples/RecordRowExample.cs b/Examples/RecordRowExample.cs index 1bd0e9808..cc3142c9a 100644 --- a/Examples/RecordRowExample.cs +++ b/Examples/RecordRowExample.cs @@ -16,7 +16,7 @@ public static async Task Main() const string bucket = "my-bucket"; const string org = "my-org"; - using var client = InfluxDBClientFactory.Create(url, token.ToCharArray()); + using var client = new InfluxDBClient(url, token); // // Prepare Data diff --git a/Examples/RunExamples.cs b/Examples/RunExamples.cs index edeb48d95..91d5e59f8 100644 --- a/Examples/RunExamples.cs +++ b/Examples/RunExamples.cs @@ -19,55 +19,55 @@ public static async Task Main(string[] args) switch (args[0]) { case "FluxExample": - await FluxExample.Main(args); + await FluxExample.Main(); break; case "FluxClientSimpleExample": - await FluxClientSimpleExample.Main(args); + await FluxClientSimpleExample.Main(); break; case "FluxRawExample": - await FluxRawExample.Main(args); + await FluxRawExample.Main(); break; case "FluxClientFactoryExample": - await FluxClientFactoryExample.Main(args); + await FluxClientExample.Main(); break; case "FluxClientPocoExample": - await FluxClientPocoExample.Main(args); + await FluxClientPocoExample.Main(); break; case "PlatformExample": - await PlatformExample.Main(args); + await PlatformExample.Main(); break; case "WriteEventHandlerExample": await WriteEventHandlerExample.Main(); break; case "WriteApiAsyncExample": - await WriteApiAsyncExample.Main(args); + await WriteApiAsyncExample.Main(); break; case "PocoQueryWriteExample": - await PocoQueryWriteExample.Main(args); + await PocoQueryWriteExample.Main(); break; case "CustomDomainMappingAndLinq": - await CustomDomainMappingAndLinq.Main(args); + await CustomDomainMappingAndLinq.Main(); break; case "InfluxDB18Example": - await InfluxDB18Example.Main(args); + await InfluxDB18Example.Main(); break; case "SynchronousQuery": - SynchronousQuery.Main(args); + SynchronousQuery.Main(); break; case "CustomDomainMapping": - await CustomDomainMapping.Main(args); + await CustomDomainMapping.Main(); break; case "QueryLinqCloud": - QueryLinqCloud.Main(args); + QueryLinqCloud.Main(); break; case "ManagementExample": - await ManagementExample.Main(args); + await ManagementExample.Main(); break; case "InvokableScripts": - await InvokableScripts.Main(args); + await InvokableScripts.Main(); break; case "ParametrizedQuery": - await ParametrizedQuery.Main(args); + await ParametrizedQuery.Main(); break; case "RecordRowExample": await RecordRowExample.Main(); diff --git a/Examples/SynchronousQuery.cs b/Examples/SynchronousQuery.cs index 5aba0d70b..3388842ea 100644 --- a/Examples/SynchronousQuery.cs +++ b/Examples/SynchronousQuery.cs @@ -5,9 +5,9 @@ namespace Examples { public class SynchronousQuery { - public static void Main(string[] args) + public static void Main() { - using var client = InfluxDBClientFactory.Create("http://localhost:9999", "my-token"); + using var client = new InfluxDBClient("http://localhost:9999", "my-token"); const string query = "from(bucket:\"my-bucket\") |> range(start: 0)"; diff --git a/Examples/WriteApiAsyncExample.cs b/Examples/WriteApiAsyncExample.cs index a71b29781..5cc0e336d 100644 --- a/Examples/WriteApiAsyncExample.cs +++ b/Examples/WriteApiAsyncExample.cs @@ -19,15 +19,15 @@ private class Temperature [Column(IsTimestamp = true)] public DateTime Time { get; set; } } - public static async Task Main(string[] args) + public static async Task Main() { - var influxDbClient = InfluxDBClientFactory.Create("http://localhost:9999", - "my-user", "my-password".ToCharArray()); + using var client = new InfluxDBClient("http://localhost:9999", + "my-user", "my-password"); // // Write Data // - var writeApiAsync = influxDbClient.GetWriteApiAsync(); + var writeApiAsync = client.GetWriteApiAsync(); // // @@ -57,7 +57,7 @@ await writeApiAsync.WriteRecordAsync("temperature,location=north value=60.0", Wr // // Check written data // - var tables = await influxDbClient.GetQueryApi() + var tables = await client.GetQueryApi() .QueryAsync("from(bucket:\"my-bucket\") |> range(start: 0)", "my-org"); tables.ForEach(table => @@ -65,8 +65,6 @@ await writeApiAsync.WriteRecordAsync("temperature,location=north value=60.0", Wr var fluxRecords = table.Records; fluxRecords.ForEach(record => { Console.WriteLine($"{record.GetTime()}: {record.GetValue()}"); }); }); - - influxDbClient.Dispose(); } } } \ No newline at end of file diff --git a/Examples/WriteEventHandlerExample.cs b/Examples/WriteEventHandlerExample.cs index b472ed4cc..49e6d9911 100644 --- a/Examples/WriteEventHandlerExample.cs +++ b/Examples/WriteEventHandlerExample.cs @@ -34,15 +34,16 @@ public static async Task Main() private static Task BasicEventHandler() { - using var client = InfluxDBClientFactory.Create("http://localhost:9999", - "my-user", "my-password".ToCharArray()); + using var client = new InfluxDBClient("http://localhost:9999", + "my-user", "my-password"); - var options = WriteOptions.CreateNew() - .BatchSize(1) - .FlushInterval(1000) - .RetryInterval(2000) - .MaxRetries(3) - .Build(); + var options = new WriteOptions + { + BatchSize = 1, + FlushInterval = 1000, + RetryInterval = 2000, + MaxRetries = 3 + }; // // Write Data @@ -150,15 +151,17 @@ private static Task BasicEventHandler() private static Task CustomEventListener() { - using var client = InfluxDBClientFactory.Create("http://localhost:9999/", - "my-user", "my-password".ToCharArray()); - - var options = WriteOptions.CreateNew() - .BatchSize(5) - .FlushInterval(1000) - .RetryInterval(2000) - .MaxRetries(3) - .Build(); + using var client = new InfluxDBClient("http://localhost:9999", + "my-user", "my-password"); + + var options = new WriteOptions + { + BatchSize = 5, + FlushInterval = 1000, + RetryInterval = 2000, + MaxRetries = 3 + }; + // // Write Data // diff --git a/README.md b/README.md index 8f819223e..cf722a68b 100644 --- a/README.md +++ b/README.md @@ -87,14 +87,14 @@ namespace Examples { private static readonly char[] Token = "".ToCharArray(); - public static async Task Main(string[] args) + public static async Task Main() { - var influxDBClient = InfluxDBClientFactory.Create("http://localhost:8086", Token); + using var client = new InfluxDBClient("http://localhost:8086", Token); // // Write Data // - using (var writeApi = influxDBClient.GetWriteApi()) + using (var writeApi = client.GetWriteApi()) { // // Write by Point @@ -132,8 +132,6 @@ namespace Examples Console.WriteLine($"{fluxRecord.GetTime()}: {fluxRecord.GetValue()}"); }); }); - - influxDBClient.Dispose(); } [Measurement("temperature")] @@ -179,13 +177,13 @@ namespace Examples { public static class ManagementExample { - public static async Task Main(string[] args) + public static async Task Main() { const string url = "http://localhost:8086"; const string token = "my-token"; const string org = "my-org"; - using var client = InfluxDBClientFactory.Create(url, token); + using var client = new InfluxDBClient(url, token); // Find ID of Organization with specified name (PermissionAPI requires ID of Organization). var orgId = (await client.GetOrganizationsApi().FindOrganizationsAsync(org: org)).First().Id; @@ -264,14 +262,14 @@ namespace Examples { public static void Run() { - using var fluxClient = FluxClientFactory.Create("http://localhost:8086/"); + using var client = new FluxClient("http://localhost:8086/"); var fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" + " |> range(start: -1d)" + " |> sample(n: 5, pos: 1)"; - fluxClient.QueryAsync(fluxQuery, record => + client.QueryAsync(fluxQuery, record => { // process the flux query records Console.WriteLine(record.GetTime() + ": " + record.GetValue());