using Agger.Registro; using Gestor.Common.Security; using Gestor.Common.Validation; using Gestor.Model.API; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Gestor.Application.Helpers { public static class Connection { private const bool defaultUsaAzureStorage = false; private const string defaultAzureStorage = "ad1"; public static string Server; public static string Catalog; public static string User; public static string Password; public static string Pool; public static string Type; public static Gestor.Model.API.ConnectionAddress ConnectionAddress { get; set; } public static string LinkAggilizador { get; set; } public static string UrlCentralSegurado { get; set; } private static string AdApiV2(string storage) { if (Address.get_ApiAD().ToString().Contains("/api/v1")) { return string.Empty; } return storage; } internal static Uri Append(this Uri uri, params string[] paths) { return new Uri(paths.Aggregate(uri.AbsoluteUri, (string current, string path) => string.Concat(current.TrimEnd(new char[] { '/' }), "/", path.TrimStart(new char[] { '/' })))); } public static string Base64Encode(this string plainText) { return (new Token()).Encrypt(plainText); } public static string BasicKey() { string numeroSerial = ApplicationHelper.NumeroSerial; DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); return string.Format("{0}:{1}", numeroSerial, universalTime.Ticks).Base64Encode(); } public static async Task Delete(string command) { Uri uri = new Uri(Address.GestorApi(), command); HttpClient httpClient = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); if (await httpClient.DeleteAsync(uri).get_StatusCode() != HttpStatusCode.OK) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); } return true; } internal static async Task DeleteFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad") { bool flag; string str; bool flag1; str = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage); azureStorage = str; Uri apiAD = Address.get_ApiAD(); string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(azureStorage) }; Uri uri = apiAD.Append(strArrays); string[] strArrays1 = new string[] { path }; Uri uri1 = uri.Append(strArrays1); string[] str1 = new string[] { ano.ToString() }; Uri uri2 = uri1.Append(str1); string[] str2 = new string[] { id.ToString() }; Uri uri3 = uri2.Append(str2); string[] strArrays2 = new string[] { extensao.Replace(".", string.Empty) }; Uri uri4 = uri3.Append(strArrays2); try { using (HttpClient httpClient = new HttpClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().Clear(); httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage httpResponseMessage = await httpClient.DeleteAsync(uri4); flag1 = (!httpResponseMessage.get_IsSuccessStatusCode() ? false : httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent); flag = flag1; return flag; } } catch { } flag = false; return flag; } internal static async Task DownloadFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad", bool forceDownload = false) { byte[] numArray; string str; str = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage); azureStorage = str; Uri apiAD = Address.get_ApiAD(); string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(azureStorage) }; Uri uri = apiAD.Append(strArrays); string[] strArrays1 = new string[] { path }; Uri uri1 = uri.Append(strArrays1); string[] str1 = new string[] { ano.ToString() }; Uri uri2 = uri1.Append(str1); string[] str2 = new string[] { id.ToString() }; Uri uri3 = uri2.Append(str2); string[] strArrays2 = new string[] { extensao.Replace(".", string.Empty) }; Uri uri4 = uri3.Append(strArrays2); try { string str3 = string.Format("{0}{1}{2}", Path.GetTempPath(), id, extensao); if (forceDownload || !File.Exists(str3)) { using (HttpClient httpClient = new HttpClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().Clear(); httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage async = await httpClient.GetAsync(uri4); if (async.get_IsSuccessStatusCode() && async.get_StatusCode() != HttpStatusCode.NotFound) { numArray = await async.get_Content().ReadAsByteArrayAsync(); return numArray; } } httpClient = null; } else { numArray = File.ReadAllBytes(str3); return numArray; } } catch { } numArray = null; return numArray; } public static string EncodeBase64(this string plainText) { string base64String; try { base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText)); } catch { return string.Empty; } return base64String; } internal static async Task EspacoUsadoAzureInBytes(string path = "") { double num; Uri apiAD = Address.get_ApiAD(); string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(Gestor.Application.Helpers.Connection.ConnectionAddress.get_AzureStorage()) }; Uri uri = apiAD.Append(strArrays); string[] strArrays1 = new string[] { "tamanho" }; Uri uri1 = uri.Append(strArrays1); if (!string.IsNullOrEmpty(path)) { string[] strArrays2 = new string[] { path }; uri1.Append(strArrays2); } try { using (HttpClient httpClient = new HttpClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().Clear(); httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage async = await httpClient.GetAsync(uri1); if (async.get_IsSuccessStatusCode() && async.get_StatusCode() != HttpStatusCode.NoContent) { num = double.Parse(await async.get_Content().ReadAsStringAsync()); return num; } } httpClient = null; } catch { } num = 0; return num; } public static async Task Get(string command, bool autorizar = true, bool verificarConexao = false) where T : class { Gestor.Application.Helpers.T t; HttpResponseMessage httpResponseMessage; Uri uri = new Uri(Address.GestorApi(), command); HttpClient httpClient = new HttpClient(); if (autorizar) { httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false); httpResponseMessage = await configuredTaskAwaitable; } catch (Exception exception) { ApplicationHelper.Conectado = false; t = default(Gestor.Application.Helpers.T); return t; } if (verificarConexao) { ApplicationHelper.Conectado = true; } if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent) { if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); } t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); } else { t = default(Gestor.Application.Helpers.T); } return t; } public static async Task Get(string command, bool autorizar = true) { HttpStatusCode statusCode; HttpResponseMessage httpResponseMessage; Uri uri = new Uri(Address.GestorApi(), command); HttpClient httpClient = new HttpClient(); if (autorizar) { httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false); httpResponseMessage = await configuredTaskAwaitable; } catch (Exception exception) { statusCode = HttpStatusCode.InternalServerError; return statusCode; } statusCode = httpResponseMessage.get_StatusCode(); return statusCode; } public static string GetAdConnection(string serial) { ApplicationHelper.NumeroSerial = serial; if (string.IsNullOrWhiteSpace(Gestor.Application.Helpers.Connection.Server)) { Gestor.Application.Helpers.Connection.GetAdConnection(serial); } return string.Concat(new string[] { "Server=", Gestor.Application.Helpers.Connection.Server, ";initial catalog=", Gestor.Application.Helpers.Connection.Catalog, "AD;user=", Gestor.Application.Helpers.Connection.User, ";password=", Gestor.Application.Helpers.Connection.Password, ";" }); } public static string GetConnection(bool tryconnect = true) { string str; string aggilizador; string urlCentralSegurado; try { Token token = new Token(); RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); bool usaAzureStorage = false; string str1 = "ad1"; if (ApplicationHelper.Conectado) { List result = Gestor.Application.Helpers.Connection.Get>(string.Format("Server/{0}", ApplicationHelper.IdFornecedor), true, false).Result; for (int i = 0; i < result.Count; i++) { string str2 = token.AggerEncrypt(token.Decrypt(result[i].get_Server())); string str3 = token.AggerEncrypt(token.Decrypt(result[i].get_Catalog())); string str4 = token.AggerEncrypt(token.Decrypt(result[i].get_User())); string str5 = token.AggerEncrypt(token.Decrypt(result[i].get_Password())); string str6 = token.AggerEncrypt(token.Decrypt(result[i].get_Pool())); string str7 = result[i].get_Type().ToString(); if (string.IsNullOrEmpty(result[i].get_Aggilizador())) { aggilizador = null; } else { aggilizador = result[i].get_Aggilizador(); } Gestor.Application.Helpers.Connection.LinkAggilizador = aggilizador; if (string.IsNullOrEmpty(result[i].get_UrlCentralSegurado())) { urlCentralSegurado = null; } else { urlCentralSegurado = result[0].get_UrlCentralSegurado(); } Gestor.Application.Helpers.Connection.UrlCentralSegurado = urlCentralSegurado; usaAzureStorage = result[i].get_UsaAzureStorage(); str1 = (string.IsNullOrEmpty(result[i].get_AzureStorage()) ? "ad1" : token.Decrypt(result[i].get_AzureStorage())); registryHelper.Write(string.Format("SERVER{0}", i + 1), str2, true); registryHelper.Write(string.Format("DB{0}", i + 1), str3, true); registryHelper.Write(string.Format("USER{0}", i + 1), str4, true); registryHelper.Write(string.Format("PASSWORD{0}", i + 1), str5, true); registryHelper.Write(string.Format("POOL{0}", i + 1), str6, true); registryHelper.Write(string.Format("TYPE{0}", i + 1), str7, true); } } string str8 = ""; for (int j = 0; j < 3 && registryHelper.Read(string.Format("SERVER{0}", j + 1), true) != null; j++) { if (registryHelper.Read(string.Format("TYPE{0}", j + 1), true) != "4") { Gestor.Application.Helpers.Connection.Server = token.AggerDecrypt(registryHelper.Read(string.Format("SERVER{0}", j + 1), true)); Gestor.Application.Helpers.Connection.Catalog = token.AggerDecrypt(registryHelper.Read(string.Format("DB{0}", j + 1), true)); Gestor.Application.Helpers.Connection.User = token.AggerDecrypt(registryHelper.Read(string.Format("USER{0}", j + 1), true)); Gestor.Application.Helpers.Connection.Password = token.AggerDecrypt(registryHelper.Read(string.Format("PASSWORD{0}", j + 1), true)); Gestor.Application.Helpers.Connection.Pool = token.AggerDecrypt(registryHelper.Read(string.Format("POOL{0}", j + 1), true)); Gestor.Application.Helpers.Connection.Type = registryHelper.Read(string.Format("TYPE{0}", j + 1), true); if (!usaAzureStorage) { usaAzureStorage = Task.Run(async () => await Gestor.Application.Helpers.Connection.SaveInAzureStorage()).Result; } Gestor.Model.API.ConnectionAddress connectionAddress = new Gestor.Model.API.ConnectionAddress(); connectionAddress.set_Server(Gestor.Application.Helpers.Connection.Server); connectionAddress.set_Catalog(Gestor.Application.Helpers.Connection.Catalog); connectionAddress.set_User(Gestor.Application.Helpers.Connection.User); connectionAddress.set_Password(Gestor.Application.Helpers.Connection.Password); connectionAddress.set_Pool(Gestor.Application.Helpers.Connection.Pool); connectionAddress.set_Aggilizador(Gestor.Application.Helpers.Connection.LinkAggilizador); connectionAddress.set_UrlCentralSegurado(Gestor.Application.Helpers.Connection.UrlCentralSegurado); connectionAddress.set_UsaAzureStorage(usaAzureStorage); connectionAddress.set_AzureStorage(str1); connectionAddress.set_Type(int.Parse((Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(Gestor.Application.Helpers.Connection.Type) ? "0" : Gestor.Application.Helpers.Connection.Type))); Gestor.Application.Helpers.Connection.ConnectionAddress = connectionAddress; string connectionString = Gestor.Application.Helpers.Connection.GetConnectionString(); if (!tryconnect || Gestor.Application.Helpers.Connection.TryConnect(connectionString, 1)) { str8 = connectionString; break; } } } str = str8; } catch (Exception exception) { str = null; } return str; } public static string GetConnectionString() { return string.Concat(new string[] { "Server=", Gestor.Application.Helpers.Connection.Server, ";initial catalog=", Gestor.Application.Helpers.Connection.Catalog, ";user=", Gestor.Application.Helpers.Connection.User, ";password=", Gestor.Application.Helpers.Connection.Password, ";" }); } public static async Task GetPool() { string pool; Gestor.Model.API.ConnectionAddress connectionAddress = await Gestor.Application.Helpers.Connection.Get("Server/Pool", true, false); if (connectionAddress != null) { Gestor.Application.Helpers.Connection.Pool = (new Token()).Decrypt(connectionAddress.get_Pool()); pool = Gestor.Application.Helpers.Connection.Pool; } else { pool = ""; } return pool; } public static async Task Post(string command, T keyValues) where T : class { Gestor.Application.Helpers.T t; Uri uri = new Uri(Address.GestorApi(), command); object obj = keyValues; JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); jsonSerializerSetting.set_ReferenceLoopHandling(1); jsonSerializerSetting.set_MissingMemberHandling(0); StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json"); HttpClient httpClient = new HttpClient(); httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, stringContent); if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent) { if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); } t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); } else { t = default(Gestor.Application.Helpers.T); } return t; } public static async Task Post(string command, object keyValues) where T : class { Gestor.Application.Helpers.T t; Uri uri = new Uri(Address.GestorApi(), command); object obj = keyValues; JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); jsonSerializerSetting.set_ReferenceLoopHandling(1); jsonSerializerSetting.set_MissingMemberHandling(0); StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json"); HttpClient httpClient = new HttpClient(); httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, stringContent); if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent) { if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); } t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); } else { t = default(Gestor.Application.Helpers.T); } return t; } public static async Task Put(string command, T keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), command); object obj = keyValues; JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); jsonSerializerSetting.set_ReferenceLoopHandling(1); StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json"); HttpClient httpClient = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent); if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); } Gestor.Application.Helpers.T t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); return t; } public static async Task Put(string command, object keyValues) where T : class { Gestor.Application.Helpers.T t; Uri uri = new Uri(Address.GestorApi(), command); object obj = keyValues; JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); jsonSerializerSetting.set_ReferenceLoopHandling(1); StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json"); HttpClient httpClient = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent); if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent) { if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null); } t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); } else { t = default(Gestor.Application.Helpers.T); } return t; } public static async void PutError(T keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), "Error/Objeto"); object obj = keyValues; JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); jsonSerializerSetting.set_ReferenceLoopHandling(1); StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json"); HttpClient httpClient = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); if (await httpClient.PutAsync(uri, stringContent).get_StatusCode() != HttpStatusCode.NoContent) { throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " Error"), null); } } internal static async Task SaveInAzureStorage() { bool flag; string str = string.Format("{0}Data", Address.GestorApi()); try { using (HttpClient httpClient = new HttpClient()) { httpClient.get_DefaultRequestHeaders().Clear(); httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage async = await httpClient.GetAsync(str); if (async.get_IsSuccessStatusCode()) { flag = await async.get_Content().ReadAsStringAsync() == "true"; return flag; } } httpClient = null; } catch { } flag = false; return flag; } internal static bool TryConnect(string connectionString, int retryCount = 1) { bool flag; List exceptions = new List(); int num = 0; Label1: while (num < retryCount) { try { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); } flag = true; } catch (Exception exception) { exceptions.Add(exception); goto Label0; } return flag; } return exceptions.Count == 0; Label0: num++; goto Label1; } internal static async Task UploadFile(UploadFile upload, string path = "ad") { bool flag; bool flag1; Uri apiAD = Address.get_ApiAD(); string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(Gestor.Application.Helpers.Connection.ConnectionAddress.get_AzureStorage()) }; Uri uri = apiAD.Append(strArrays); string[] strArrays1 = new string[] { path }; Uri uri1 = uri.Append(strArrays1); try { using (HttpClient httpClient = new HttpClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; httpClient.get_DefaultRequestHeaders().Clear(); httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey())); HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri1, new StringContent(JsonConvert.SerializeObject(upload), Encoding.UTF8, "application/json")); flag1 = (!httpResponseMessage.get_IsSuccessStatusCode() ? false : httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent); flag = flag1; return flag; } } catch { } flag = false; return flag; } } }