Add C# client library examples for Get Started (#5051)

* Add Csharp client lib write examples
Part of #5047

* chore(v3): Add C# write examples, fix Go and Python examples.

- Part of #5047
- Examples for writing with the CNodeJS client library.
- Cleanup and fixes for Go examples.
- Python client library no longer requires `org` for writing (defaults to "").

* chore(v3): Add query examples for C# client library.

- Fixes Add Csharp client lib examples #5047
- Makes Go time formatting consistent with example output.
- Cleanup.

* fix(v3): Add custom timestamp tags
pull/5052/head
Jason Stirnaman 2023-07-26 15:25:24 -05:00 committed by GitHub
parent 1cb3cf856a
commit 76cba186ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 596 additions and 30 deletions

View File

@ -202,6 +202,7 @@ credentials (**url**, **organization**, and **token**) are provided by
[influx3 CLI](#influx3-cli)
[Python](#)
[Go](#)
[C#](#)
{{% /tabs %}}
{{% tab-content %}}
<!--------------------------- BEGIN influx3 CONTENT --------------------------->
@ -351,7 +352,7 @@ _If your project's virtual environment is already running, skip to step 3._
- **database**: the name of the {{% cloud-name %}} database to query
3. Defines the SQL query to execute and assigns it to a `query` variable.
4. Calls the `client.query()` method with the SQL query.
`query()` sends a
Flight request to InfluxDB, queries the database, retrieves result data from the endpoint, and then returns a
@ -426,6 +427,7 @@ _If your project's virtual environment is already running, skip to step 3._
"fmt"
"io"
"os"
"time"
"text/tabwriter"
"github.com/apache/arrow/go/v12/arrow"
@ -434,15 +436,18 @@ _If your project's virtual environment is already running, skip to step 3._
func Query() error {
// INFLUX_TOKEN is an environment variable you created for your database read token
// INFLUX_TOKEN is an environment variable you created
// for your database read token.
token := os.Getenv("INFLUX_TOKEN")
database := "get-started"
// Instantiate the client.
client, err := influx.New(influx.Configs{
HostURL: "https://cluster-id.influxdb.io",
AuthToken: token,
})
// Close the client when the function returns.
defer func (client *influx.Client) {
err := client.Close()
if err != nil {
@ -450,12 +455,13 @@ _If your project's virtual environment is already running, skip to step 3._
}
}(client)
// Execute query
// Define the query.
query := `SELECT *
FROM home
WHERE time >= '2022-01-02T08:00:00Z'
AND time <= '2022-01-02T20:00:00Z'`
// Execute the query.
iterator, err := client.Query(context.Background(), database, query)
if err != nil {
@ -466,10 +472,16 @@ _If your project's virtual environment is already running, skip to step 3._
w.Init(os.Stdout, 0, 8, 0, '\t', 0)
fmt.Fprintln(w, "time\troom\ttemp\thum\tco")
// Iterate over rows and prints column values in table format.
for iterator.Next() {
row := iterator.Value()
day := (row["time"].(arrow.Timestamp)).ToTime(arrow.TimeUnit(arrow.Nanosecond))
fmt.Fprintf(w, "%s\t%s\t%.2f\t%.2f\t%d\n", day, row["room"], row["temp"], row["hum"], row["co"])
// Use Go arrow and time packages to format unix timestamp
// as a time with timezone layout (RFC3339).
time := (row["time"].(arrow.Timestamp)).
ToTime(arrow.TimeUnit(arrow.Nanosecond)).
Format(time.RFC3339)
fmt.Fprintf(w, "%s\t%s\t%d\t%.2f\t%.2f\n",
time, row["room"], row["co"], row["hum"], row["temp"])
}
w.Flush()
@ -493,7 +505,7 @@ _If your project's virtual environment is already running, skip to step 3._
1. Instantiates `influx.Client` with InfluxDB credentials.
- **HostURL**: your {{% cloud-name %}} cluster URL.
- **HostURL**: your {{% cloud-name %}} cluster URL
- **AuthToken**: a [database token](/influxdb/cloud-dedicated/admin/tokens/) with _read_ access to the specified database.
_For security reasons, we recommend setting this as an environment
variable rather than including the raw token string._
@ -502,7 +514,7 @@ _If your project's virtual environment is already running, skip to step 3._
3. Defines a string variable for the SQL query.
4. Calls the `influx.Client.query()` method to send the query request with the database name and SQL string. The `query()` method returns an `iterator` for data in the response stream.
5. Iterates over rows and prints the data in table format to stdout.
5. Iterates over rows, formats the timestamp as an[RFC3339 timestamp](/influxdb/cloud-dedicated/reference/glossary/#rfc3339-timestamp), and prints the data in table format to stdout.
3. In your editor, open the `main.go` file you created in the
[Write data section](/influxdb/cloud-serverless/get-started/write/?t=Go#write-line-protocol-to-influxdb) and insert code to call the `Query()` function--for example:
@ -553,6 +565,123 @@ time room co hum temp
{{< /expand-wrapper >}}
{{% /influxdb/custom-timestamps %}}
<!------------------------------ END GO CONTENT ------------------------------->
{{% /tab-content %}}
{{% tab-content %}}
<!------------------------------ BEGIN C# CONTENT ----------------------------->
```c#
// Query.cs
using System;
using System.Threading.Tasks;
using InfluxDB3.Client;
using InfluxDB3.Client.Query;
namespace InfluxDBv3;
public class Query
{
/**
* Queries an InfluxDB database using the C# .NET client
* library.
**/
public static async Task QuerySQL()
{
/** Set InfluxDB credentials **/
const string hostUrl = "https://cluster-id.influxdb.io";
string? database = "get-started";
/** INFLUX_TOKEN is an environment variable you assigned to your
* API token value.
**/
string? authToken = System.Environment
.GetEnvironmentVariable("INFLUX_TOKEN");
/**
* Instantiate the InfluxDB client with credentials.
**/
using var client = new InfluxDBClient(
hostUrl, authToken: authToken, database: database);
const string sql = @"
SELECT time, room, temp, hum, co
FROM home
WHERE time >= '2022-01-02T08:00:00Z'
AND time <= '2022-01-02T20:00:00Z'
";
Console.WriteLine("{0,-30}{1,-15}{2,-15}{3,-15}{4,-15}",
"time", "room", "temp", "hum", "co");
await foreach (var row in client.Query(query: sql))
{
{
/**
* Iterate over rows and print column values in table format.
* Format the timestamp as sortable UTC format.
*/
Console.WriteLine("{0,-30:u}{1,-15}{2,-15}{3,-15}{4,-15}",
row[0], row[1], row[2], row[3], row[4]);
}
}
Console.WriteLine();
}
}
```
The sample code does the following:
1. Imports the following classes:
- `System`
- `System.Threading.Tasks`;
- `InfluxDB3.Client`;
- `InfluxDB3.Client.Query`;
2. Defines a `Query` class with a `QuerySQL()` method that does the following:
1. Calls the `new InfluxDBClient()` constructor to instantiate a client configured
with InfluxDB credentials.
- **hostURL**: your {{% cloud-name %}} cluster URL.
- **authToken**: a [database token](/influxdb/cloud-dedicated/admin/tokens/) with _read_ access to the specified database.
_For security reasons, we recommend setting this as an environment variable rather than including the raw token string._
- **database**: the name of the {{% cloud-name %}} database to query
2. Defines a string variable for the SQL query.
3. Calls the `InfluxDBClient.Query()` method to send the query request with the SQL string. `Query()` returns batches of rows from the response stream as a two-dimensional array--an array of rows in which each row is an array of values.
4. Iterates over rows and prints the data in table format to stdout.
3. In your editor, open the `Program.cs` file you created in the
[Write data section](/influxdb/cloud-dedicated/get-started/write/?t=C%23#write-line-protocol-to-influxdb) and insert code to call the `Query()` function--for example:
```c#
// Program.cs
using System;
using System.Threading.Tasks;
namespace InfluxDBv3;
public class Program
{
public static async Task Main()
{
await Write.WriteLineProtocol();
await Query.QuerySQL();
}
}
```
4. To build and execute the program and query your {{% cloud-name %}} cluster,
enter the following commands in your terminal:
```sh
dotnet build
```
```sh
dotnet run
```
<!------------------------------ END C# CONTENT ------------------------------->
{{% /tab-content %}}
{{< /tabs-wrapper >}}

View File

@ -153,6 +153,7 @@ credentials (**url**, **organization**, and **token**) are provided by
[Python](#)
[Go](#)
[Node.js](#)
[C#](#)
{{% /tabs %}}
{{% tab-content %}}
<!------------------------------- BEGIN TELEGRAF CONTENT ------------------------------>
@ -704,7 +705,165 @@ To write data to {{% cloud-name %}} using Node.js, use the
{{% /influxdb/custom-timestamps %}}
<!------------------------------- END NODE.JS CONTENT ------------------------------>
{{% /tab-content %}}
{{% tab-content %}}
<!---------------------------- BEGIN C# CONTENT --------------------------->
{{% influxdb/custom-timestamps %}}
1. If you haven't already, follow the [Microsoft.com download instructions](https://dotnet.microsoft.com/en-us/download) to install .NET and the `dotnet` CLI.
2. In your terminal, create an executable C# project using the .NET **console** template.
```sh
dotnet new console --name influxdb_csharp_client
```
3. Change into the generated `influxdb_csharp_client` directory.
```sh
cd influxdb_csharp_client
```
4. Run the following command to install the latest version of the InfluxDB v3 C# client library.
```sh
dotnet add package InfluxDB3.Client
```
5. In your editor, create a `Write.cs` file and enter the following sample code:
```c#
// Write.cs
using System;
using System.Threading.Tasks;
using InfluxDB3.Client;
using InfluxDB3.Client.Query;
namespace InfluxDBv3;
public class Write
{
/**
* Writes line protocol to InfluxDB using the C# .NET client
* library.
*/
public static async Task WriteLines()
{
// Set InfluxDB credentials
const string hostUrl = "https://cloud2.influxdata.com";
string? database = "get-started";
/**
* INFLUX_TOKEN is an environment variable you assigned to your
* database token value.
*/
string? authToken = System.Environment
.GetEnvironmentVariable("INFLUX_TOKEN");
// Instantiate the InfluxDB client with credentials.
using var client = new InfluxDBClient(
hostUrl, authToken: authToken, database: database);
/**
* Define an array of line protocol strings to write.
* Include an additional backslash to preserve backslashes
* and prevent interpretation of escape sequences---for example,
* escaped spaces in tag values.
*/
string[] lines = new string[] {
"home,room=Living\\ Room temp=21.1,hum=35.9,co=0i 1641024000",
"home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000",
"home,room=Living\\ Room temp=21.4,hum=35.9,co=0i 1641027600",
"home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600",
"home,room=Living\\ Room temp=21.8,hum=36.0,co=0i 1641031200",
"home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200",
"home,room=Living\\ Room temp=22.2,hum=36.0,co=0i 1641034800",
"home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800",
"home,room=Living\\ Room temp=22.2,hum=35.9,co=0i 1641038400",
"home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400",
"home,room=Living\\ Room temp=22.4,hum=36.0,co=0i 1641042000",
"home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000",
"home,room=Living\\ Room temp=22.3,hum=36.1,co=0i 1641045600",
"home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600",
"home,room=Living\\ Room temp=22.3,hum=36.1,co=1i 1641049200",
"home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200",
"home,room=Living\\ Room temp=22.4,hum=36.0,co=4i 1641052800",
"home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800",
"home,room=Living\\ Room temp=22.6,hum=35.9,co=5i 1641056400",
"home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400",
"home,room=Living\\ Room temp=22.8,hum=36.2,co=9i 1641060000",
"home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000",
"home,room=Living\\ Room temp=22.5,hum=36.3,co=14i 1641063600",
"home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600",
"home,room=Living\\ Room temp=22.2,hum=36.4,co=17i 1641067200",
"home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200"
};
// Write each record separately.
foreach (string line in lines)
{
// Write the record to InfluxDB with timestamp precision in seconds.
await client.WriteRecordAsync(
record: line, precision: WritePrecision.S);
Console.WriteLine(
"Data has been written successfully: {0,-30}", line);
}
}
}
```
The sample does the following:
1. Calls the `new InfluxDBClient()` constructor to instantiate a client configured
with InfluxDB credentials.
- **hostUrl**: your {{% cloud-name %}} cluster URL
- **database**: the name of the {{% cloud-name %}} database to write to
- **authToken**: an [database token](/influxdb/cloud-dedicated/admin/tokens/) with _write_ access to the specified bucket.
_For security reasons, we recommend setting this as an environment variable rather than including the raw token string._
_Instantiating the client with the `using` statement ensures that the client is disposed of when it's no longer needed._
2. Defines an array of line protocol strings where each string represents a data record.
3. Calls the client's `WriteRecordAsync()` method to write each line protocol record to InfluxDB.
**Because the timestamps in the sample line protocol are in second
precision, the example passes the [`WritePrecision.S` enum value](https://github.com/InfluxCommunity/influxdb3-csharp/blob/main/Client/Write/WritePrecision.cs)
to the `precision:` option in order to set the timestamp precision to seconds.**
6. In your editor, open the `Program.cs` file and replace its contents with the following:
```c#
// Program.cs
using System;
using System.Threading.Tasks;
namespace InfluxDBv3;
public class Program
{
public static async Task Main()
{
await Write.WriteLineProtocol();
}
}
```
The `Program` class shares the same `InfluxDBv3` namespace as the `Write` class you defined in the preceding step
and defines a `Main()` function that calls `Write.WriteLineProtocol()`.
The `dotnet` CLI recognizes `Program.Main()` as the entry point for your program.
7. To build and execute the program and write the line protocol to your {{% cloud-name %}} database, enter the following commands in your terminal:
```sh
dotnet build
```
```sh
dotnet run
```
<!---------------------------- END C# CONTENT --------------------------->
{{% /influxdb/custom-timestamps %}}
{{% /tab-content %}}
{{< /tabs-wrapper >}}
If successful, the output is the success message; otherwise, error details and the failure message.
@ -749,10 +908,4 @@ If successful, the output is the success message; otherwise, error details and t
**Congratulations!** You have written data to InfluxDB.
With data now stored in InfluxDB, let's query it.
<!-- The method described
above is the manual way of writing data, but there are other options available:
- [Write data to InfluxDB using no-code solutions](/influxdb/cloud-iox/write-data/no-code/)
- [Write data to InfluxDB using developer tools](/influxdb/cloud-iox/write-data/developer-tools/) -->
{{< page-nav prev="/influxdb/cloud-dedicated/get-started/setup/" next="/influxdb/cloud-dedicated/get-started/query/" keepTab=true >}}

View File

@ -103,6 +103,8 @@ SELECT * FROM home
```
##### Select all data in a measurement within time bounds
{{% influxdb/custom-timestamps %}}
```sql
SELECT
*
@ -112,6 +114,7 @@ WHERE
time >= '2022-01-01T08:00:00Z'
AND time <= '2022-01-01T20:00:00Z'
```
{{% /influxdb/custom-timestamps %}}
##### Select a specific field within relative time bounds
```sql
@ -201,6 +204,7 @@ credentials (**url**, **organization**, and **token**) are provided by
[influx3 CLI](#influx3-cli)
[Python](#)
[Go](#)
[C#](#)
{{% /tabs %}}
{{% tab-content %}}
@ -382,7 +386,7 @@ _If your project's virtual environment is already running, skip to step 3._
Flight request to InfluxDB, queries the database, retrieves result data from the endpoint, and then returns a
[pyarrow.Table](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table)
assigned to the `table` variable.
5. Calls the [`to_pandas()` method](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.to_pandas)
to convert the Arrow table to a [pandas DataFrame](https://arrow.apache.org/docs/python/pandas.html).
@ -451,6 +455,7 @@ _If your project's virtual environment is already running, skip to step 3._
"fmt"
"io"
"os"
"time"
"text/tabwriter"
"github.com/apache/arrow/go/v12/arrow"
@ -459,15 +464,18 @@ _If your project's virtual environment is already running, skip to step 3._
func Query() error {
// INFLUX_TOKEN is an environment variable you created for your API read token
// INFLUX_TOKEN is an environment variable you created
// for your API read token.
token := os.Getenv("INFLUX_TOKEN")
database := "get-started"
// Instantiate the client.
client, err := influx.New(influx.Configs{
HostURL: "https://cloud2.influxdata.com",
AuthToken: token,
})
// Close the client when the function returns.
defer func (client *influx.Client) {
err := client.Close()
if err != nil {
@ -475,12 +483,13 @@ _If your project's virtual environment is already running, skip to step 3._
}
}(client)
// Execute query
// Define the query.
query := `SELECT *
FROM home
WHERE time >= '2022-01-02T08:00:00Z'
AND time <= '2022-01-02T20:00:00Z'`
// Execute the query.
iterator, err := client.Query(context.Background(), database, query)
if err != nil {
@ -491,10 +500,16 @@ _If your project's virtual environment is already running, skip to step 3._
w.Init(os.Stdout, 0, 8, 0, '\t', 0)
fmt.Fprintln(w, "time\troom\ttemp\thum\tco")
// Iterate over rows and prints column values in table format.
for iterator.Next() {
row := iterator.Value()
day := (row["time"].(arrow.Timestamp)).ToTime(arrow.TimeUnit(arrow.Nanosecond))
fmt.Fprintf(w, "%s\t%s\t%.2f\t%.2f\t%d\n", day, row["room"], row["temp"], row["hum"], row["co"])
// Use Go arrow and time packages to format unix timestamp
// as a time with timezone layout (RFC3339).
time := (row["time"].(arrow.Timestamp)).
ToTime(arrow.TimeUnit(arrow.Nanosecond)).
Format(time.RFC3339)
fmt.Fprintf(w, "%s\t%s\t%d\t%.2f\t%.2f\n",
time, row["room"], row["co"], row["hum"], row["temp"])
}
w.Flush()
@ -518,7 +533,7 @@ _If your project's virtual environment is already running, skip to step 3._
1. Instantiates `influx.Client` with InfluxDB credentials.
- **HostURL**: your {{% cloud-name %}} region URL.
- **HostURL**: your {{% cloud-name %}} region URL
- **AuthToken**: an [API token](/influxdb/cloud-serverless/admin/tokens/) with _read_ access to the specified bucket.
_For security reasons, we recommend setting this as an environment
variable rather than including the raw token string._
@ -527,7 +542,7 @@ _If your project's virtual environment is already running, skip to step 3._
3. Defines a string variable for the SQL query.
4. Calls the `influx.Client.query()` method to send the query request with the database (bucket) name and SQL string. The `query()` method returns an `iterator` for data in the response stream.
5. Iterates over rows and prints the data in table format to stdout.
5. Iterates over rows, formats the timestamp as an[RFC3339 timestamp](/influxdb/cloud-serverless/reference/glossary/#rfc3339-timestamp), and prints the data in table format to stdout.
3. In your editor, open the `main.go` file you created in the
[Write data section](/influxdb/cloud-serverless/get-started/write/?t=Go#write-line-protocol-to-influxdb) and insert code to call the `Query()` function--for example:
@ -578,6 +593,123 @@ time room co hum temp
{{< /expand-wrapper >}}
{{% /influxdb/custom-timestamps %}}
<!------------------------------ END GO CONTENT ------------------------------->
{{% /tab-content %}}
{{% tab-content %}}
<!------------------------------ BEGIN C# CONTENT ----------------------------->
```c#
// Query.cs
using System;
using System.Threading.Tasks;
using InfluxDB3.Client;
using InfluxDB3.Client.Query;
namespace InfluxDBv3;
public class Query
{
/**
* Queries an InfluxDB database (bucket) using the C# .NET client
* library.
**/
public static async Task QuerySQL()
{
/** Set InfluxDB credentials **/
const string hostUrl = "https://cloud2.influxdata.com";
string? database = "get-started";
/** INFLUX_TOKEN is an environment variable you assigned to your
* API token value.
**/
string? authToken = System.Environment
.GetEnvironmentVariable("INFLUX_TOKEN");
/**
* Instantiate the InfluxDB client with credentials.
**/
using var client = new InfluxDBClient(
hostUrl, authToken: authToken, database: database);
const string sql = @"
SELECT time, room, temp, hum, co
FROM home
WHERE time >= '2022-01-02T08:00:00Z'
AND time <= '2022-01-02T20:00:00Z'
";
Console.WriteLine("{0,-30}{1,-15}{2,-15}{3,-15}{4,-15}",
"time", "room", "temp", "hum", "co");
await foreach (var row in client.Query(query: sql))
{
{
/**
* Iterate over rows and print column values in table format.
* Format the timestamp as sortable UTC format.
*/
Console.WriteLine("{0,-30:u}{1,-15}{2,-15}{3,-15}{4,-15}",
row[0], row[1], row[2], row[3], row[4]);
}
}
Console.WriteLine();
}
}
```
The sample code does the following:
1. Imports the following classes:
- `System`
- `System.Threading.Tasks`;
- `InfluxDB3.Client`;
- `InfluxDB3.Client.Query`;
2. Defines a `Query` class with a `QuerySQL()` method that does the following:
1. Calls the `new InfluxDBClient()` constructor to instantiate a client configured
with InfluxDB credentials.
- **hostURL**: your {{% cloud-name %}} region URL.
- **authToken**: an [API token](/influxdb/cloud-serverless/admin/tokens/) with _read_ access to the specified bucket.
_For security reasons, we recommend setting this as an environment variable rather than including the raw token string._
- **database**: the name of the {{% cloud-name %}} bucket to query
2. Defines a string variable for the SQL query.
3. Calls the `InfluxDBClient.Query()` method to send the query request with the SQL string. `Query()` returns batches of rows from the response stream as a two-dimensional array--an array of rows in which each row is an array of values.
4. Iterates over rows and prints the data in table format to stdout.
3. In your editor, open the `Program.cs` file you created in the
[Write data section](/influxdb/cloud-serverless/get-started/write/?t=C%23#write-line-protocol-to-influxdb) and insert code to call the `Query()` function--for example:
```c#
// Program.cs
using System;
using System.Threading.Tasks;
namespace InfluxDBv3;
public class Program
{
public static async Task Main()
{
await Write.WriteLineProtocol();
await Query.QuerySQL();
}
}
```
4. To build and execute the program and query {{% cloud-name %}},
enter the following commands in your terminal:
```sh
dotnet build
```
```sh
dotnet run
```
<!------------------------------ END C# CONTENT ------------------------------->
{{% /tab-content %}}
{{< /tabs-wrapper >}}

View File

@ -432,7 +432,6 @@ dependencies to your current project.
# host is the URL without protocol or trailing slash
client = InfluxDBClient3(
host='cloud2.influxdata.com',
org='',
token=token,
database='get-started'
)
@ -476,8 +475,8 @@ dependencies to your current project.
configured with the following credentials:
- **host**: {{% cloud-name %}} region hostname (URL without protocol or trailing slash)
- **org**: an empty or arbitrary string (InfluxDB ignores this parameter)
- **token**: an InfluxDB [API token](/influxdb/cloud-serverless/admin/tokens/) with write access to the target bucket
- **token**: an InfluxDB [API token](/influxdb/cloud-serverless/admin/tokens/) with _write_ access to the specified bucket.
_For security reasons, we recommend setting this as an environment variable rather than including the raw token string._
- **database**: the name of the {{% cloud-name %}} bucket to write to
3. Defines a list of line protocol strings where each string represents a data record.
@ -503,7 +502,7 @@ dependencies to your current project.
{{% influxdb/custom-timestamps %}}
To write data to {{% cloud-name %}} using Go, use the
[influxdb-client-go module](https://github.com/influxdata/influxdb-client-go).
InfluxDB v3 [influxdb3-go client library package](https://github.com/InfluxCommunity/influxdb3-go).
1. Inside of your project directory, create a new module directory and navigate into it.
@ -782,6 +781,165 @@ To write data to {{% cloud-name %}} using Node.js, use the
{{% /influxdb/custom-timestamps %}}
<!------------------------------- END NODE.JS CONTENT ------------------------------>
{{% /tab-content %}}
{{% tab-content %}}
<!---------------------------- BEGIN C# CONTENT --------------------------->
{{% influxdb/custom-timestamps %}}
1. If you haven't already, follow the [Microsoft.com download instructions](https://dotnet.microsoft.com/en-us/download) to install .NET and the `dotnet` CLI.
2. In your terminal, create an executable C# project using the .NET **console** template.
```sh
dotnet new console --name influxdb_csharp_client
```
3. Change into the generated `influxdb_csharp_client` directory.
```sh
cd influxdb_csharp_client
```
4. Run the following command to install the latest version of the InfluxDB v3 C# client library.
```sh
dotnet add package InfluxDB3.Client
```
5. In your editor, create a `Write.cs` file and enter the following sample code:
```c#
// Write.cs
using System;
using System.Threading.Tasks;
using InfluxDB3.Client;
using InfluxDB3.Client.Query;
namespace InfluxDBv3;
public class Write
{
/**
* Writes line protocol to InfluxDB using the C# .NET client
* library.
*/
public static async Task WriteLines()
{
// Set InfluxDB credentials
const string hostUrl = "https://cloud2.influxdata.com";
string? database = "get-started";
/**
* INFLUX_TOKEN is an environment variable you assigned to your
* API token value.
*/
string? authToken = System.Environment
.GetEnvironmentVariable("INFLUX_TOKEN");
// Instantiate the InfluxDB client with credentials.
using var client = new InfluxDBClient(
hostUrl, authToken: authToken, database: database);
/**
* Define an array of line protocol strings to write.
* Include an additional backslash to preserve backslashes
* and prevent interpretation of escape sequences---for example,
* escaped spaces in tag values.
*/
string[] lines = new string[] {
"home,room=Living\\ Room temp=21.1,hum=35.9,co=0i 1641024000",
"home,room=Kitchen temp=21.0,hum=35.9,co=0i 1641024000",
"home,room=Living\\ Room temp=21.4,hum=35.9,co=0i 1641027600",
"home,room=Kitchen temp=23.0,hum=36.2,co=0i 1641027600",
"home,room=Living\\ Room temp=21.8,hum=36.0,co=0i 1641031200",
"home,room=Kitchen temp=22.7,hum=36.1,co=0i 1641031200",
"home,room=Living\\ Room temp=22.2,hum=36.0,co=0i 1641034800",
"home,room=Kitchen temp=22.4,hum=36.0,co=0i 1641034800",
"home,room=Living\\ Room temp=22.2,hum=35.9,co=0i 1641038400",
"home,room=Kitchen temp=22.5,hum=36.0,co=0i 1641038400",
"home,room=Living\\ Room temp=22.4,hum=36.0,co=0i 1641042000",
"home,room=Kitchen temp=22.8,hum=36.5,co=1i 1641042000",
"home,room=Living\\ Room temp=22.3,hum=36.1,co=0i 1641045600",
"home,room=Kitchen temp=22.8,hum=36.3,co=1i 1641045600",
"home,room=Living\\ Room temp=22.3,hum=36.1,co=1i 1641049200",
"home,room=Kitchen temp=22.7,hum=36.2,co=3i 1641049200",
"home,room=Living\\ Room temp=22.4,hum=36.0,co=4i 1641052800",
"home,room=Kitchen temp=22.4,hum=36.0,co=7i 1641052800",
"home,room=Living\\ Room temp=22.6,hum=35.9,co=5i 1641056400",
"home,room=Kitchen temp=22.7,hum=36.0,co=9i 1641056400",
"home,room=Living\\ Room temp=22.8,hum=36.2,co=9i 1641060000",
"home,room=Kitchen temp=23.3,hum=36.9,co=18i 1641060000",
"home,room=Living\\ Room temp=22.5,hum=36.3,co=14i 1641063600",
"home,room=Kitchen temp=23.1,hum=36.6,co=22i 1641063600",
"home,room=Living\\ Room temp=22.2,hum=36.4,co=17i 1641067200",
"home,room=Kitchen temp=22.7,hum=36.5,co=26i 1641067200"
};
// Write each record separately.
foreach (string line in lines)
{
// Write the record to InfluxDB with timestamp precision in seconds.
await client.WriteRecordAsync(
record: line, precision: WritePrecision.S);
Console.WriteLine(
"Data has been written successfully: {0,-30}", line);
}
}
}
```
The sample does the following:
1. Calls the `new InfluxDBClient()` constructor to instantiate a client configured
with InfluxDB credentials.
- **hostUrl**: your {{% cloud-name %}} region URL
- **database**: the name of the {{% cloud-name %}} bucket to write to
- **authToken**: an [API token](/influxdb/cloud-serverless/admin/tokens/) with _write_ access to the specified bucket.
_For security reasons, we recommend setting this as an environment variable rather than including the raw token string._
_Instantiating the client with the `using` statement ensures that the client is disposed of when it's no longer needed._
2. Defines an array of line protocol strings where each string represents a data record.
3. Calls the client's `WriteRecordAsync()` method to write each line protocol record to InfluxDB.
**Because the timestamps in the sample line protocol are in second
precision, the example passes the [`WritePrecision.S` enum value](https://github.com/InfluxCommunity/influxdb3-csharp/blob/main/Client/Write/WritePrecision.cs)
to the `precision:` option in order to set the timestamp precision to seconds.**
6. In your editor, open the `Program.cs` file and replace its contents with the following:
```c#
// Program.cs
using System;
using System.Threading.Tasks;
namespace InfluxDBv3;
public class Program
{
public static async Task Main()
{
await Write.WriteLineProtocol();
}
}
```
The `Program` class shares the same `InfluxDBv3` namespace as the `Write` class you defined in the preceding step
and defines a `Main()` function that calls `Write.WriteLineProtocol()`.
The `dotnet` CLI recognizes `Program.Main()` as the entry point for your program.
7. To build and execute the program and write the line protocol to your {{% cloud-name %}} bucket, enter the following commands in your terminal:
```sh
dotnet build
```
```sh
dotnet run
```
<!---------------------------- END C# CONTENT --------------------------->
{{% /influxdb/custom-timestamps %}}
{{% /tab-content %}}
{{< /tabs-wrapper >}}
If successful, the output is the success message; otherwise, error details and the failure message.
@ -826,10 +984,4 @@ If successful, the output is the success message; otherwise, error details and t
**Congratulations!** You have written data to InfluxDB.
With data now stored in InfluxDB, let's query it.
<!-- The method described
above is the manual way of writing data, but there are other options available:
- [Write data to InfluxDB using no-code solutions](/influxdb/cloud-serverless/write-data/no-code/)
- [Write data to InfluxDB using developer tools](/influxdb/cloud-serverless/write-data/developer-tools/) -->
{{< page-nav prev="/influxdb/cloud-serverless/get-started/setup/" next="/influxdb/cloud-serverless/get-started/query/" keepTab=true >}}