Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将Application Insights查询API调用结果转换为DataTable_C#_Json_Azure_Datatable_Azure Application Insights - Fatal编程技术网

C# 将Application Insights查询API调用结果转换为DataTable

C# 将Application Insights查询API调用结果转换为DataTable,c#,json,azure,datatable,azure-application-insights,C#,Json,Azure,Datatable,Azure Application Insights,我正在使用Application Insight记录CustomEvent。我想通过代码(c#)查询它。我发现了如何使用,以及如何使用GET/Query运行查询并获得JSON结果 当我查看JSON字符串时,它看起来是在定义一个表: { "tables": [ { "name": "PrimaryResult", "columns": [ { "name": "times

我正在使用Application Insight记录CustomEvent。我想通过代码(c#)查询它。我发现了如何使用,以及如何使用GET/Query运行查询并获得JSON结果

当我查看JSON字符串时,它看起来是在定义一个表:

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

因此,我想知道是否存在将结果转换为数据表的方法?

很难或不可能转换为
数据表
,因为结果中的某些值是动态类型(如
自定义维度
自定义度量

我使用字典来存储重构后的结果(对于动态类型,如
customDimensions
,我只是将其视为一个字符串进行测试。如果您想继续此操作,可以为此使用更复杂的字典类型)

示例代码如下所示:

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();
        }
    }
}
使用Newtonsoft.Json;
使用Newtonsoft.Json.Linq;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用System.Net.Http;
使用System.Net.Http.Header;
命名空间控制台App20
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串URL=
"https://api.applicationinsights.io/v1/apps/{0}/{1}";
字符串apikey=“xxxxx”;
字符串appid=“xxxx”;
string query=“query?query=customEvents |其中timestamp>ago(30d)|按时间戳排列的前5名”;
字符串结果=”;
HttpClient=新的HttpClient();
client.DefaultRequestHeaders.Accept.Add(
新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Add(“x-api-key”,apikey);
var req=string.Format(URL、appid、查询);
HttpResponseMessage response=client.GetAsync(req).Result;
if(响应。IsSuccessStatusCode)
{
结果=response.Content.ReadAsStringAsync().result;
}
其他的
{
结果=响应。原因短语;
}
//获取结果的模式,例如有多少列以及每列的名称
string schema=result.Remove(0,result.IndexOf(“\”columns\:”)+1);
schema=schema.Remove(schema.IndexOf(“]),Remove(0,schema.IndexOf(“[”));
schema=schema+“]”;
//定义用于存储结构化结果的字典
Dictionary dict=新字典();
//将模式字符串转换为json
var json=JsonConvert.DeserializeObject(模式);
foreach(json中的var项)
{
var t1=((JObject)项);
变量t2=((作业对象)项);
字符串s1=t1.ToString();
列表=新列表();
dict.Add(s1.Replace(“\”name\”:“,”).Trim(),list);
}
//将值添加到字典中
//格式化字符串
字符串new\u content=result.Remove(0,result.IndexOf(“\”行\“:[”)。替换(“\”行\“:[”,”)。替换(“]}]},”);
//将每行值添加到数组中
var row_array=new_content.Split(']');
foreach(行数组中的变量t)
{
//如果该行为空,则忽略它
如果(t.Length==0)继续;
整数计数=0;
字符串a=“”;
List json2=null;
如果(t.StartsWith(“,”))
{
a=t.Remove(0,1)+“]”;
json2=JsonConvert.DeserializeObject(a.Trim());
}
如果(!t.EndsWith(“]),则为else
{
a=t+“]”;
json2=JsonConvert.DeserializeObject(a.Trim());
}
foreach(json2中的var项)
{
var s2=((JValue)项).ToString();
dict[dict.Keys.ElementAt(count)].Add(s2);
计数++;
}
}
Console.WriteLine(“--done--”);
Console.ReadLine();
}
}
}
测试结果:我取出5行记录,全部存储在字典中


很难或不可能转换为
数据表
,因为结果中的某些值是动态类型(如
自定义维度
自定义度量值

我使用字典来存储重构后的结果(对于动态类型,如
customDimensions
,我只是将其视为一个字符串进行测试。如果您想继续此操作,可以为此使用更复杂的字典类型)

示例代码如下所示:

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();
        }
    }
}
使用Newtonsoft.Json;
使用Newtonsoft.Json.Linq;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用System.Net.Http;
使用System.Net.Http.Header;
命名空间控制台App20
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串URL=
"https://api.applicationinsights.io/v1/apps/{0}/{1}";
字符串apikey=“xxxxx”;
字符串appid=“xxxx”;
string query=“query?query=customEvents |其中timestamp>ago(30d)|按时间戳排列的前5名”;
字符串结果=”;
HttpClient=新的HttpClient();
client.DefaultRequestHeaders.Accept.Add(
新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Add(“x-api-key”,apikey);
var req=string.Format(URL、appid、查询);
HttpResponseMessage response=client.GetAsync(req).Result;
if(响应。IsSuccessStatusCode)
{
结果=response.Content.ReadAsStringAsync().result;
}
其他的
{
结果=响应。原因短语;
}
//获取结果的模式,例如有多少列以及每列的名称