将Application Insights查询API调用结果转换为DataTable [英] convert Application Insights query API call result to a DataTable

查看:91
本文介绍了将Application Insights查询API调用结果转换为DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Application Insight记录CustomEvent.我想通过代码(c#)查询它.我发现了如何使用

I am using Application Insight to log CustomEvent. I would like querying it by code (c#). I found how to use the REST API, and using GET/Query to run a query and get the JSON result.

When I looks at the JSON string it's look defining a table:

    {
      "tables": [
        {
          "name": "PrimaryResult",
          "columns": [
            {
              "name": "timestamp",
              "type": "datetime"
            },
            {
.....
   "rows": [
        [
          "2019-01-10T16:09:44.2443658Z",
          "zzzz",
          "customEvent",
          "{\"Application\":\"LogClient-IntegrationTests\",\"EventType\":\"Action\"}",

So I would like to know if it's exist a way to convert the result to a DataTable?

解决方案

It's hard or impossible to convert to datatable, since some values in the result are dynamic type(like customDimensions and customMeasurements).

I used the Dictionary to store the restructured result(For the dynamic type like customDimensions, I just treat it as a string for testing purpose. If you want to continue on this, you can use a more complex Dictionary type for this).

Sample code like below:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleApp20
{
    class Program
    {
        static void Main(string[] args)
        {

            string URL =
        "https://api.applicationinsights.io/v1/apps/{0}/{1}";

            string apikey = "xxxxx";
            string appid = "xxxx";
            string query = "query?query=customEvents| where timestamp >ago(30d)| top 5 by timestamp";

            string result = "";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("x-api-key", apikey);

            var req = string.Format(URL, appid, query);

            HttpResponseMessage response = client.GetAsync(req).Result;
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                result = response.ReasonPhrase;
            }

            //get the schema of the results, like how many columns and each columns' name
            string schema = result.Remove(0, result.IndexOf("\"columns\":") + 1);
            schema = schema.Remove(schema.IndexOf("],")).Remove(0, schema.IndexOf("["));
            schema = schema + "]";

            //define a dictionary for storing structured results
            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

            //convert schema string to json
            var json = JsonConvert.DeserializeObject<List<dynamic>>(schema);

            foreach (var item in json)
            {
                var t1 = ((JObject)item).First;
                var t2 = ((JObject)item).Last;

                string s1 = t1.ToString();

                List<string> list = new List<string>();
                dict.Add(s1.Replace("\"name\":", "").Trim(), list);
            }


            //add the value to the dictionary
            //format the string
            string new_content = result.Remove(0, result.IndexOf("\"rows\":[")).Replace("\"rows\":[", "").Replace("]}]}", "");

            //add each row of value to an array
            var row_array = new_content.Split(']');

            foreach (var t in row_array)
            {
                //if the row is empty, ignore it
                if (t.Length == 0) continue;

                int count = 0;
                string a = "";
                List<dynamic> json2 = null;

                if (t.StartsWith(","))
                {
                    a = t.Remove(0, 1) + "]";
                    json2 = JsonConvert.DeserializeObject<List<dynamic>>(a.Trim());
                }
                else if (!t.EndsWith("]"))
                {
                    a = t + "]";

                    json2 = JsonConvert.DeserializeObject<List<dynamic>>(a.Trim());
                }

                foreach (var item in json2)
                {
                    var s2 = ((JValue)item).ToString();
                    dict[dict.Keys.ElementAt(count)].Add(s2);
                    count++;
                }
            }

            Console.WriteLine("---done---");
            Console.ReadLine();
        }
    }
}

The testing result: I fetch 5 rows of records, and all of them stored in Dictionary

这篇关于将Application Insights查询API调用结果转换为DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