refactor(c#): refactor c# connector to v3.1.0

This commit is contained in:
t_max 2023-12-14 16:58:18 +08:00
parent 394dc6c725
commit eab4861370
39 changed files with 2533 additions and 1358 deletions

View File

@ -177,7 +177,7 @@ Just need to add the reference to [TDengine.Connector](https://www.nuget.org/pac
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.0" /> <PackageReference Include="TDengine.Connector" Version="3.1.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,3 +0,0 @@
```csharp
{{#include docs/examples/csharp/asyncQuery/Program.cs}}
```

View File

@ -15,7 +15,6 @@ import CQuery from "./_c.mdx";
import PhpQuery from "./_php.mdx"; import PhpQuery from "./_php.mdx";
import PyAsync from "./_py_async.mdx"; import PyAsync from "./_py_async.mdx";
import NodeAsync from "./_js_async.mdx"; import NodeAsync from "./_js_async.mdx";
import CsAsync from "./_cs_async.mdx";
import CAsync from "./_c_async.mdx"; import CAsync from "./_c_async.mdx";
## Introduction ## Introduction
@ -174,9 +173,6 @@ Please note that async query can only be used with a native connection.
<TabItem label="Python" value="python"> <TabItem label="Python" value="python">
<PyAsync /> <PyAsync />
</TabItem> </TabItem>
<TabItem label="C#" value="csharp">
<CsAsync />
</TabItem>
<TabItem label="C" value="c"> <TabItem label="C" value="c">
<CAsync /> <CAsync />
</TabItem> </TabItem>

View File

@ -248,23 +248,23 @@ function close()
<TabItem value="C#" label="C#"> <TabItem value="C#" label="C#">
```csharp ```csharp
class ConsumerBuilder<TValue>
ConsumerBuilder(IEnumerable<KeyValuePair<string, string>> config) ConsumerBuilder(IEnumerable<KeyValuePair<string, string>> config)
virtual IConsumer Build() public IConsumer<TValue> Build()
Consumer(ConsumerBuilder builder)
void Subscribe(IEnumerable<string> topics) void Subscribe(IEnumerable<string> topics)
void Subscribe(string topic) void Subscribe(string topic)
ConsumeResult Consume(int millisecondsTimeout) ConsumeResult<TValue> Consume(int millisecondsTimeout)
List<string> Subscription() List<string> Subscription()
void Unsubscribe() void Unsubscribe()
void Commit(ConsumeResult consumerResult) List<TopicPartitionOffset> Commit()
void Close() void Close()
``` ```
@ -500,25 +500,19 @@ let consumer = taos.consumer({
<TabItem value="C#" label="C#"> <TabItem value="C#" label="C#">
```csharp ```csharp
using TDengineTMQ; var cfg = new Dictionary<string, string>()
{
// Create consumer groups on demand (GourpID) and enable automatic commits (EnableAutoCommit), { "group.id", "group1" },
// an automatic commit interval (AutoCommitIntervalMs), and a username (TDConnectUser) and password (TDConnectPasswd) { "auto.offset.reset", "latest" },
var cfg = new ConsumerConfig { "td.connect.ip", "127.0.0.1" },
{ { "td.connect.user", "root" },
EnableAutoCommit = "true" { "td.connect.pass", "taosdata" },
AutoCommitIntervalMs = "1000" { "td.connect.port", "6030" },
GourpId = "TDengine-TMQ-C#", { "client.id", "tmq_example" },
TDConnectUser = "root", { "enable.auto.commit", "true" },
TDConnectPasswd = "taosdata", { "msg.with.table.name", "false" },
AutoOffsetReset = "latest" };
MsgWithTableName = "true", var consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
TDConnectIp = "127.0.0.1",
TDConnectPort = "6030"
};
var consumer = new ConsumerBuilder(cfg).Build();
``` ```
</TabItem> </TabItem>
@ -747,10 +741,12 @@ while(true){
## Consume data ## Consume data
while (true) while (true)
{ {
var consumerRes = consumer.Consume(100); using (var result = consumer.Consume(500))
// process ConsumeResult {
ProcessMsg(consumerRes); if (result == null) continue;
consumer.Commit(consumerRes); ProcessMsg(result);
consumer.Commit();
}
} }
``` ```

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
.vs .vs
asyncQuery/bin .idea
connect/bin connect/bin
influxdbLine/bin influxdbLine/bin
optsJSON/bin optsJSON/bin
@ -12,7 +12,6 @@ wsConnect/bin
wsInsert/bin wsInsert/bin
wsQuery/bin wsQuery/bin
wsStmt/bin wsStmt/bin
asyncQuery/obj
connect/obj connect/obj
influxdbLine/obj influxdbLine/obj
optsJSON/obj optsJSON/obj

View File

@ -1,111 +0,0 @@
using System;
using System.Collections.Generic;
using TDengineDriver;
using TDengineDriver.Impl;
using System.Runtime.InteropServices;
namespace TDengineExample
{
public class AsyncQueryExample
{
static void Main()
{
IntPtr conn = GetConnection();
try
{
QueryAsyncCallback queryAsyncCallback = new QueryAsyncCallback(QueryCallback);
TDengine.QueryAsync(conn, "select * from meters", queryAsyncCallback, IntPtr.Zero);
Thread.Sleep(2000);
}
finally
{
TDengine.Close(conn);
}
}
static void QueryCallback(IntPtr param, IntPtr taosRes, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
FetchRawBlockAsyncCallback fetchRowAsyncCallback = new FetchRawBlockAsyncCallback(FetchRawBlockCallback);
TDengine.FetchRawBlockAsync(taosRes, fetchRowAsyncCallback, param);
}
else
{
throw new Exception($"async query data failed,code:{code},reason:{TDengine.Error(taosRes)}");
}
}
// Iteratively call this interface until "numOfRows" is no greater than 0.
static void FetchRawBlockCallback(IntPtr param, IntPtr taosRes, int numOfRows)
{
if (numOfRows > 0)
{
Console.WriteLine($"{numOfRows} rows async retrieved");
IntPtr pdata = TDengine.GetRawBlock(taosRes);
List<TDengineMeta> metaList = TDengine.FetchFields(taosRes);
List<object> dataList = LibTaos.ReadRawBlock(pdata, metaList, numOfRows);
for (int i = 0; i < dataList.Count; i++)
{
if (i != 0 && (i + 1) % metaList.Count == 0)
{
Console.WriteLine("{0}\t|", dataList[i]);
}
else
{
Console.Write("{0}\t|", dataList[i]);
}
}
Console.WriteLine("");
TDengine.FetchRawBlockAsync(taosRes, FetchRawBlockCallback, param);
}
else
{
if (numOfRows == 0)
{
Console.WriteLine("async retrieve complete.");
}
else
{
throw new Exception($"FetchRawBlockCallback callback error, error code {numOfRows}");
}
TDengine.FreeResult(taosRes);
}
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "power";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
}
}
}
// //output:
// // Connect to TDengine success
// // 8 rows async retrieved
// // 1538548685500 | 11.8 | 221 | 0.28 | california.losangeles | 2 |
// // 1538548696600 | 13.4 | 223 | 0.29 | california.losangeles | 2 |
// // 1538548685000 | 10.8 | 223 | 0.29 | california.losangeles | 3 |
// // 1538548686500 | 11.5 | 221 | 0.35 | california.losangeles | 3 |
// // 1538548685000 | 10.3 | 219 | 0.31 | california.sanfrancisco | 2 |
// // 1538548695000 | 12.6 | 218 | 0.33 | california.sanfrancisco | 2 |
// // 1538548696800 | 12.3 | 221 | 0.31 | california.sanfrancisco | 2 |
// // 1538548696650 | 10.3 | 218 | 0.25 | california.sanfrancisco | 3 |
// // async retrieve complete.

View File

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<StartupObject>TDengineExample.AsyncQueryExample</StartupObject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" />
</ItemGroup>
</Project>

View File

@ -1,4 +1,5 @@
using TDengineDriver; using TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
@ -7,23 +8,11 @@ namespace TDengineExample
{ {
static void Main(String[] args) static void Main(String[] args)
{ {
string host = "localhost"; var builder = new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
short port = 6030; using (var client = DbDriver.Open(builder))
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{ {
throw new Exception("Connect to TDengine failed"); Console.WriteLine("connected");
} }
else
{
Console.WriteLine("Connect to TDengine success");
}
TDengine.Close(conn);
TDengine.Cleanup();
} }
} }
} }

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -3,8 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105 VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "asyncquery", "asyncQuery\asyncquery.csproj", "{E2A5F00C-14E7-40E1-A2DE-6AB2975616D3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "connect", "connect\connect.csproj", "{CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "connect", "connect\connect.csproj", "{CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "influxdbline", "influxdbLine\influxdbline.csproj", "{6A24FB80-1E3C-4E2D-A5AB-914FA583874D}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "influxdbline", "influxdbLine\influxdbline.csproj", "{6A24FB80-1E3C-4E2D-A5AB-914FA583874D}"
@ -38,10 +36,6 @@ Global
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E2A5F00C-14E7-40E1-A2DE-6AB2975616D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E2A5F00C-14E7-40E1-A2DE-6AB2975616D3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E2A5F00C-14E7-40E1-A2DE-6AB2975616D3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E2A5F00C-14E7-40E1-A2DE-6AB2975616D3}.Release|Any CPU.Build.0 = Release|Any CPU
{CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}.Release|Any CPU.ActiveCfg = Release|Any CPU {CCC5042D-93FC-4AE0-B2F6-7E692FD476B7}.Release|Any CPU.ActiveCfg = Release|Any CPU

View File

@ -1,4 +1,5 @@
using TDengineDriver; using TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
@ -6,60 +7,23 @@ namespace TDengineExample
{ {
static void Main() static void Main()
{ {
IntPtr conn = GetConnection(); var builder =
PrepareDatabase(conn); new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
using (var client = DbDriver.Open(builder))
{
client.Exec("CREATE DATABASE test WAL_RETENTION_PERIOD 3600");
client.Exec("use test");
string[] lines = { string[] lines = {
"meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
"meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
"meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
"meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250" "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250"
}; };
IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS); client.SchemalessInsert(lines,
if (TDengine.ErrorNo(res) != 0) TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL,
{ TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
throw new Exception("SchemalessInsert failed since " + TDengine.Error(res));
}
else
{
int affectedRows = TDengine.AffectRows(res);
Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
}
TDengine.FreeResult(res);
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
}
static void PrepareDatabase(IntPtr conn)
{
IntPtr res = TDengine.Query(conn, "CREATE DATABASE test WAL_RETENTION_PERIOD 3600");
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("failed to create database, reason: " + TDengine.Error(res));
}
res = TDengine.Query(conn, "USE test");
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("failed to change database, reason: " + TDengine.Error(res));
} }
} }
} }
} }

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,68 +1,27 @@
using TDengineDriver; using TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
internal class OptsJsonExample internal class OptsJsonExample
{ {
static void Main() public static void Main(string[] args)
{ {
IntPtr conn = GetConnection(); var builder =
try new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
using (var client = DbDriver.Open(builder))
{ {
PrepareDatabase(conn); client.Exec("CREATE DATABASE test WAL_RETENTION_PERIOD 3600");
string[] lines = { "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + client.Exec("use test");
string[] lines =
{
"[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," +
" {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " +
"{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," +
" {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}]" " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}]"
}; };
client.SchemalessInsert(lines, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
IntPtr res = TDengine.SchemalessInsert(conn, lines, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED); TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("SchemalessInsert failed since " + TDengine.Error(res));
}
else
{
int affectedRows = TDengine.AffectRows(res);
Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
}
TDengine.FreeResult(res);
}
finally
{
TDengine.Close(conn);
}
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
}
static void PrepareDatabase(IntPtr conn)
{
IntPtr res = TDengine.Query(conn, "CREATE DATABASE test WAL_RETENTION_PERIOD 3600");
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("failed to create database, reason: " + TDengine.Error(res));
}
res = TDengine.Query(conn, "USE test");
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("failed to change database, reason: " + TDengine.Error(res));
} }
} }
} }

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,15 +1,18 @@
using TDengineDriver; using TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
internal class OptsTelnetExample internal class OptsTelnetExample
{ {
static void Main() public static void Main(string[] args)
{ {
IntPtr conn = GetConnection(); var builder =
try new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
using (var client = DbDriver.Open(builder))
{ {
PrepareDatabase(conn); client.Exec("CREATE DATABASE test WAL_RETENTION_PERIOD 3600");
client.Exec("USE test");
string[] lines = { string[] lines = {
"meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2",
"meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2",
@ -20,53 +23,9 @@ namespace TDengineExample
"meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3",
"meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3",
}; };
IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED); client.SchemalessInsert(lines,
if (TDengine.ErrorNo(res) != 0) TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL,
{ TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
throw new Exception("SchemalessInsert failed since " + TDengine.Error(res));
}
else
{
int affectedRows = TDengine.AffectRows(res);
Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
}
TDengine.FreeResult(res);
}
catch
{
TDengine.Close(conn);
}
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
}
static void PrepareDatabase(IntPtr conn)
{
IntPtr res = TDengine.Query(conn, "CREATE DATABASE test WAL_RETENTION_PERIOD 3600");
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("failed to create database, reason: " + TDengine.Error(res));
}
res = TDengine.Query(conn, "USE test");
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception("failed to change database, reason: " + TDengine.Error(res));
} }
} }
} }

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,80 +1,35 @@
using TDengineDriver; using System.Text;
using TDengineDriver.Impl; using TDengine.Driver;
using System.Runtime.InteropServices; using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
internal class QueryExample internal class QueryExample
{ {
static void Main() public static void Main(string[] args)
{
var builder = new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
using (var client = DbDriver.Open(builder))
{ {
IntPtr conn = GetConnection();
try try
{ {
// run query client.Exec("use power");
IntPtr res = TDengine.Query(conn, "SELECT * FROM meters LIMIT 2"); string query = "SELECT * FROM meters";
if (TDengine.ErrorNo(res) != 0) using (var rows = client.Query(query))
{ {
throw new Exception("Failed to query since: " + TDengine.Error(res)); while (rows.Read())
}
// get filed count
int fieldCount = TDengine.FieldCount(res);
Console.WriteLine("fieldCount=" + fieldCount);
// print column names
List<TDengineMeta> metas = LibTaos.GetMeta(res);
for (int i = 0; i < metas.Count; i++)
{ {
Console.Write(metas[i].name + "\t"); Console.WriteLine(
$"{((DateTime)rows.GetValue(0)):yyyy-MM-dd HH:mm:ss.fff}, {rows.GetValue(1)}, {rows.GetValue(2)}, {rows.GetValue(3)}, {rows.GetValue(4)}, {Encoding.UTF8.GetString((byte[])rows.GetValue(5))}");
} }
Console.WriteLine(); }
}
// print values catch (Exception e)
List<Object> resData = LibTaos.GetData(res);
for (int i = 0; i < resData.Count; i++)
{ {
Console.Write($"|{resData[i].ToString()} \t"); Console.WriteLine(e.ToString());
if (((i + 1) % metas.Count == 0)) throw;
{
Console.WriteLine("");
} }
} }
Console.WriteLine();
// Free result after use
TDengine.FreeResult(res);
}
finally
{
TDengine.Close(conn);
}
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "power";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
} }
} }
} }
// output:
// Connect to TDengine success
// fieldCount=6
// ts current voltage phase location groupid
// 1648432611249 10.3 219 0.31 California.SanFrancisco 2
// 1648432611749 12.6 218 0.33 California.SanFrancisco 2

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,69 +1,47 @@
using TDengineDriver; using System.Text;
using TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
internal class SQLInsertExample internal class SQLInsertExample
{ {
static void Main() public static void Main(string[] args)
{
var builder = new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
using (var client = DbDriver.Open(builder))
{ {
IntPtr conn = GetConnection();
try try
{ {
IntPtr res = TDengine.Query(conn, "CREATE DATABASE power WAL_RETENTION_PERIOD 3600"); client.Exec("create database power");
CheckRes(conn, res, "failed to create database"); client.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
res = TDengine.Query(conn, "USE power"); string insertQuery =
CheckRes(conn, res, "failed to change database"); "INSERT INTO " +
res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " +
CheckRes(conn, res, "failed to create stable"); "VALUES " +
var sql = "INSERT INTO d1001 USING meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) " + "('2023-10-03 14:38:05.000', 10.30000, 219, 0.31000) " +
"d1002 USING power.meters TAGS('California.SanFrancisco', 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) " + "('2023-10-03 14:38:15.000', 12.60000, 218, 0.33000) " +
"d1003 USING power.meters TAGS('California.LosAngeles', 2) VALUES('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) " + "('2023-10-03 14:38:16.800', 12.30000, 221, 0.31000) " +
"d1004 USING power.meters TAGS('California.LosAngeles', 3) VALUES('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000)('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"; "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " +
res = TDengine.Query(conn, sql); "VALUES " +
CheckRes(conn, res, "failed to insert data"); "('2023-10-03 14:38:16.650', 10.30000, 218, 0.25000) " +
int affectedRows = TDengine.AffectRows(res); "power.d1003 USING power.meters TAGS(2,'California.LosAngeles') " +
Console.WriteLine("affectedRows " + affectedRows); "VALUES " +
TDengine.FreeResult(res); "('2023-10-03 14:38:05.500', 11.80000, 221, 0.28000) " +
"('2023-10-03 14:38:16.600', 13.40000, 223, 0.29000) " +
"power.d1004 USING power.meters TAGS(3,'California.LosAngeles') " +
"VALUES " +
"('2023-10-03 14:38:05.000', 10.80000, 223, 0.29000) " +
"('2023-10-03 14:38:06.500', 11.50000, 221, 0.35000)";
client.Exec(insertQuery);
} }
finally catch (Exception e)
{ {
TDengine.Close(conn); Console.WriteLine(e.ToString());
} throw;
}
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
}
static void CheckRes(IntPtr conn, IntPtr res, String errorMsg)
{
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception($"{errorMsg} since: {TDengine.Error(res)}");
} }
} }
} }
} }
// output:
// Connect to TDengine success
// affectedRows 8

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,109 +1,38 @@
using TDengineDriver; using TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample namespace TDengineExample
{ {
internal class StmtInsertExample internal class StmtInsertExample
{ {
private static IntPtr conn; public static void Main(string[] args)
private static IntPtr stmt; {
static void Main() var builder = new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
using (var client = DbDriver.Open(builder))
{ {
conn = GetConnection();
try try
{ {
PrepareSTable(); client.Exec($"create database power");
// 1. init and prepare client.Exec(
stmt = TDengine.StmtInit(conn); "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
if (stmt == IntPtr.Zero) using (var stmt = client.StmtInit())
{ {
throw new Exception("failed to init stmt."); stmt.Prepare(
"Insert into power.d1001 using power.meters tags(2,'California.SanFrancisco') values(?,?,?,?)");
var ts = new DateTime(2023, 10, 03, 14, 38, 05, 000);
stmt.BindRow(new object[] { ts, (float)10.30000, (int)219, (float)0.31000 });
stmt.AddBatch();
stmt.Exec();
var affected = stmt.Affected();
Console.WriteLine($"affected rows: {affected}");
} }
int res = TDengine.StmtPrepare(stmt, "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)");
CheckStmtRes(res, "failed to prepare stmt");
// 2. bind table name and tags
TAOS_MULTI_BIND[] tags = new TAOS_MULTI_BIND[2] { TaosMultiBind.MultiBindBinary(new string[] { "California.SanFrancisco" }), TaosMultiBind.MultiBindInt(new int?[] { 2 }) };
res = TDengine.StmtSetTbnameTags(stmt, "d1001", tags);
CheckStmtRes(res, "failed to bind table name and tags");
// 3. bind values
TAOS_MULTI_BIND[] values = new TAOS_MULTI_BIND[4] {
TaosMultiBind.MultiBindTimestamp(new long[2] { 1648432611249, 1648432611749}),
TaosMultiBind.MultiBindFloat(new float?[2] { 10.3f, 12.6f}),
TaosMultiBind.MultiBindInt(new int?[2] { 219, 218}),
TaosMultiBind.MultiBindFloat(new float?[2]{ 0.31f, 0.33f})
};
res = TDengine.StmtBindParamBatch(stmt, values);
CheckStmtRes(res, "failed to bind params");
// 4. add batch
res = TDengine.StmtAddBatch(stmt);
CheckStmtRes(res, "failed to add batch");
// 5. execute
res = TDengine.StmtExecute(stmt);
CheckStmtRes(res, "failed to execute");
// 6. free
TaosMultiBind.FreeTaosBind(tags);
TaosMultiBind.FreeTaosBind(values);
} }
finally catch (Exception e)
{ {
TDengine.Close(conn); Console.WriteLine(e);
} throw;
}
static IntPtr GetConnection()
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
return conn;
}
static void PrepareSTable()
{
IntPtr res = TDengine.Query(conn, "CREATE DATABASE power WAL_RETENTION_PERIOD 3600");
CheckResPtr(res, "failed to create database");
res = TDengine.Query(conn, "USE power");
CheckResPtr(res, "failed to change database");
res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
CheckResPtr(res, "failed to create stable");
}
static void CheckStmtRes(int res, string errorMsg)
{
if (res != 0)
{
Console.WriteLine(errorMsg + ", " + TDengine.StmtErrorStr(stmt));
int code = TDengine.StmtClose(stmt);
if (code != 0)
{
throw new Exception($"failed to close stmt, {code} reason: {TDengine.StmtErrorStr(stmt)} ");
} }
} }
} }
static void CheckResPtr(IntPtr res, string errorMsg)
{
if (TDengine.ErrorNo(res) != 0)
{
throw new Exception(errorMsg + " since:" + TDengine.Error(res));
}
}
} }
} }

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,95 +1,72 @@
using System; 
using TDengineTMQ; using TDengine.Driver;
using TDengineDriver; using TDengine.Driver.Client;
using System.Runtime.InteropServices; using TDengine.TMQ;
namespace TMQExample namespace TMQExample
{ {
internal class SubscribeDemo internal class SubscribeDemo
{ {
static void Main(string[] args) public static void Main(string[] args)
{ {
IntPtr conn = GetConnection(); var builder = new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
string topic = "topic_example"; using (var client = DbDriver.Open(builder))
//create topic
IntPtr res = TDengine.Query(conn, $"create topic if not exists {topic} as select * from meters");
if (TDengine.ErrorNo(res) != 0 )
{ {
throw new Exception($"create topic failed, reason:{TDengine.Error(res)}"); try
}
var cfg = new ConsumerConfig
{ {
GourpId = "group_1", client.Exec("CREATE DATABASE power");
TDConnectUser = "root", client.Exec("USE power");
TDConnectPasswd = "taosdata", client.Exec(
MsgWithTableName = "true", "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
TDConnectIp = "127.0.0.1", client.Exec("CREATE TOPIC topic_meters as SELECT * from power.meters");
var cfg = new Dictionary<string, string>()
{
{ "group.id", "group1" },
{ "auto.offset.reset", "latest" },
{ "td.connect.ip", "127.0.0.1" },
{ "td.connect.user", "root" },
{ "td.connect.pass", "taosdata" },
{ "td.connect.port", "6030" },
{ "client.id", "tmq_example" },
{ "enable.auto.commit", "true" },
{ "msg.with.table.name", "false" },
}; };
var consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
// create consumer consumer.Subscribe(new List<string>() { "topic_meters" });
var consumer = new ConsumerBuilder(cfg) Task.Run(InsertData);
.Build(); while (true)
// subscribe
consumer.Subscribe(topic);
// consume
for (int i = 0; i < 5; i++)
{ {
var consumeRes = consumer.Consume(300); using (var cr = consumer.Consume(500))
// print consumeResult
foreach (KeyValuePair<TopicPartition, TaosResult> kv in consumeRes.Message)
{ {
Console.WriteLine("topic partitions:\n{0}", kv.Key.ToString()); if (cr == null) continue;
foreach (var message in cr.Message)
kv.Value.Metas.ForEach(meta =>
{ {
Console.Write("{0} {1}({2}) \t|", meta.name, meta.TypeName(), meta.size); Console.WriteLine(
}); $"message {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
Console.WriteLine(""); $"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
kv.Value.Datas.ForEach(data => }
}
}
}
catch (Exception e)
{ {
Console.WriteLine(data.ToString()); Console.WriteLine(e.ToString());
}); throw;
}
}
} }
consumer.Commit(consumeRes); static void InsertData()
Console.WriteLine("\n================ {0} done ", i);
}
// retrieve topic list
List<string> topics = consumer.Subscription();
topics.ForEach(t => Console.WriteLine("topic name:{0}", t));
// unsubscribe
consumer.Unsubscribe();
// close consumer after use.Otherwise will lead memory leak.
consumer.Close();
TDengine.Close(conn);
}
static IntPtr GetConnection()
{ {
string host = "localhost"; var builder = new ConnectionStringBuilder("host=localhost;port=6030;username=root;password=taosdata");
short port = 6030; using (var client = DbDriver.Open(builder))
string username = "root";
string password = "taosdata";
string dbname = "power";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{ {
throw new Exception("Connect to TDengine failed"); while (true)
}
else
{ {
Console.WriteLine("Connect to TDengine success"); client.Exec("INSERT into power.d1001 using power.meters tags(2,'California.SanFrancisco') values(now,11.5,219,0.30)");
Task.Delay(1000).Wait();
}
} }
return conn;
} }
} }

View File

@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,28 +1,18 @@
using System; using System;
using TDengineWS.Impl; using TDengine.Driver;
using TDengine.Driver.Client;
namespace Examples namespace Examples
{ {
public class WSConnExample public class WSConnExample
{ {
static int Main(string[] args) static void Main(string[] args)
{ {
string DSN = "ws://root:taosdata@127.0.0.1:6041/test"; var builder = new ConnectionStringBuilder("protocol=WebSocket;host=localhost;port=6041;useSSL=false;username=root;password=taosdata");
IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN); using (var client = DbDriver.Open(builder))
if (wsConn == IntPtr.Zero)
{ {
Console.WriteLine("get WS connection failed"); Console.WriteLine("connected");
return -1;
} }
else
{
Console.WriteLine("Establish connect success.");
// close connection.
LibTaosWS.WSClose(wsConn);
}
return 0;
} }
} }
} }

View File

@ -6,7 +6,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" GeneratePathProperty="true" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup> </ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild"> <Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup> <ItemGroup>

View File

@ -1,61 +1,46 @@
using System; using System;
using TDengineWS.Impl; using TDengine.Driver;
using TDengine.Driver.Client;
namespace Examples namespace Examples
{ {
public class WSInsertExample public class WSInsertExample
{ {
static int Main(string[] args) public static void Main(string[] args)
{ {
string DSN = "ws://root:taosdata@127.0.0.1:6041/test"; var builder = new ConnectionStringBuilder("protocol=WebSocket;host=localhost;port=6041;useSSL=false;username=root;password=taosdata");
IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN); using (var client = DbDriver.Open(builder))
// Assert if connection is validate
if (wsConn == IntPtr.Zero)
{ {
Console.WriteLine("get WS connection failed"); try
return -1;
}
else
{ {
Console.WriteLine("Establish connect success."); client.Exec("create database power");
client.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
string insertQuery =
"INSERT INTO " +
"power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " +
"VALUES " +
"('2023-10-03 14:38:05.000', 10.30000, 219, 0.31000) " +
"('2023-10-03 14:38:15.000', 12.60000, 218, 0.33000) " +
"('2023-10-03 14:38:16.800', 12.30000, 221, 0.31000) " +
"power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " +
"VALUES " +
"('2023-10-03 14:38:16.650', 10.30000, 218, 0.25000) " +
"power.d1003 USING power.meters TAGS(2,'California.LosAngeles') " +
"VALUES " +
"('2023-10-03 14:38:05.500', 11.80000, 221, 0.28000) " +
"('2023-10-03 14:38:16.600', 13.40000, 223, 0.29000) " +
"power.d1004 USING power.meters TAGS(3,'California.LosAngeles') " +
"VALUES " +
"('2023-10-03 14:38:05.000', 10.80000, 223, 0.29000) " +
"('2023-10-03 14:38:06.500', 11.50000, 221, 0.35000)";
client.Exec(insertQuery);
} }
catch (Exception e)
string createTable = "CREATE STABLE test.meters (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);";
string insert = "INSERT INTO test.d1001 USING test.meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000)" +
"test.d1002 USING test.meters TAGS('California.SanFrancisco', 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)" +
"test.d1003 USING test.meters TAGS('California.LosAngeles', 2) VALUES('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) " +
"test.d1004 USING test.meters TAGS('California.LosAngeles', 3) VALUES('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000)('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)";
IntPtr wsRes = LibTaosWS.WSQuery(wsConn, createTable);
ValidInsert("create table", wsRes);
LibTaosWS.WSFreeResult(wsRes);
wsRes = LibTaosWS.WSQuery(wsConn, insert);
ValidInsert("insert data", wsRes);
LibTaosWS.WSFreeResult(wsRes);
// close connection.
LibTaosWS.WSClose(wsConn);
return 0;
}
static void ValidInsert(string desc, IntPtr wsRes)
{ {
int code = LibTaosWS.WSErrorNo(wsRes); Console.WriteLine(e.ToString());
if (code != 0) throw;
{ }
Console.WriteLine($"execute SQL failed: reason: {LibTaosWS.WSErrorStr(wsRes)}, code:{code}");
}
else
{
Console.WriteLine("{0} success affect {2} rows, cost {1} nanoseconds", desc, LibTaosWS.WSTakeTiming(wsRes), LibTaosWS.WSAffectRows(wsRes));
} }
} }
} }
} }
// Establish connect success.
// create table success affect 0 rows, cost 3717542 nanoseconds
// insert data success affect 8 rows, cost 2613637 nanoseconds

View File

@ -6,7 +6,7 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" GeneratePathProperty="true" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup> </ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild"> <Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup> <ItemGroup>

View File

@ -1,79 +1,36 @@
using System; using System;
using TDengineWS.Impl; using System.Text;
using System.Collections.Generic; using TDengine.Driver;
using TDengineDriver; using TDengine.Driver.Client;
namespace Examples namespace Examples
{ {
public class WSQueryExample public class WSQueryExample
{ {
static int Main(string[] args) public static void Main(string[] args)
{ {
string DSN = "ws://root:taosdata@127.0.0.1:6041/test"; var builder = new ConnectionStringBuilder("protocol=WebSocket;host=localhost;port=6041;useSSL=false;username=root;password=taosdata");
IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN); using (var client = DbDriver.Open(builder))
if (wsConn == IntPtr.Zero)
{ {
Console.WriteLine("get WS connection failed"); try
return -1; {
client.Exec("use power");
string query = "SELECT * FROM meters";
using (var rows = client.Query(query))
{
while (rows.Read())
{
Console.WriteLine(
$"{((DateTime)rows.GetValue(0)):yyyy-MM-dd HH:mm:ss.fff}, {rows.GetValue(1)}, {rows.GetValue(2)}, {rows.GetValue(3)}, {rows.GetValue(4)}, {Encoding.UTF8.GetString((byte[])rows.GetValue(5))}");
} }
else
{
Console.WriteLine("Establish connect success.");
} }
string select = "select * from test.meters";
// optional:wsRes = LibTaosWS.WSQuery(wsConn, select);
IntPtr wsRes = LibTaosWS.WSQueryTimeout(wsConn, select, 1);
// Assert if query execute success.
int code = LibTaosWS.WSErrorNo(wsRes);
if (code != 0)
{
Console.WriteLine($"execute SQL failed: reason: {LibTaosWS.WSErrorStr(wsRes)}, code:{code}");
LibTaosWS.WSFreeResult(wsRes);
return -1;
} }
catch (Exception e)
// get meta data
List<TDengineMeta> metas = LibTaosWS.WSGetFields(wsRes);
// get retrieved data
List<object> dataSet = LibTaosWS.WSGetData(wsRes);
// do something with result.
foreach (var meta in metas)
{ {
Console.Write("{0} {1}({2}) \t|\t", meta.name, meta.TypeName(), meta.size); Console.WriteLine(e.ToString());
throw;
} }
Console.WriteLine("");
for (int i = 0; i < dataSet.Count;)
{
for (int j = 0; j < metas.Count; j++)
{
Console.Write("{0}\t|\t", dataSet[i]);
i++;
} }
Console.WriteLine("");
}
// Free result after use.
LibTaosWS.WSFreeResult(wsRes);
// close connection.
LibTaosWS.WSClose(wsConn);
return 0;
} }
} }
} }
// Establish connect success.
// ts TIMESTAMP(8) | current FLOAT(4) | voltage INT(4) | phase FLOAT(4) | location BINARY(64) | groupid INT(4) |
// 1538548685000 | 10.8 | 223 | 0.29 | California.LosAngeles | 3 |
// 1538548686500 | 11.5 | 221 | 0.35 | California.LosAngeles | 3 |
// 1538548685500 | 11.8 | 221 | 0.28 | California.LosAngeles | 2 |
// 1538548696600 | 13.4 | 223 | 0.29 | California.LosAngeles | 2 |
// 1538548685000 | 10.3 | 219 | 0.31 | California.SanFrancisco | 2 |
// 1538548695000 | 12.6 | 218 | 0.33 | California.SanFrancisco | 2 |
// 1538548696800 | 12.3 | 221 | 0.31 | California.SanFrancisco | 2 |
// 1538548696650 | 10.3 | 218 | 0.25 | California.SanFrancisco | 3 |

View File

@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" GeneratePathProperty="true" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup> </ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild"> <Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup> <ItemGroup>

View File

@ -1,98 +1,41 @@
using System; using System;
using TDengineWS.Impl; using TDengine.Driver;
using TDengineDriver; using TDengine.Driver.Client;
using System.Runtime.InteropServices;
namespace Examples namespace Examples
{ {
public class WSStmtExample public class WSStmtExample
{ {
static int Main(string[] args) public static void Main(string[] args)
{ {
const string DSN = "ws://root:taosdata@127.0.0.1:6041/test"; var builder =
const string table = "meters"; new ConnectionStringBuilder(
const string database = "test"; "protocol=WebSocket;host=localhost;port=6041;useSSL=false;username=root;password=taosdata");
const string childTable = "d1005"; using (var client = DbDriver.Open(builder))
string insert = $"insert into ? using {database}.{table} tags(?,?) values(?,?,?,?)";
const int numOfTags = 2;
const int numOfColumns = 4;
// Establish connection
IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN);
if (wsConn == IntPtr.Zero)
{ {
Console.WriteLine($"get WS connection failed"); try
return -1; {
client.Exec($"create database power");
client.Exec(
"CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
using (var stmt = client.StmtInit())
{
stmt.Prepare(
"Insert into power.d1001 using power.meters tags(2,'California.SanFrancisco') values(?,?,?,?)");
var ts = new DateTime(2023, 10, 03, 14, 38, 05, 000);
stmt.BindRow(new object[] { ts, (float)10.30000, (int)219, (float)0.31000 });
stmt.AddBatch();
stmt.Exec();
var affected = stmt.Affected();
Console.WriteLine($"affected rows: {affected}");
} }
else
{
Console.WriteLine("Establish connect success...");
} }
catch (Exception e)
// init stmt
IntPtr wsStmt = LibTaosWS.WSStmtInit(wsConn);
if (wsStmt != IntPtr.Zero)
{ {
int code = LibTaosWS.WSStmtPrepare(wsStmt, insert); Console.WriteLine(e);
ValidStmtStep(code, wsStmt, "WSStmtPrepare"); throw;
TAOS_MULTI_BIND[] wsTags = new TAOS_MULTI_BIND[] { WSMultiBind.WSBindNchar(new string[] { "California.SanDiego" }), WSMultiBind.WSBindInt(new int?[] { 4 }) };
code = LibTaosWS.WSStmtSetTbnameTags(wsStmt, $"{database}.{childTable}", wsTags, numOfTags);
ValidStmtStep(code, wsStmt, "WSStmtSetTbnameTags");
TAOS_MULTI_BIND[] data = new TAOS_MULTI_BIND[4];
data[0] = WSMultiBind.WSBindTimestamp(new long[] { 1538548687000, 1538548688000, 1538548689000, 1538548690000, 1538548691000 });
data[1] = WSMultiBind.WSBindFloat(new float?[] { 10.30F, 10.40F, 10.50F, 10.60F, 10.70F });
data[2] = WSMultiBind.WSBindInt(new int?[] { 223, 221, 222, 220, 219 });
data[3] = WSMultiBind.WSBindFloat(new float?[] { 0.31F, 0.32F, 0.33F, 0.35F, 0.28F });
code = LibTaosWS.WSStmtBindParamBatch(wsStmt, data, numOfColumns);
ValidStmtStep(code, wsStmt, "WSStmtBindParamBatch");
code = LibTaosWS.WSStmtAddBatch(wsStmt);
ValidStmtStep(code, wsStmt, "WSStmtAddBatch");
IntPtr stmtAffectRowPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Int32)));
code = LibTaosWS.WSStmtExecute(wsStmt, stmtAffectRowPtr);
ValidStmtStep(code, wsStmt, "WSStmtExecute");
Console.WriteLine("WS STMT insert {0} rows...", Marshal.ReadInt32(stmtAffectRowPtr));
Marshal.FreeHGlobal(stmtAffectRowPtr);
LibTaosWS.WSStmtClose(wsStmt);
// Free unmanaged memory
WSMultiBind.WSFreeTaosBind(wsTags);
WSMultiBind.WSFreeTaosBind(data);
//check result with SQL "SELECT * FROM test.d1005;"
} }
else
{
Console.WriteLine("Init STMT failed...");
}
// close connection.
LibTaosWS.WSClose(wsConn);
return 0;
}
static void ValidStmtStep(int code, IntPtr wsStmt, string desc)
{
if (code != 0)
{
Console.WriteLine($"{desc} failed,reason: {LibTaosWS.WSErrorStr(wsStmt)}, code: {code}");
}
else
{
Console.WriteLine("{0} success...", desc);
} }
} }
} }
} }
// WSStmtPrepare success...
// WSStmtSetTbnameTags success...
// WSStmtBindParamBatch success...
// WSStmtAddBatch success...
// WSStmtExecute success...
// WS STMT insert 5 rows...

