20231107 - Serialização e Desserialização de Json
This commit is contained in:
parent
79f5e3db25
commit
4665174aca
303
Program.cs
303
Program.cs
@ -3,10 +3,11 @@ using System.Data.OleDb;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection.Metadata;
|
||||
|
||||
class Program
|
||||
{
|
||||
@ -18,50 +19,74 @@ class Program
|
||||
string ConnSourcePath = @"C:\Users\contratos\Documents\Giuliano\Pipefy.accdb";
|
||||
string PipefyTokenTableID = "b9t-7uD5";
|
||||
|
||||
string? cursor = "null";
|
||||
|
||||
// Crie uma instância HttpClient
|
||||
using (HttpClient httpClient = new HttpClient())
|
||||
string query = $"{{\"query\":\"query GetRecords($cursor: String){{ table_records(table_id: \\\"{PipefyTokenTableID}\\\",first:50,after:$cursor){{ pageInfo{{ hasNextPage endCursor }} edges{{ node{{ record_fields{{ field {{ id }} value array_value }} }} }} }}}}\",\"variables\":{{\"cursor\":{cursor}}}}}";
|
||||
Console.WriteLine(query);
|
||||
bool hasNextPage = true;
|
||||
bool hasSucceeded = true;
|
||||
JArray allRecords = new JArray();
|
||||
|
||||
while (hasNextPage)
|
||||
{
|
||||
var httpClient = new HttpClient();
|
||||
// Defina os headers da requisição (opcional)
|
||||
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
|
||||
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + PipefyToken);
|
||||
|
||||
// Crie a consulta GraphQL
|
||||
string query = /*lang=json,strict*/ @"{""query"":""query{\r\n table_records(table_id: \""wzirXS8w\"") {\r\n edges {\r\n node {\r\n id\r\n record_fields{\r\n field{\r\n id\r\n }\r\n value\r\n }\r\n }\r\n }\r\n }\r\n}"",""variables"":{}}";
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
|
||||
request.Headers.Add("Accept", "application/json");
|
||||
|
||||
// Defina o conteúdo do corpo da requisição
|
||||
var content = new StringContent(query, System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
// Envie a requisição POST com a consulta GraphQL
|
||||
var response = await httpClient.PostAsync(apiUrl, content);
|
||||
var content = new StringContent(query, null, "application/json");
|
||||
request.Content = content;
|
||||
var response = await httpClient.SendAsync(request);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
string responseBody = await response.Content.ReadAsStringAsync();
|
||||
var responseContent = await response.Content.ReadAsStringAsync();
|
||||
var responseData = JObject.Parse(responseContent);
|
||||
|
||||
Console.WriteLine("Resposta bem-sucedida:");
|
||||
Console.WriteLine(responseBody);
|
||||
var records = responseData["data"]["table_records"]["edges"];
|
||||
foreach (var record in records)
|
||||
{
|
||||
allRecords.Add(record);
|
||||
}
|
||||
|
||||
hasNextPage = responseData["data"]["table_records"]["pageInfo"]["hasNextPage"].Value<bool>();
|
||||
cursor = responseData["data"]["table_records"]["pageInfo"]["endCursor"].Value<string>();
|
||||
query = $"{{\"query\":\"query GetRecords($cursor: String){{ table_records(table_id: \\\"{PipefyTokenTableID}\\\",first:50,after:$cursor){{ pageInfo{{ hasNextPage endCursor }} edges{{ node{{ record_fields{{ field {{ id }} value array_value }} }} }} }}}}\",\"variables\":{{\"cursor\":\"{cursor}\"}}}}";
|
||||
|
||||
// Agora você pode comparar a resposta JSON com a tabela no banco de dados Access
|
||||
CompareResponseWithDatabase(responseBody, ConnSourcePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Erro na requisição: {response.StatusCode}");
|
||||
Console.WriteLine($"Erro na solicitação GraphQL: {response.StatusCode}");
|
||||
hasSucceeded = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
static void CompareResponseWithDatabase(string jsonResponse, string ConnSourcePath)
|
||||
if (hasSucceeded)
|
||||
{
|
||||
// Defina a string de conexão para o banco de dados Access
|
||||
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath;
|
||||
var responseObject = JObject.Parse(jsonResponse);
|
||||
string strJson = Newtonsoft.Json.JsonSerializer(allRecords);
|
||||
// Desserialize o JSON em objetos C#
|
||||
var jsonData = JsonConvert.DeserializeObject(allRecords.ToO);
|
||||
|
||||
var idFromJson = responseObject["data"]["table_records"]["edges"];
|
||||
foreach( var id in idFromJson){
|
||||
var a = 10;
|
||||
// Consulte os dados da tabela no banco de dados Access
|
||||
List<ClasseEmpresas> databaseData = GetDataFromDatabase(ConnSourcePath);
|
||||
|
||||
// Compare os dados e encontre os registros ausentes no JSON
|
||||
List<ClasseEmpresas> recordsMissingInJson = CompareData(databaseData, jsonData?.data?.table_records?.edges);
|
||||
|
||||
// Faça algo com os registros ausentes
|
||||
foreach (var record in recordsMissingInJson)
|
||||
{
|
||||
Console.WriteLine($"Registro ausente no JSON - ID: {record.c_odigo_smart}, Nome: {record.nome_da_empresa}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static List<ClasseEmpresas> GetDataFromDatabase(string ConnSourcePath)
|
||||
{
|
||||
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath;
|
||||
List<ClasseEmpresas> data = new List<ClasseEmpresas>();
|
||||
|
||||
using (OleDbConnection connection = new OleDbConnection(connectionString))
|
||||
{
|
||||
@ -71,23 +96,231 @@ class Program
|
||||
string sqlQuery = "SELECT * FROM tblEmpresas";
|
||||
using (OleDbCommand command = new OleDbCommand(sqlQuery, connection))
|
||||
{
|
||||
//teste
|
||||
using (OleDbDataReader reader = command.ExecuteReader())
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
int idFromDatabase = (int)reader["id"];
|
||||
string nomeFromDatabase = (string)reader["nome"];
|
||||
ClasseEmpresas record = new ClasseEmpresas
|
||||
{
|
||||
c_odigo_smart = (int)reader["Código Smart"],
|
||||
nome_da_empresa = (string)reader["Nome da empresa"],
|
||||
modalidade = (string)reader["modalidade"],
|
||||
gestores = (string)reader["gestores"],
|
||||
|
||||
// Compare os valores do JSON com os valores do banco de dados
|
||||
//if (idFromJson == idFromDatabase && nomeFromJson == nomeFromDatabase)
|
||||
//{
|
||||
// // Realize ação quando houver correspondência
|
||||
// Console.WriteLine("Correspondência encontrada!");
|
||||
//}
|
||||
// Adicione outras propriedades conforme necessário
|
||||
};
|
||||
data.Add(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
static List<ClasseEmpresas> CompareData(List<ClasseEmpresas> databaseData, List<Edge> jsonData)
|
||||
{
|
||||
if (jsonData == null)
|
||||
{
|
||||
return databaseData;
|
||||
}
|
||||
|
||||
List<ClasseEmpresas> recordsMissingInJson = new List<ClasseEmpresas>();
|
||||
|
||||
foreach (var record in databaseData)
|
||||
{
|
||||
if (!jsonData.Any(item => item.node.c_odigo_smart == record.c_odigo_smart))
|
||||
{
|
||||
recordsMissingInJson.Add(record);
|
||||
}
|
||||
}
|
||||
|
||||
return recordsMissingInJson;
|
||||
}
|
||||
}
|
||||
|
||||
class Root
|
||||
{
|
||||
public Data data { get; set; }
|
||||
}
|
||||
|
||||
class Data
|
||||
{
|
||||
public TableRecords table_records { get; set; }
|
||||
}
|
||||
|
||||
class TableRecords
|
||||
{
|
||||
public List<Edge> edges { get; set; }
|
||||
}
|
||||
|
||||
class Edge
|
||||
{
|
||||
public Node node { get; set; }
|
||||
}
|
||||
|
||||
class Node
|
||||
{
|
||||
public int c_odigo_smart { get; set; }
|
||||
public string nome_da_empresa { get; set; }
|
||||
public string modalidade { get; set; }
|
||||
public string gestores { get; set; }
|
||||
}
|
||||
|
||||
class ClasseEmpresas
|
||||
{
|
||||
public int c_odigo_smart { get; set; }
|
||||
public string nome_da_empresa { get; set; }
|
||||
public string modalidade { get; set; }
|
||||
public string gestores { get; set; }
|
||||
// Adicione outras propriedades conforme necessário
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//using System;
|
||||
//using System.Data.OleDb;
|
||||
//using System.Net.Http;
|
||||
//using System.Net.Http.Headers;
|
||||
//using System.Text.Json;
|
||||
//using System.Threading.Tasks;
|
||||
//using Newtonsoft.Json;
|
||||
//using Newtonsoft.Json.Linq;
|
||||
//using System.Collections.Generic;
|
||||
|
||||
//class Program
|
||||
//{
|
||||
// static async Task Main(string[] args)
|
||||
// {
|
||||
// // URL da API que você deseja chamar
|
||||
// string apiUrl = "https://api.pipefy.com/graphql";
|
||||
// string PipefyToken = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJQaXBlZnkiLCJpYXQiOjE2OTg4NTYyMjcsImp0aSI6IjM2N2Y4M2NhLWZjODYtNGRhOC04ODEyLTkzODRkZGZkODc0MiIsInN1YiI6MzAyNTM0MzY2LCJ1c2VyIjp7ImlkIjozMDI1MzQzNjYsImVtYWlsIjoiYmFjazVAZW5lcmdpYXNtYXJ0LmNvbS5iciIsImFwcGxpY2F0aW9uIjozMDAyODkyNDgsInNjb3BlcyI6W119LCJpbnRlcmZhY2VfdXVpZCI6bnVsbH0.o13j9c_y3G3HX35qhX4PmkkibGsmlHsk5dL_Bxsr1CKV5Jlgj218kJdEmriS7aHiw0-P7sfs-bu4YcElfuyiqg";
|
||||
// string ConnSourcePath = @"C:\Users\contratos\Documents\Giuliano\Pipefy.accdb";
|
||||
// string PipefyTokenTableID = "b9t-7uD5";
|
||||
|
||||
|
||||
// // Crie uma instância HttpClient
|
||||
// using (HttpClient httpClient = new HttpClient())
|
||||
// {
|
||||
// // Defina os headers da requisição (opcional)
|
||||
// httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
// httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
|
||||
// httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + PipefyToken);
|
||||
|
||||
// // Crie a consulta GraphQL
|
||||
// //string rawGraphQuery = @"{""query"":""query{\r\n table_records(table_id: \""" + PipefyTokenTableID + @"\"") {\r\n edges {\r\n node {\r\n id\r\n record_fields{\r\n field{\r\n id\r\n }\r\n value\r\n }\r\n }\r\n }\r\n }\r\n}"",""variables"":{}}";
|
||||
// string rawGraphQuery = "{\"query\":\"query { table_records(table_id: \\\"" + PipefyTokenTableID + "\\\") { edges { node { id record_fields { field { id } value } } } } }\",\"variables\":{}}";
|
||||
// string query = /*lang=json,strict*/ rawGraphQuery;
|
||||
|
||||
// // Defina o conteúdo do corpo da requisição
|
||||
// var content = new StringContent(query, System.Text.Encoding.UTF8, "application/json");
|
||||
|
||||
// // Envie a requisição POST com a consulta GraphQL
|
||||
// var response = await httpClient.PostAsync(apiUrl, content);
|
||||
|
||||
// if (response.IsSuccessStatusCode)
|
||||
// {
|
||||
// string responseBody = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Console.WriteLine("Resposta bem-sucedida:");
|
||||
// Console.WriteLine(responseBody);
|
||||
|
||||
// // Desserialize o JSON em objetos C#
|
||||
// var jsonData = JsonConvert.DeserializeObject<Root>(responseBody);
|
||||
|
||||
// // Consulte os dados da tabela no banco de dados Access
|
||||
// List<ClasseEmpresas> databaseData = GetDataFromDatabase(ConnSourcePath);
|
||||
|
||||
// // Compare os dados e encontre os registros ausentes no JSON
|
||||
// List<ClasseEmpresas> recordsMissingInJson = CompareData(databaseData, jsonData);
|
||||
|
||||
// // Faça algo com os registros ausentes
|
||||
// foreach (var record in recordsMissingInJson)
|
||||
// {
|
||||
// Console.WriteLine($"Registro ausente no JSON - ID: {record.Id}, Nome: {record.Nome}");
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Console.WriteLine($"Erro na requisição: {response.StatusCode}");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// static List<ClasseEmpresas> GetDataFromDatabase(string ConnSourcePath)
|
||||
// {
|
||||
// string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath;
|
||||
// List<ClasseEmpresas> data = new List<ClasseEmpresas>();
|
||||
|
||||
// using (OleDbConnection connection = new OleDbConnection(connectionString))
|
||||
// {
|
||||
// connection.Open();
|
||||
|
||||
// // Execute uma consulta SQL para recuperar dados da tabela no banco de dados Access
|
||||
// string sqlQuery = "SELECT * FROM tblEmpresas";
|
||||
// using (OleDbCommand command = new OleDbCommand(sqlQuery, connection))
|
||||
// {
|
||||
// using (OleDbDataReader reader = command.ExecuteReader())
|
||||
// {
|
||||
// while (reader.Read())
|
||||
// {
|
||||
// ClasseEmpresas record = new ClasseEmpresas
|
||||
// {
|
||||
// Id = (int)reader["id"],
|
||||
// Nome = (string)reader["nome"],
|
||||
// // Adicione outras propriedades conforme necessário
|
||||
// };
|
||||
// data.Add(record);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// return data;
|
||||
// }
|
||||
|
||||
// static List<ClasseEmpresas> CompareData(List<ClasseEmpresas> databaseData, Root? jsonData)
|
||||
// {
|
||||
// if(jsonData == null) { return databaseData; }
|
||||
|
||||
// List<ClasseEmpresas> recordsMissingInJson = new List<ClasseEmpresas>();
|
||||
|
||||
// foreach (var record in databaseData)
|
||||
// {
|
||||
// if (!jsonData.Any(item => item.id == record.id))
|
||||
// {
|
||||
// recordsMissingInJson.Add(record);
|
||||
// }
|
||||
// }
|
||||
|
||||
// return recordsMissingInJson;
|
||||
// }
|
||||
//}
|
||||
|
||||
//class Root
|
||||
//{
|
||||
// public required List<ClasseEmpresas> jsonData { get; set; }
|
||||
|
||||
// internal bool Any(Func<object, bool> value)
|
||||
// {
|
||||
// throw new NotImplementedException();
|
||||
// }
|
||||
//}
|
||||
//class ClasseEmpresas
|
||||
//{
|
||||
// public int Id { get; set; }
|
||||
// public required string Nome { get; set; }
|
||||
|
||||
// internal bool Any(Func<object, bool> value)
|
||||
// {
|
||||
// throw new NotImplementedException();
|
||||
// }
|
||||
// // Adicione outras propriedades conforme necessário
|
||||
//}
|
||||
Loading…
x
Reference in New Issue
Block a user