influxdb-client-csharp

C# - 图1

CircleCI codecov Nuget License GitHub issues GitHub pull requests Slack Status

This repository contains the C# client library for use with InfluxDB 2.x and Flux. InfluxDB 3.x users should instead use the lightweight v3 client library. InfluxDB 1.x users should use the v1 client library.

For ease of migration and a consistent query and write experience, v2 users should consider using InfluxQL and the v1 client library.

Documentation

C# - 图9

This section contains links to the client library documentation.

Client Description Documentation Compatibility
Client The reference C# client that allows query, write and InfluxDB 2.x management. readme 2.x
Client.Linq The library supports to use a LINQ expression to query the InfluxDB. readme 2.x
Client.Legacy The reference C# client that allows you to perform Flux queries against InfluxDB 1.7+. readme 1.7+

Features

C# - 图10

  • Supports querying using the Flux language over the InfluxDB 1.7+ REST API (/api/v2/query endpoint)
  • InfluxDB 2.x client
  • Querying data using the Flux language
  • Writing data using
  • InfluxDB 2.x Management API client for managing
    • sources, buckets
    • tasks
    • authorizations
    • health check
    • …

How To Use

C# - 图11

Writes and Queries in InfluxDB 2.x

C# - 图12

The following example demonstrates how to write data to InfluxDB 2.x and read them back using the Flux language:

Installation

C# - 图13

Use the latest version:

.Net CLI

C# - 图14

1. dotnet add package InfluxDB.Client
Or when using Package Manager

C# - 图15

1. Install-Package InfluxDB.Client
1. using System;
2. using InfluxDB.Client;
3. using InfluxDB.Client.Api.Domain;
4. using InfluxDB.Client.Core;
5. using InfluxDB.Client.Writes;
6. using Task = System.Threading.Tasks.Task;

8. namespace Examples
9. {
10. public static class QueriesWritesExample
11. {
12. private static readonly char[] Token = "".ToCharArray();

14. public static async Task Main()
15. {
16. using var client = new InfluxDBClient("http://localhost:8086", Token);

18. //
19. // Write Data
20. //
21. using (var writeApi = client.GetWriteApi())
22. {
23. //
24. // Write by Point
25. //
26. var point = PointData.Measurement("temperature")
27. .Tag("location", "west")
28. .Field("value", 55D)
29. .Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);

31. writeApi.WritePoint(point, "bucket_name", "org_id");

33. //
34. // Write by LineProtocol
35. //
36. writeApi.WriteRecord("temperature,location=north value=60.0", WritePrecision.Ns, "bucket_name", "org_id");

38. //
39. // Write by POCO
40. //
41. var temperature = new Temperature {Location = "south", Value = 62D, Time = DateTime.UtcNow};
42. writeApi.WriteMeasurement(temperature, WritePrecision.Ns, "bucket_name", "org_id");
43. }

45. //
46. // Query data
47. //
48. var flux = "from(bucket:\"temperature-sensors\") |> range(start: 0)";

50. var fluxTables = await influxDBClient.GetQueryApi().QueryAsync(flux, "org_id");
51. fluxTables.ForEach(fluxTable =>
52. {
53. var fluxRecords = fluxTable.Records;
54. fluxRecords.ForEach(fluxRecord =>
55. {
56. Console.WriteLine($"{fluxRecord.GetTime()}: {fluxRecord.GetValue()}");
57. });
58. });
59. }

61. [Measurement("temperature")]
62. private class Temperature
63. {
64. [Column("location", IsTag = true)] public string? Location { get; set; }

66. [Column("value")] public double Value { get; set; }

68. [Column(IsTimestamp = true)] public DateTime Time { get; set; }
69. }
70. }
71. }

Use Management API to create a new Bucket in InfluxDB 2.x

C# - 图16

The following example demonstrates how to use a InfluxDB 2.x Management API. For further information see client documentation.

Installation

C# - 图17

Use the latest version:

.Net CLI

C# - 图18

1. dotnet add package InfluxDB.Client
Or when using Package Manager

C# - 图19

1. Install-Package InfluxDB.Client
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using InfluxDB.Client;
5. using InfluxDB.Client.Api.Domain;
6. using Task = System.Threading.Tasks.Task;

8. namespace Examples
9. {
10. public static class ManagementExample
11. {
12. public static async Task Main()
13. {
14. const string url = "http://localhost:8086";
15. const string token = "my-token";
16. const string org = "my-org";

18. using var client = new InfluxDBClient(url, token);

20. // Find ID of Organization with specified name (PermissionAPI requires ID of Organization).
21. var orgId = (await client.GetOrganizationsApi().FindOrganizationsAsync(org: org)).First().Id;

23. //
24. // Create bucket "iot_bucket" with data retention set to 3,600 seconds
25. //
26. var retention = new BucketRetentionRules(BucketRetentionRules.TypeEnum.Expire, 3600);

28. var bucket = await client.GetBucketsApi().CreateBucketAsync("iot_bucket", retention, orgId);

30. //
31. // Create access token to "iot_bucket"
32. //
33. var resource = new PermissionResource(PermissionResource.TypeEnum.Buckets, bucket.Id, null,
34. orgId);

36. // Read permission
37. var read = new Permission(Permission.ActionEnum.Read, resource);

39. // Write permission
40. var write = new Permission(Permission.ActionEnum.Write, resource);

42. var authorization = await client.GetAuthorizationsApi()
43. .CreateAuthorizationAsync(orgId, new List<Permission> { read, write });

45. //
46. // Created token that can be use for writes to "iot_bucket"
47. //
48. Console.WriteLine($"Authorized token to write into iot_bucket: {authorization.Token}");
49. }
50. }
51. }

InfluxDB 1.8 API compatibility

C# - 图20

InfluxDB 1.8.0 introduced forward compatibility APIs for InfluxDB 2.x. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.x Cloud or open source.

The following forward compatible APIs are available:

API Endpoint Description
QueryApi.cs /api/v2/query Query data in InfluxDB 1.8.0+ using the InfluxDB 2.x API and Flux (endpoint should be enabled by flux-enabled option)
WriteApi.cs /api/v2/write Write data to InfluxDB 1.8.0+ using the InfluxDB 2.x API
PingAsync /ping Checks the status of InfluxDB instance and version of InfluxDB.

For detail info see InfluxDB 1.8 example.

Flux queries in InfluxDB 1.7+

C# - 图21

The following example demonstrates querying using the Flux language.

Installation

C# - 图22

Use the latest version:

.Net CLI

C# - 图23

1. dotnet add package InfluxDB.Client.Flux
Or when using Package Manager

C# - 图24

1. Install-Package InfluxDB.Client.Flux
1. using System;
2. using InfluxDB.Client.Flux;

4. namespace Examples
5. {
6. public static class FluxExample
7. {
8. public static void Run()
9. {
10. using var client = new FluxClient("http://localhost:8086/");

12. var fluxQuery = "from(bucket: \"telegraf\")\n"
13. + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))"
14. + " |> range(start: -1d)"
15. + " |> sample(n: 5, pos: 1)";

17. client.QueryAsync(fluxQuery, record =>
18. {
19. // process the flux query records
20. Console.WriteLine(record.GetTime() + ": " + record.GetValue());
21. },
22. (error) =>
23. {
24. // error handling while processing result
25. Console.WriteLine(error.ToString());

27. }, () =>
28. {
29. // on complete
30. Console.WriteLine("Query completed");
31. }).GetAwaiter().GetResult();
32. }
33. }
34. }

Contributing

C# - 图25

If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master branch.

License

C# - 图26

The InfluxDB 2.x Clients are released under the MIT License.