View File

@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.*" GeneratePathProperty="true" /> <PackageReference Include="TDengine.Connector" Version="3.1.*" GeneratePathProperty="true" />
</ItemGroup> </ItemGroup>
<Target Name="copyDLLDependency" BeforeTargets="BeforeBuild"> <Target Name="copyDLLDependency" BeforeTargets="BeforeBuild">
<ItemGroup> <ItemGroup>

View File

@ -176,7 +176,7 @@ npm install @tdengine/rest
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.0" /> <PackageReference Include="TDengine.Connector" Version="3.1.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,3 +0,0 @@
```csharp
{{#include docs/examples/csharp/asyncQuery/Program.cs}}
```

View File

@ -16,7 +16,6 @@ import CQuery from "./_c.mdx";
import PhpQuery from "./_php.mdx"; import PhpQuery from "./_php.mdx";
import PyAsync from "./_py_async.mdx"; import PyAsync from "./_py_async.mdx";
import NodeAsync from "./_js_async.mdx"; import NodeAsync from "./_js_async.mdx";
import CsAsync from "./_cs_async.mdx";
import CAsync from "./_c_async.mdx"; import CAsync from "./_c_async.mdx";
## 主要查询功能 ## 主要查询功能
@ -175,9 +174,6 @@ Query OK, 6 rows in database (0.005515s)
<TabItem label="Python" value="python"> <TabItem label="Python" value="python">
<PyAsync /> <PyAsync />
</TabItem> </TabItem>
<TabItem label="C#" value="csharp">
<CsAsync />
</TabItem>
<TabItem label="C" value="c"> <TabItem label="C" value="c">
<CAsync /> <CAsync />
</TabItem> </TabItem>

