From 674ca83ba9243a9e95a7568c797668dab6aee26a Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Mon, 30 Mar 2026 10:35:25 -0300 Subject: feat: upload files --- Gestor.Application/Helpers/ConnectionHelper.cs | 521 +++++++++++++++++++++++++ 1 file changed, 521 insertions(+) create mode 100644 Gestor.Application/Helpers/ConnectionHelper.cs (limited to 'Gestor.Application/Helpers/ConnectionHelper.cs') diff --git a/Gestor.Application/Helpers/ConnectionHelper.cs b/Gestor.Application/Helpers/ConnectionHelper.cs new file mode 100644 index 0000000..1b364ca --- /dev/null +++ b/Gestor.Application/Helpers/ConnectionHelper.cs @@ -0,0 +1,521 @@ +using Agger.Registro; +using Gestor.Application.Migration; +using Gestor.Common.Exceptions; +using Gestor.Model.API; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; + +namespace Gestor.Application.Helpers +{ + public class ConnectionHelper + { + public static bool BancoAtualizado + { + get; + set; + } + + public ConnectionHelper() + { + } + + public async Task AtualizarBanco() + { + string str; + bool flag = await (new Migrator()).Execute(); + ConnectionHelper.BancoAtualizado = flag; + if (flag) + { + str = null; + } + else + { + str = "HOUVE UM PROBLEMA AO ATUALIZAR O BANCO DE DADOS."; + } + return str; + } + + public bool BDConvertido() + { + bool flag; + try + { + using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(false))) + { + sqlConnection.Open(); + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT OBJECT_ID('dbo.AtualizacaoDados', 'U')"; + if (sqlCommand.ExecuteScalar() == DBNull.Value) + { + flag = true; + return flag; + } + } + using (SqlCommand sqlCommand1 = sqlConnection.CreateCommand()) + { + sqlCommand1.CommandText = "SELECT COUNT(IdArquivo) FROM AtualizacaoDados"; + flag = (int)sqlCommand1.ExecuteScalar() == 0; + } + } + } + catch + { + return true; + } + return flag; + } + + public static async Task CheckDatabase() + { + string message; + string str; + try + { + bool flag = await ConnectionHelper.DatabaseExists(); + bool flag1 = await ConnectionHelper.LoginExists(); + bool flag2 = await ConnectionHelper.UserExists(); + bool flag3 = false; + if (!(flag & flag1 & flag2)) + { + if (!flag) + { + flag = await ConnectionHelper.CreateDatabase(); + } + if (flag) + { + if (!flag1) + { + bool flag4 = await ConnectionHelper.CreateLogin(); + bool flag5 = flag4; + flag3 = flag4; + flag1 = flag5; + } + if (flag1) + { + if (!flag2) + { + flag2 = await ConnectionHelper.CreateUser(); + } + if (flag3) + { + int num = 10; + while (num > 1) + { + try + { + using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(true))) + { + sqlConnection.Open(); + break; + } + } + catch + { + Thread.Sleep(10000); + num--; + } + } + } + if (!flag2) + { + str = "ERRO AO CRIAR USUÁRIO"; + } + else + { + str = null; + } + message = str; + } + else + { + message = "ERRO AO CRIAR LOGIN"; + } + } + else + { + message = "ERRO AO CRIAR BANCO DE DADOS"; + } + } + else + { + message = null; + } + } + catch (ValidationException validationException) + { + message = validationException.Message; + } + catch (Exception exception) + { + message = "ERRO AO CRIAR BANCO DE DADOS"; + } + return message; + } + + private static async Task CreateDatabase() + { + bool flag; + bool i; + string str = Uri.EscapeDataString(ApplicationHelper.NumeroSerial); + if (await ConnectionHelper.Post(string.Concat("Data/CreateData?token=", str)) != "ERRO INTERNO") + { + int num = 0; + for (i = false; num < 24 && !i; i = await ConnectionHelper.DatabaseExists()) + { + await Task.Delay(5000); + num++; + } + flag = i; + } + else + { + flag = false; + } + return flag; + } + + private static async Task CreateLogin() + { + bool flag; + bool i; + if (await ConnectionHelper.Post("Data/CreateLogin") != "ERRO INTERNO") + { + int num = 0; + for (i = false; num < 24 && !i; i = await ConnectionHelper.Get("Data/ServerLoginExists", true) == null) + { + await Task.Delay(5000); + num++; + } + flag = i; + } + else + { + flag = false; + } + return flag; + } + + private static async Task CreateUser() + { + bool flag; + bool i; + if (await ConnectionHelper.Post("Data/CreateUser") != "ERRO INTERNO") + { + int num = 0; + for (i = false; num < 24 && !i; i = await ConnectionHelper.Get("Data/UserExists", true) == null) + { + await Task.Delay(5000); + num++; + } + flag = i; + } + else + { + flag = false; + } + return flag; + } + + private static async Task DatabaseExists() + { + return await ConnectionHelper.Get("Data/DataExists", true) == null; + } + + private static async Task DatabaseTest() + { + return await ConnectionHelper.Get("Data/Verify", true); + } + + public bool ExisteEmpresa() + { + bool flag; + try + { + using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(false))) + { + sqlConnection.Open(); + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT OBJECT_ID (N'empresa', N'U')"; + if (sqlCommand.ExecuteScalar() == DBNull.Value) + { + flag = false; + return flag; + } + } + using (SqlCommand sqlCommand1 = sqlConnection.CreateCommand()) + { + sqlCommand1.CommandText = "SELECT COUNT(idempresa) FROM empresa WHERE idempresa = 1"; + flag = (int)sqlCommand1.ExecuteScalar() > 0; + } + } + } + catch + { + return true; + } + return flag; + } + + private static async Task Get(string command, bool autorizar = true) + { + string str; + Uri uri = new Uri(Address.GestorApi(), command); + HttpClient httpClient = new HttpClient(); + httpClient.set_Timeout(new TimeSpan(0, 2, 0)); + HttpClient httpClient1 = httpClient; + if (autorizar) + { + httpClient1.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey())); + } + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; + try + { + ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient1.GetAsync(uri).ConfigureAwait(false); + HttpResponseMessage httpResponseMessage = await configuredTaskAwaitable; + if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK) + { + str = null; + } + else + { + str = await httpResponseMessage.get_Content().ReadAsStringAsync(); + } + } + catch (Exception exception) + { + str = "ERRO INTERNO"; + } + return str; + } + + internal static async Task HasLogin(string connectionString) + { + bool flag1 = await Task.Run(() => { + bool flag; + List exceptions = new List(); + try + { + using (SqlConnection sqlConnection = new SqlConnection(connectionString)) + { + sqlConnection.Open(); + using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) + { + sqlCommand.CommandText = "SELECT 1 FROM [dbo].[usuario] WHERE [removido] IS NULL OR [removido] = '0'"; + SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); + if (sqlDataReader.HasRows) + { + sqlDataReader.Close(); + sqlCommand.CommandText = "SELECT 1 FROM [dbo].[empresa] WHERE [idempresa] = 1"; + sqlDataReader = sqlCommand.ExecuteReader(); + if (sqlDataReader.HasRows) + { + sqlDataReader.Close(); + sqlCommand.CommandText = "SELECT 1 FROM [dbo].[vendedor] WHERE [corretora] = '1'"; + sqlDataReader = sqlCommand.ExecuteReader(); + if (sqlDataReader.HasRows) + { + sqlDataReader.Close(); + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + } + } + catch (Exception exception) + { + exceptions.Add(exception); + return exceptions.Count == 0; + } + return flag; + }); + return flag1; + } + + private static async Task LoginExists() + { + return await ConnectionHelper.Get("Data/ServerLoginExists", true) == null; + } + + private static async Task Post(string command) + { + string str; + Uri uri = new Uri(Address.GestorApi(), command); + 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; + try + { + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, null); + if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK) + { + str = null; + } + else + { + str = await httpResponseMessage.get_Content().ReadAsStringAsync(); + } + } + catch (Exception exception) + { + str = "ERRO INTERNO"; + } + return str; + } + + public async Task> PrimeiroAcesso() + { + Tuple tuple; + Tuple tuple1; + string connection = Gestor.Application.Helpers.Connection.GetConnection(false); + if (!await ConnectionHelper.TryConnect(connection, 1)) + { + if (await ConnectionHelper.DatabaseExists()) + { + bool flag = !await ConnectionHelper.LoginExists(); + if (flag) + { + flag = !await ConnectionHelper.CreateLogin(); + } + if (!flag) + { + flag = !await ConnectionHelper.UserExists(); + if (flag) + { + flag = !await ConnectionHelper.CreateUser(); + } + if (flag) + { + tuple = new Tuple(false, false); + connection = null; + return tuple; + } + } + else + { + tuple = new Tuple(false, false); + connection = null; + return tuple; + } + } + else + { + tuple = new Tuple(false, false); + connection = null; + return tuple; + } + } + tuple1 = (!await ConnectionHelper.HasLogin(connection) ? new Tuple(true, false) : new Tuple(true, true)); + tuple = tuple1; + connection = null; + return tuple; + } + + internal static async Task TryConnect(string connectionString, int retryCount = 1) + { + bool flag1 = await Task.Run(() => { + bool flag; + List exceptions = new List(); + int num = 0; + Label1: + while (num < retryCount) + { + try + { + using (SqlConnection sqlConnection = new SqlConnection(string.Concat(connectionString, "Connection Timeout=5"))) + { + sqlConnection.Open(); + } + flag = true; + } + catch (Exception exception) + { + exceptions.Add(exception); + goto Label0; + } + return flag; + } + return exceptions.Count == 0; + Label0: + num++; + goto Label1; + }); + return flag1; + } + + private static async Task UserExists() + { + return await ConnectionHelper.Get("Data/UserExists", true) == null; + } + + public async Task VerifyConnection() + { + string str; + try + { + if (!await ConnectionHelper.TryConnect(Gestor.Application.Helpers.Connection.GetConnection(false), 1)) + { + string str1 = await ConnectionHelper.DatabaseTest(); + if (str1 == null) + { + string str2 = string.Concat(Gestor.Application.Helpers.Connection.ConnectionAddress.get_Catalog(), ".cfg"); + string str3 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Data_", str2); + string str4 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Files_", str2); + string str5 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Sign_", str2); + if (File.Exists(str3)) + { + File.Delete(str3); + } + if (File.Exists(str4)) + { + File.Delete(str4); + } + if (File.Exists(str5)) + { + File.Delete(str5); + } + string str6 = await ConnectionHelper.CheckDatabase(); + await Task.Delay(2000); + str = str6; + } + else + { + str = str1; + } + } + else + { + str = null; + } + } + catch (Exception exception) + { + str = "ERRO AO CONECTAR NO BANCO DE DADOS DA CORRETORA"; + } + return str; + } + } +} \ No newline at end of file -- cgit v1.2.3