Skip to main content

Connect with C#

Create Project

dotnet new console -o example

Add C# TDengine Driver class lib

cd example
vim example.csproj

Add following ItemGroup and Task to your project file.

  <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup>
<DepDLLFiles Include="$(PkgTDengine_Connector)\runtimes\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(DepDLLFiles)" DestinationFolder="$(OutDir)" />
</Target>
dotnet add package TDengine.Connector

Config

Run this command in your terminal to save TDengine cloud endpoint and token as variable:

export TDENGINE_CLOUD_ENDPOINT="<cloud_endpoint>"
export TDENGINE_CLOUD_TOKEN="<cloud_token>"
IMPORTANT

Replace <cloud_endpoint> and <cloud_token> from the real TDengine Cloud DSN like https://cloud_endpoint?token=cloud_token. To obtain the real value, please log in TDengine Cloud and click "Programming" on the left menu, then select "C#".

Connect

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup>
<DepDLLFiles Include="$(PkgTDengine_Connector)\runtimes\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(DepDLLFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>

view source code

using System;
using System.Text;
using TDengine.Driver;
using TDengine.Driver.Client;

namespace Cloud.Examples
{
public class ConnectExample
{
static void Main(string[] args)
{
var cloudEndPoint = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_ENDPOINT");
var cloudToken = Environment.GetEnvironmentVariable("TDENGINE_CLOUD_TOKEN");
var connectionString = $"protocol=WebSocket;host={cloudEndPoint};port=443;useSSL=true;token={cloudToken};";
// Connect to TDengine server using WebSocket
var builder = new ConnectionStringBuilder(connectionString);
try
{
// Open connection with using block, it will close the connection automatically
using (var client = DbDriver.Open(builder))
{
Console.WriteLine("Connected to " + builder.ToString() + " successfully.");
}
}
catch (TDengineError e)
{
// handle TDengine error
Console.WriteLine("Failed to connect to " + builder.ToString() + "; ErrCode:" + e.Code +
"; ErrMessage: " + e.Error);
throw;
}
catch (Exception e)
{
// handle other exceptions
Console.WriteLine("Failed to connect to " + builder.ToString() + "; Err:" + e.Message);
throw;
}
}
}
}

view source code

The client connection is then established. For how to write data and query data, please refer to Insert and Query.

For more details about how to write or query data via REST API, please check REST API.