using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Agger.Registro; using Gestor.Common.Security; using Gestor.Common.Validation; using Gestor.Model.API; using Newtonsoft.Json; 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 ConnectionAddress ConnectionAddress { get; set; } public static string LinkAggilizador { get; set; } public static string UrlCentralSegurado { get; set; } public static string BasicKey() { return $"{ApplicationHelper.NumeroSerial}:{Funcoes.GetNetworkTime().ToUniversalTime().Ticks}".Base64Encode(); } public static string Base64Encode(this string plainText) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return new Token().Encrypt(plainText); } public static string EncodeBase64(this string plainText) { try { return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText)); } catch { } return string.Empty; } public static async Task GetPool() { ConnectionAddress val = await Get("Server/Pool"); if (val == null) { return ""; } Pool = new Token().Decrypt(val.Pool); return Pool; } public static string GetConnection(bool tryconnect = true) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03b5: Unknown result type (might be due to invalid IL or missing references) //IL_03c0: Unknown result type (might be due to invalid IL or missing references) //IL_03cb: Unknown result type (might be due to invalid IL or missing references) //IL_03d6: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Unknown result type (might be due to invalid IL or missing references) //IL_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Expected O, but got Unknown try { Token val = new Token(); RegistryHelper val2 = new RegistryHelper(ApplicationHelper.Subkey); bool flag = false; string azureStorage = "ad1"; if (ApplicationHelper.Conectado) { List result = Get>($"Server/{ApplicationHelper.IdFornecedor}").Result; for (int i = 0; i < result.Count; i++) { string text = val.AggerEncrypt(val.Decrypt(result[i].Server)); string text2 = val.AggerEncrypt(val.Decrypt(result[i].Catalog)); string text3 = val.AggerEncrypt(val.Decrypt(result[i].User)); string text4 = val.AggerEncrypt(val.Decrypt(result[i].Password)); string text5 = val.AggerEncrypt(val.Decrypt(result[i].Pool)); string text6 = result[i].Type.ToString(); LinkAggilizador = (string.IsNullOrEmpty(result[i].Aggilizador) ? null : result[i].Aggilizador); UrlCentralSegurado = (string.IsNullOrEmpty(result[i].UrlCentralSegurado) ? null : result[0].UrlCentralSegurado); flag = result[i].UsaAzureStorage; azureStorage = (string.IsNullOrEmpty(result[i].AzureStorage) ? "ad1" : val.Decrypt(result[i].AzureStorage)); val2.Write($"SERVER{i + 1}", text, true); val2.Write($"DB{i + 1}", text2, true); val2.Write($"USER{i + 1}", text3, true); val2.Write($"PASSWORD{i + 1}", text4, true); val2.Write($"POOL{i + 1}", text5, true); val2.Write($"TYPE{i + 1}", text6, true); } } string result2 = ""; for (int j = 0; j < 3 && val2.Read($"SERVER{j + 1}", true) != null; j++) { if (val2.Read($"TYPE{j + 1}", true) == "4") { continue; } Server = val.AggerDecrypt(val2.Read($"SERVER{j + 1}", true)); Catalog = val.AggerDecrypt(val2.Read($"DB{j + 1}", true)); User = val.AggerDecrypt(val2.Read($"USER{j + 1}", true)); Password = val.AggerDecrypt(val2.Read($"PASSWORD{j + 1}", true)); Pool = val.AggerDecrypt(val2.Read($"POOL{j + 1}", true)); Type = val2.Read($"TYPE{j + 1}", true); if (!flag) { flag = Task.Run(async () => await SaveInAzureStorage()).Result; } ConnectionAddress = new ConnectionAddress { Server = Server, Catalog = Catalog, User = User, Password = Password, Pool = Pool, Aggilizador = LinkAggilizador, UrlCentralSegurado = UrlCentralSegurado, UsaAzureStorage = flag, AzureStorage = azureStorage, Type = int.Parse(ValidationHelper.IsNotNullOrEmpty(Type) ? "0" : Type) }; string connectionString = GetConnectionString(); if (!tryconnect || TryConnect(connectionString)) { result2 = connectionString; break; } } return result2; } catch (Exception) { return null; } } public static string GetConnectionString() { return "Server=" + Server + ";initial catalog=" + Catalog + ";user=" + User + ";password=" + Password + ";"; } internal static bool TryConnect(string connectionString, int retryCount = 1) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown List list = new List(); for (int i = 0; i < retryCount; i++) { try { SqlConnection val = new SqlConnection(connectionString); try { ((DbConnection)(object)val).Open(); } finally { ((IDisposable)val)?.Dispose(); } return true; } catch (Exception item) { list.Add(item); } } return list.Count == 0; } public static string GetAdConnection(string serial) { ApplicationHelper.NumeroSerial = serial; if (string.IsNullOrWhiteSpace(Server)) { GetAdConnection(serial); } return "Server=" + Server + ";initial catalog=" + Catalog + "AD;user=" + User + ";password=" + Password + ";"; } public static async Task Get(string command, bool autorizar = true, bool verificarConexao = false) where T : class { Uri uri = new Uri(Address.GestorApi(), command); HttpClient val = new HttpClient(); if (autorizar) { val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage val2; try { val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception) { ApplicationHelper.Conectado = false; return null; } if (verificarConexao) { ApplicationHelper.Conectado = true; } if (val2.StatusCode == HttpStatusCode.NoContent) { return null; } if (val2.StatusCode != HttpStatusCode.OK) { throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null); } return JsonConvert.DeserializeObject(val2.Content.ReadAsStringAsync().Result); } public static async Task Get(string command, bool autorizar = true) { Uri uri = new Uri(Address.GestorApi(), command); HttpClient val = new HttpClient(); if (autorizar) { val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage val2; try { val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception) { return HttpStatusCode.InternalServerError; } return val2.StatusCode; } public static async Task Post(string command, T keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), command); StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings { ReferenceLoopHandling = (ReferenceLoopHandling)1, MissingMemberHandling = (MissingMemberHandling)0 }), Encoding.UTF8, "application/json"); HttpClient val2 = new HttpClient(); val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage val3 = await val2.PostAsync(uri, (HttpContent)(object)val); if (val3.StatusCode == HttpStatusCode.NoContent) { return null; } if (val3.StatusCode != HttpStatusCode.OK) { throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null); } return JsonConvert.DeserializeObject(val3.Content.ReadAsStringAsync().Result); } public static async Task Post(string command, object keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), command); StringContent val = new StringContent(JsonConvert.SerializeObject(keyValues, (Formatting)1, new JsonSerializerSettings { ReferenceLoopHandling = (ReferenceLoopHandling)1, MissingMemberHandling = (MissingMemberHandling)0 }), Encoding.UTF8, "application/json"); HttpClient val2 = new HttpClient(); val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpResponseMessage val3 = await val2.PostAsync(uri, (HttpContent)(object)val); if (val3.StatusCode == HttpStatusCode.NoContent) { return null; } if (val3.StatusCode != HttpStatusCode.OK) { throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null); } return JsonConvert.DeserializeObject(val3.Content.ReadAsStringAsync().Result); } public static async Task Put(string command, T keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), command); StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings { ReferenceLoopHandling = (ReferenceLoopHandling)1 }), Encoding.UTF8, "application/json"); HttpClient val2 = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); HttpResponseMessage obj = await val2.PutAsync(uri, (HttpContent)(object)val); if (obj.StatusCode != HttpStatusCode.OK) { throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null); } return JsonConvert.DeserializeObject(obj.Content.ReadAsStringAsync().Result); } public static async Task Put(string command, object keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), command); StringContent val = new StringContent(JsonConvert.SerializeObject(keyValues, (Formatting)1, new JsonSerializerSettings { ReferenceLoopHandling = (ReferenceLoopHandling)1 }), Encoding.UTF8, "application/json"); HttpClient val2 = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); HttpResponseMessage val3 = await val2.PutAsync(uri, (HttpContent)(object)val); if (val3.StatusCode == HttpStatusCode.NoContent) { return null; } if (val3.StatusCode != HttpStatusCode.OK) { throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null); } return JsonConvert.DeserializeObject(val3.Content.ReadAsStringAsync().Result); } public static async void PutError(T keyValues) where T : class { Uri uri = new Uri(Address.GestorApi(), "Error/Objeto"); StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings { ReferenceLoopHandling = (ReferenceLoopHandling)1 }), Encoding.UTF8, "application/json"); HttpClient val2 = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); if ((await val2.PutAsync(uri, (HttpContent)(object)val)).StatusCode != HttpStatusCode.NoContent) { throw new Exception("Api connection Error " + Environment.NewLine + " Error", null); } } public static async Task Delete(string command) { Uri uri = new Uri(Address.GestorApi(), command); HttpClient val = new HttpClient(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey()); if ((await val.DeleteAsync(uri)).StatusCode != HttpStatusCode.OK) { throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null); } return true; } internal static async Task DownloadFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad", bool forceDownload = false) { azureStorage = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage); Uri uri = Address.ApiAD.Append(AdApiV2(azureStorage)).Append(path).Append(ano.ToString()) .Append(id.ToString()) .Append(extensao.Replace(".", string.Empty)); try { string path2 = $"{Path.GetTempPath()}{id}{extensao}"; if (!forceDownload && File.Exists(path2)) { return File.ReadAllBytes(path2); } HttpClient client = new HttpClient(); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ((HttpHeaders)client.DefaultRequestHeaders).Clear(); ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey()); HttpResponseMessage val = await client.GetAsync(uri); if (val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NotFound) { return await val.Content.ReadAsByteArrayAsync(); } } finally { ((IDisposable)client)?.Dispose(); } } catch { } return null; } internal static async Task SaveInAzureStorage() { string text = $"{Address.GestorApi()}Data"; try { HttpClient client = new HttpClient(); try { ((HttpHeaders)client.DefaultRequestHeaders).Clear(); ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey()); HttpResponseMessage val = await client.GetAsync(text); if (val.IsSuccessStatusCode) { return await val.Content.ReadAsStringAsync() == "true"; } } finally { ((IDisposable)client)?.Dispose(); } } catch { } return false; } internal static async Task UploadFile(UploadFile upload, string path = "ad") { Uri uri = Address.ApiAD.Append(AdApiV2(ConnectionAddress.AzureStorage)).Append(path); try { HttpClient client = new HttpClient(); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ((HttpHeaders)client.DefaultRequestHeaders).Clear(); ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey()); HttpResponseMessage val = await client.PutAsync(uri, (HttpContent)new StringContent(JsonConvert.SerializeObject((object)upload), Encoding.UTF8, "application/json")); return val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent; } finally { ((IDisposable)client)?.Dispose(); } } catch { } return false; } internal static async Task DeleteFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad") { azureStorage = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage); Uri uri = Address.ApiAD.Append(AdApiV2(azureStorage)).Append(path).Append(ano.ToString()) .Append(id.ToString()) .Append(extensao.Replace(".", string.Empty)); try { HttpClient client = new HttpClient(); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ((HttpHeaders)client.DefaultRequestHeaders).Clear(); ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey()); HttpResponseMessage val = await client.DeleteAsync(uri); return val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent; } finally { ((IDisposable)client)?.Dispose(); } } catch { } return false; } internal static async Task EspacoUsadoAzureInBytes(string path = "") { Uri uri = Address.ApiAD.Append(AdApiV2(ConnectionAddress.AzureStorage)).Append("tamanho"); if (!string.IsNullOrEmpty(path)) { uri.Append(path); } try { HttpClient client = new HttpClient(); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ((HttpHeaders)client.DefaultRequestHeaders).Clear(); ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey()); HttpResponseMessage val = await client.GetAsync(uri); if (val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent) { return double.Parse(await val.Content.ReadAsStringAsync()); } } finally { ((IDisposable)client)?.Dispose(); } } catch { } return 0.0; } private static string AdApiV2(string storage) { if (Address.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) => current.TrimEnd(new char[1] { '/' }) + "/" + path.TrimStart(new char[1] { '/' }))); } }