View File

@ -248,23 +248,23 @@ function close()
<TabItem value="C#" label="C#"> <TabItem value="C#" label="C#">
```csharp ```csharp
class ConsumerBuilder<TValue>
ConsumerBuilder(IEnumerable<KeyValuePair<string, string>> config) ConsumerBuilder(IEnumerable<KeyValuePair<string, string>> config)
virtual IConsumer Build() public IConsumer<TValue> Build()
Consumer(ConsumerBuilder builder)
void Subscribe(IEnumerable<string> topics) void Subscribe(IEnumerable<string> topics)
void Subscribe(string topic) void Subscribe(string topic)
ConsumeResult Consume(int millisecondsTimeout) ConsumeResult<TValue> Consume(int millisecondsTimeout)
List<string> Subscription() List<string> Subscription()
void Unsubscribe() void Unsubscribe()
void Commit(ConsumeResult consumerResult) List<TopicPartitionOffset> Commit()
void Close() void Close()
``` ```
@ -501,25 +501,19 @@ let consumer = taos.consumer({
<TabItem value="C#" label="C#"> <TabItem value="C#" label="C#">
```csharp ```csharp
using TDengineTMQ; var cfg = new Dictionary<string, string>()
{
// 根据需要,设置消费组 (GourpId)、自动提交 (EnableAutoCommit)、 { "group.id", "group1" },
// 自动提交时间间隔 (AutoCommitIntervalMs)、用户名 (TDConnectUser)、密码 (TDConnectPasswd) 等参数 { "auto.offset.reset", "latest" },
var cfg = new ConsumerConfig { "td.connect.ip", "127.0.0.1" },
{ { "td.connect.user", "root" },
EnableAutoCommit = "true" { "td.connect.pass", "taosdata" },
AutoCommitIntervalMs = "1000" { "td.connect.port", "6030" },
GourpId = "TDengine-TMQ-C#", { "client.id", "tmq_example" },
TDConnectUser = "root", { "enable.auto.commit", "true" },
TDConnectPasswd = "taosdata", { "msg.with.table.name", "false" },
AutoOffsetReset = "latest" };
MsgWithTableName = "true", var consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
TDConnectIp = "127.0.0.1",
TDConnectPort = "6030"
};
var consumer = new ConsumerBuilder(cfg).Build();
``` ```
</TabItem> </TabItem>
@ -748,10 +742,12 @@ while(true){
// 消费数据 // 消费数据
while (true) while (true)
{ {
var consumerRes = consumer.Consume(100); using (var result = consumer.Consume(500))
// process ConsumeResult {
ProcessMsg(consumerRes); if (result == null) continue;
consumer.Commit(consumerRes); ProcessMsg(result);
consumer.Commit();
}
} }
``` ```

File diff suppressed because it is too large Load Diff

View File

@ -11,10 +11,9 @@ dotnet run --project connect/connect.csproj
taos -s "drop database if exists power" taos -s "drop database if exists power"
dotnet run --project sqlInsert/sqlinsert.csproj dotnet run --project sqlInsert/sqlinsert.csproj
dotnet run --project query/query.csproj dotnet run --project query/query.csproj
dotnet run --project asyncQuery/asyncquery.csproj #dotnet run --project subscribe/subscribe.csproj
dotnet run --project subscribe/subscribe.csproj
taos -s "drop topic if exists topic_example" #taos -s "drop topic if exists topic_example"
taos -s "drop database if exists power" taos -s "drop database if exists power"
dotnet run --project stmtInsert/stmtinsert.csproj dotnet run --project stmtInsert/stmtinsert.csproj
@ -28,10 +27,12 @@ taos -s "drop database if exists test"
dotnet run --project optsJSON/optsJSON.csproj dotnet run --project optsJSON/optsJSON.csproj
taos -s "create database if not exists test" taos -s "create database if not exists test"
taos -s "drop database if exists power"
dotnet run --project wsConnect/wsConnect.csproj dotnet run --project wsConnect/wsConnect.csproj
dotnet run --project wsInsert/wsInsert.csproj dotnet run --project wsInsert/wsInsert.csproj
dotnet run --project wsStmt/wsStmt.csproj
dotnet run --project wsQuery/wsQuery.csproj dotnet run --project wsQuery/wsQuery.csproj
taos -s "drop database if exists power"
dotnet run --project wsStmt/wsStmt.csproj
taos -s "drop database if exists test" taos -s "drop database if exists test"
taos -s "drop database if exists power" taos -s "drop database if exists power"