aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio_22/Tango.Portal.Chat.Web/Services/KustoQueryService.cs
blob: 8766eacd5f3b1f8232ea89daf9011a0e4de96337 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Azure.Core;
using Azure.Identity;
using Kusto.Data;
using Kusto.Data.Common;
using Kusto.Data.Net.Client;
using Microsoft.Extensions.Options;
using System.Data;

namespace Tango.Portal.Chat.Web.Services
{
    public sealed class KustoQueryService
    {
        private readonly ICslQueryProvider _query;
        private readonly string _database;

        public KustoQueryService(IOptions<AdxOptions> opts)
        {
            var options = opts.Value;
            _database = options.Database;

            // Use DefaultAzureCredential: works locally (Azure CLI / Visual Studio), and in Azure (Managed Identity)
            var cred = new ClientSecretCredential(
                        opts.Value.TenantId,
                        opts.Value.ClientId,
                        opts.Value.ClientSecret);

            var kcsb = new KustoConnectionStringBuilder(options.ClusterUri)
                .WithAadAzureTokenCredentialsAuthentication(cred);

            _query = KustoClientFactory.CreateCslQueryProvider(kcsb);
        }

        public async Task<DataTable> QueryAsync(string kql, IDictionary<string, string> parameters, CancellationToken ct = default)
        {
            var props = new ClientRequestProperties
            {
                ClientRequestId = $"chat_{Guid.NewGuid()}"
            };

            foreach (var kvp in parameters)
            {
                // Pass all as strings; let KQL cast via e.g., datetime({from}) if declared
                props.SetParameter(kvp.Key, kvp.Value);
            }

            props.SetOption("servertimeout", "00:00:12");

            using var reader = await _query.ExecuteQueryAsync(_database, kql, props);
            var table = new DataTable();
            table.Load(reader);
            return table;
        }
    }
}