From 1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Mon, 30 Mar 2026 10:38:18 -0300 Subject: chore: location --- Gestor.Application/Helpers/ApplicationHelper.cs | 98 - Gestor.Application/Helpers/ArquivoDigital.cs | 65 - Gestor.Application/Helpers/AssinadorHelper.cs | 211 - Gestor.Application/Helpers/BindingEnumHelper.cs | 56 - Gestor.Application/Helpers/BindingHelper.cs | 239 - Gestor.Application/Helpers/Connection.cs | 632 -- Gestor.Application/Helpers/ConnectionHelper.cs | 521 -- Gestor.Application/Helpers/CustomLinq.cs | 421 -- Gestor.Application/Helpers/DataGridExtensions.cs | 83 - Gestor.Application/Helpers/Erro.cs | 24 - Gestor.Application/Helpers/Funcoes.cs | 6825 -------------------- Gestor.Application/Helpers/HttpHelper.cs | 103 - Gestor.Application/Helpers/Instancia.cs | 75 - Gestor.Application/Helpers/InstanciaAssinador.cs | 44 - Gestor.Application/Helpers/LicenseHelper.cs | 572 -- Gestor.Application/Helpers/MailHelper.cs | 745 --- .../Helpers/NotifyPropertyChangedExtension.cs | 23 - .../Helpers/ObrigatorioValidationRule.cs | 34 - Gestor.Application/Helpers/PasswordBoxAssistant.cs | 95 - Gestor.Application/Helpers/PipeClient.cs | 52 - Gestor.Application/Helpers/PipeServer.cs | 115 - Gestor.Application/Helpers/QueryableHelper.cs | 26 - Gestor.Application/Helpers/Recursos.cs | 170 - Gestor.Application/Helpers/TipoToggle.cs | 14 - Gestor.Application/Helpers/ViewHelper.cs | 462 -- 25 files changed, 11705 deletions(-) delete mode 100644 Gestor.Application/Helpers/ApplicationHelper.cs delete mode 100644 Gestor.Application/Helpers/ArquivoDigital.cs delete mode 100644 Gestor.Application/Helpers/AssinadorHelper.cs delete mode 100644 Gestor.Application/Helpers/BindingEnumHelper.cs delete mode 100644 Gestor.Application/Helpers/BindingHelper.cs delete mode 100644 Gestor.Application/Helpers/Connection.cs delete mode 100644 Gestor.Application/Helpers/ConnectionHelper.cs delete mode 100644 Gestor.Application/Helpers/CustomLinq.cs delete mode 100644 Gestor.Application/Helpers/DataGridExtensions.cs delete mode 100644 Gestor.Application/Helpers/Erro.cs delete mode 100644 Gestor.Application/Helpers/Funcoes.cs delete mode 100644 Gestor.Application/Helpers/HttpHelper.cs delete mode 100644 Gestor.Application/Helpers/Instancia.cs delete mode 100644 Gestor.Application/Helpers/InstanciaAssinador.cs delete mode 100644 Gestor.Application/Helpers/LicenseHelper.cs delete mode 100644 Gestor.Application/Helpers/MailHelper.cs delete mode 100644 Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs delete mode 100644 Gestor.Application/Helpers/ObrigatorioValidationRule.cs delete mode 100644 Gestor.Application/Helpers/PasswordBoxAssistant.cs delete mode 100644 Gestor.Application/Helpers/PipeClient.cs delete mode 100644 Gestor.Application/Helpers/PipeServer.cs delete mode 100644 Gestor.Application/Helpers/QueryableHelper.cs delete mode 100644 Gestor.Application/Helpers/Recursos.cs delete mode 100644 Gestor.Application/Helpers/TipoToggle.cs delete mode 100644 Gestor.Application/Helpers/ViewHelper.cs (limited to 'Gestor.Application/Helpers') diff --git a/Gestor.Application/Helpers/ApplicationHelper.cs b/Gestor.Application/Helpers/ApplicationHelper.cs deleted file mode 100644 index 1250a2e..0000000 --- a/Gestor.Application/Helpers/ApplicationHelper.cs +++ /dev/null @@ -1,98 +0,0 @@ -using Agger.Registro; -using Gestor.Common.Helpers; -using System; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public class ApplicationHelper - { - private static string _numeroSerial; - - private const string ChaveSerial = "NS"; - - public static bool Beta - { - get; - set; - } - - public static DateTime ChecagemVersao - { - get; - set; - } - - public static bool Conectado - { - get; - set; - } - - public static long IdFornecedor - { - get; - set; - } - - public static string NumeroSerial - { - get - { - return ApplicationHelper._numeroSerial ?? ApplicationHelper.GetSerialNumber(); - } - set - { - ApplicationHelper._numeroSerial = value; - } - } - - public static string Subkey - { - get; - set; - } - - public static Version Versao - { - get; - set; - } - - static ApplicationHelper() - { - ApplicationHelper.Conectado = true; - ApplicationHelper.Beta = false; - ApplicationHelper.ChecagemVersao = Funcoes.GetNetworkTime(); - } - - public ApplicationHelper() - { - } - - internal static string GetSerialNumber() - { - string numeroSerial; - string str; - try - { - string str1 = (new RegistryHelper(ApplicationHelper.Subkey)).Read("NS", true); - if (string.IsNullOrEmpty(str1)) - { - str = null; - } - else - { - str = EncryptionHelper.Decrypt(str1); - } - ApplicationHelper.NumeroSerial = str; - numeroSerial = ApplicationHelper.NumeroSerial; - } - catch (Exception exception) - { - numeroSerial = null; - } - return numeroSerial; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/ArquivoDigital.cs b/Gestor.Application/Helpers/ArquivoDigital.cs deleted file mode 100644 index c140906..0000000 --- a/Gestor.Application/Helpers/ArquivoDigital.cs +++ /dev/null @@ -1,65 +0,0 @@ -using ArquivoDigital.Infrastructure.UnitOfWork.Logic; -using Gestor.Application.Servicos.Generic; -using Gestor.Model.Domain.Common; -using System; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - -namespace Gestor.Application.Helpers -{ - public static class ArquivoDigital - { - public static string ConexaoAd; - - public static string Banco - { - get; - set; - } - - public static UnitOfWork Commited - { - get - { - return Gestor.Application.Helpers.ArquivoDigital.UnitOfWork(true, false); - } - } - - public static UnitOfWork Read - { - get - { - return Gestor.Application.Helpers.ArquivoDigital.UnitOfWork(false, false); - } - } - - public static string Tabela - { - get; - set; - } - - static ArquivoDigital() - { - Gestor.Application.Helpers.ArquivoDigital.ConexaoAd = null; - Gestor.Application.Helpers.ArquivoDigital.Tabela = "arquivodigital"; - } - - public static void SetConnection(string banco = "") - { - ControleArquivoDigital controleArquivoDigital = (string.IsNullOrEmpty(banco) ? (new BaseServico()).ArquivoDigital().Result : (new BaseServico()).ArquivoDigital(banco).Result); - Gestor.Application.Helpers.ArquivoDigital.Banco = controleArquivoDigital.get_Catalogo(); - Gestor.Application.Helpers.ArquivoDigital.Tabela = (string.IsNullOrWhiteSpace(controleArquivoDigital.get_Tabela()) ? "arquivodigital" : controleArquivoDigital.get_Tabela()); - Gestor.Application.Helpers.ArquivoDigital.ConexaoAd = string.Concat(new string[] { "Server=", Connection.Server, ";initial catalog=", controleArquivoDigital.get_Catalogo(), ";user=", Connection.User, ";password=", Connection.Password, ";" }); - } - - private static UnitOfWork UnitOfWork(bool withTransaction = true, bool reconect = false) - { - if (Gestor.Application.Helpers.ArquivoDigital.ConexaoAd == null) - { - Gestor.Application.Helpers.ArquivoDigital.SetConnection(""); - } - return new UnitOfWork(Gestor.Application.Helpers.ArquivoDigital.ConexaoAd, Gestor.Application.Helpers.ArquivoDigital.Tabela, withTransaction); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/AssinadorHelper.cs b/Gestor.Application/Helpers/AssinadorHelper.cs deleted file mode 100644 index 2a6939d..0000000 --- a/Gestor.Application/Helpers/AssinadorHelper.cs +++ /dev/null @@ -1,211 +0,0 @@ -using Agger.Registro; -using Assinador.Model.Domain; -using Newtonsoft.Json; -using Sign.Modelos; -using System; -using System.Diagnostics; -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 AssinadorHelper - { - private static ParametrosAssinaturaAssinador _parametros; - - public const string Authorization = "Authorization"; - - public const string Server = "Server"; - - public const string Contrato = "Purchase"; - - public const string Adquirir = "Purchase/BuyPackage"; - - public const string Disponiveis = "Sign/Availble"; - - public const string Contratadas = "Sign/Purchased"; - - private static string ApiKey - { - get; - set; - } - - public static ParametrosAssinaturaAssinador Parametros - { - get - { - return AssinadorHelper._parametros; - } - set - { - AssinadorHelper._parametros = value; - if (value == null) - { - return; - } - Sign.Modelos.Remetente remetente = new Sign.Modelos.Remetente(); - remetente.set_Id(ApplicationHelper.IdFornecedor); - remetente.set_Documento(value.get_Documento()); - remetente.set_Email(value.get_Email()); - remetente.set_Nome(value.get_Nome()); - remetente.set_Serial(ApplicationHelper.NumeroSerial); - AssinadorHelper.Remetente = remetente; - } - } - - public static Sign.Modelos.Remetente Remetente - { - get; - set; - } - - private static string Base64EncodeBasic(string plainText) - { - return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText)); - } - - public static string BasicKey(this string serial) - { - DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); - return AssinadorHelper.Base64EncodeBasic(string.Format("{0}:{1}", serial, universalTime.Ticks)); - } - - public static async Task Contratado(long id) - { - bool flag = await AssinadorHelper.Get(string.Format("{0}{1}/{2}/86", Address.GestorApi(), "Purchase", id), ApplicationHelper.NumeroSerial.BasicKey(), true) == "true"; - return flag; - } - - public static async Task Get(string command, string token = null, bool basic = false) - { - HttpStatusCode statusCode; - HttpResponseMessage httpResponseMessage; - string str = (basic ? "Basic" : "Token"); - Uri uri = new Uri(Address.GestorApi(), command); - HttpClient httpClient = new HttpClient(); - if (!string.IsNullOrWhiteSpace(token)) - { - httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token)); - } - 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; - } - - internal static async Task Get(string command, string token = null, bool basic = false) - where T : class - { - T t; - HttpResponseMessage httpResponseMessage; - string str = (basic ? "Basic" : "Token"); - Uri uri = new Uri(command); - HttpClient httpClient = new HttpClient(); - if (!string.IsNullOrWhiteSpace(token)) - { - httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token)); - } - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; - try - { - ConfiguredTaskAwaitable configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false); - httpResponseMessage = await configuredTaskAwaitable; - } - catch (Exception exception) - { - t = default(T); - return t; - } - if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK) - { - string result = httpResponseMessage.get_Content().ReadAsStringAsync().Result; - t = JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result); - } - else - { - t = default(T); - } - return t; - } - - public static async Task Key() - { - string str = null; - try - { - str = await AssinadorHelper.Get(string.Format("{0}{1}/86", Address.AssinadorApi(), "Authorization"), ApplicationHelper.NumeroSerial.BasicKey(), true); - } - catch (Exception exception) - { - } - string str1 = str; - str = null; - return str1; - } - - public static async Task Licencas(string key) - { - int num; - if (key != null) - { - int num1 = 0; - try - { - string str = await AssinadorHelper.Get(string.Format("{0}{1}/{2}", Address.AssinadorApi(), "Sign/Availble", ApplicationHelper.IdFornecedor), key, false); - num1 = int.Parse(str); - } - catch (Exception exception) - { - } - num = num1; - } - else - { - num = 0; - } - return num; - } - - internal static async Task Put(string command, T keyValues, string token = null, bool basic = false) - where T : class - { - T t; - string str = (basic ? "Basic" : "Token"); - Uri uri = new Uri(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; - if (!string.IsNullOrWhiteSpace(token)) - { - httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token)); - } - HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent); - if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK || httpResponseMessage.get_StatusCode() == HttpStatusCode.NoContent) - { - t = (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent ? JsonConvert.DeserializeObject(httpResponseMessage.get_Content().ReadAsStringAsync().Result) : default(T)); - } - else - { - t = default(T); - } - return t; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/BindingEnumHelper.cs b/Gestor.Application/Helpers/BindingEnumHelper.cs deleted file mode 100644 index 54e9330..0000000 --- a/Gestor.Application/Helpers/BindingEnumHelper.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.ComponentModel; -using System.Reflection; -using System.Text; - -namespace Gestor.Application.Helpers -{ - public class BindingEnumHelper - { - public BindingEnumHelper() - { - } - - public static string ConcatenarDescricoesEnum(string valores) - where TEnum : Enum - { - if (valores == null) - { - return null; - } - return BindingEnumHelper.ConcatenarDescricoesEnum(Array.ConvertAll(valores.Split(new char[] { ',' }), new Converter(int.Parse))); - } - - private static string ConcatenarDescricoesEnum(int[] valores) - where TEnum : Enum - { - StringBuilder stringBuilder = new StringBuilder(); - int[] numArray = valores; - for (int i = 0; i < (int)numArray.Length; i++) - { - int num = numArray[i]; - if (!Enum.IsDefined(typeof(TEnum), num)) - { - stringBuilder.Append("Valor desconhecido, "); - } - else - { - string str = BindingEnumHelper.ObterDescricaoEnum((TEnum)Enum.ToObject(typeof(TEnum), num)); - stringBuilder.Append(string.Concat(str, ", ")); - } - } - return stringBuilder.ToString().TrimEnd(new char[] { ',', ' ' }); - } - - private static string ObterDescricaoEnum(TEnum valor) - where TEnum : Enum - { - DescriptionAttribute[] customAttributes = (DescriptionAttribute[])valor.GetType().GetField(valor.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); - if (customAttributes == null || customAttributes.Length == 0) - { - return valor.ToString(); - } - return customAttributes[0].Description; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/BindingHelper.cs b/Gestor.Application/Helpers/BindingHelper.cs deleted file mode 100644 index 3c9d76e..0000000 --- a/Gestor.Application/Helpers/BindingHelper.cs +++ /dev/null @@ -1,239 +0,0 @@ -using CurrencyTextBoxControl; -using Gestor.Common.Helpers; -using Gestor.Model.Helper; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Data; - -namespace Gestor.Application.Helpers -{ - public static class BindingHelper - { - public static void AddBinding(object control, string path, ValidationRule rule = null) - { - Type type = control.GetType(); - Binding binding = new Binding() - { - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, - Path = new PropertyPath(path, Array.Empty()) - }; - if (rule != null) - { - binding.ValidationRules.Add(rule); - binding.ValidationRules[0].ValidatesOnTargetUpdated = true; - } - string name = type.Name; - if (name == "TextBox") - { - ((TextBox)control).SetBinding(TextBox.TextProperty, binding); - return; - } - if (name == "DatePicker") - { - ((DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, binding); - return; - } - if (name != "CurrencyTextBox") - { - return; - } - ((CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, binding); - } - - public static void AddValidationRule(object control, ValidationRule rule = null) - { - // - // Current member / type: System.Void Gestor.Application.Helpers.BindingHelper::AddValidationRule(System.Object,System.Windows.Controls.ValidationRule) - // File path: C:\AggerSeguros\Gestor.Application.exe - // - // Product version: 0.0.0.0 - // Exception in: System.Void AddValidationRule(System.Object,System.Windows.Controls.ValidationRule) - // - // Object reference not set to an instance of an object. - // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 - // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 - // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 - // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 - // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 - // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 - // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 - // - // mailto: JustDecompilePublicFeedback@telerik.com - - } - - private static List> AfterTreatment(bool withSelect, bool orderByLabel, List> comboData, List> comboValues, bool orderbyAttr = false) - { - List> list = comboData; - if (!withSelect) - { - list.RemoveAt(0); - } - list.AddRange(comboValues); - if (orderbyAttr) - { - Type type = typeof(T); - list = list.OrderBy, int?>((KeyValuePair s) => { - if (s.Key == string.Empty) - { - return new int?(0); - } - return EnumHelper.GetOrder((T)Enum.Parse(type, s.Key)); - }).ToList>(); - return list; - } - if (!orderByLabel) - { - return list; - } - list = ( - from in list - orderby Math.Sign(ValidationHelper.ToFloat(x.Key)), Math.Abs(ValidationHelper.ToFloat(x.Key)) - select ).ToList>(); - list = ( - from in list - orderby list.IndexOf(s) != 0, s.Value - select ).ToList>(); - return list; - } - - private static List> BeforeTreatment(string defaultValue, string defaultText) - { - defaultText = (defaultText == string.Empty ? "Selecione" : defaultText); - return new List>() - { - new KeyValuePair(defaultValue, defaultText) - }; - } - - public static List> BindingData(bool withSelect = true, bool enumDefault = true, string defaultValue = "", string defaultText = "", bool orderByLabel = false, bool showAll = false, bool orderbyAttr = false) - { - List> keyValuePairs = BindingHelper.BeforeTreatment(defaultValue, defaultText); - Type type = typeof(T); - List> list = Enum.GetNames(type).AsEnumerable().Where((string x) => { - if (showAll) - { - return true; - } - T t = (T)Enum.Parse(type, x); - bool? @default = EnumHelper.GetDefault(t); - bool hidden = EnumHelper.GetHidden(t); - if (@default.HasValue && @default.Value != enumDefault) - { - return false; - } - return !hidden; - }).Select>((string x) => { - T t = (T)Enum.Parse(type, x); - return new KeyValuePair(EnumHelper.Value(t), EnumHelper.GetDescription(t)); - }).ToList>(); - return BindingHelper.AfterTreatment(withSelect, orderByLabel, keyValuePairs, list, orderbyAttr); - } - - public static void DeleteValidationRule(object control) - { - Binding binding; - string name = control.GetType().Name; - if (name == "TextBox") - { - binding = BindingOperations.GetBinding((TextBox)control, TextBox.TextProperty) ?? new Binding() - { - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - binding.ValidationRules.Clear(); - ((TextBox)control).SetBinding(TextBox.TextProperty, binding); - return; - } - if (name == "DatePicker") - { - binding = BindingOperations.GetBinding((DatePicker)control, DatePicker.SelectedDateProperty) ?? new Binding() - { - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - binding.ValidationRules.Clear(); - ((DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, binding); - return; - } - if (name != "CurrencyTextBox") - { - return; - } - binding = BindingOperations.GetBinding((CurrencyTextBox)control, CurrencyTextBox.NumberProperty) ?? new Binding() - { - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - binding.ValidationRules.Clear(); - ((CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, binding); - } - - public static string GetPath(object control) - { - Binding binding; - PropertyPath path; - string name = control.GetType().Name; - if (name == "TextBox") - { - binding = BindingOperations.GetBinding((TextBox)control, TextBox.TextProperty); - if (binding == null) - { - return ""; - } - path = binding.Path; - } - else if (name == "DatePicker") - { - binding = BindingOperations.GetBinding((DatePicker)control, DatePicker.SelectedDateProperty); - if (binding == null) - { - return ""; - } - path = binding.Path; - } - else if (name == "CurrencyTextBox") - { - binding = BindingOperations.GetBinding((CurrencyTextBox)control, CurrencyTextBox.NumberProperty); - if (binding == null) - { - return ""; - } - path = binding.Path; - } - else if (name == "ComboBox") - { - binding = BindingOperations.GetBinding((ComboBox)control, Selector.SelectedItemProperty); - if (binding == null) - { - return ""; - } - path = binding.Path; - } - else - { - if (name != "AutoCompleteBox") - { - return ""; - } - binding = BindingOperations.GetBinding((AutoCompleteBox)control, AutoCompleteBox.SelectedItemProperty); - if (binding == null) - { - return ""; - } - path = binding.Path; - } - return path.Path; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/Connection.cs b/Gestor.Application/Helpers/Connection.cs deleted file mode 100644 index 7458e99..0000000 --- a/Gestor.Application/Helpers/Connection.cs +++ /dev/null @@ -1,632 +0,0 @@ -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; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/ConnectionHelper.cs b/Gestor.Application/Helpers/ConnectionHelper.cs deleted file mode 100644 index 1b364ca..0000000 --- a/Gestor.Application/Helpers/ConnectionHelper.cs +++ /dev/null @@ -1,521 +0,0 @@ -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 diff --git a/Gestor.Application/Helpers/CustomLinq.cs b/Gestor.Application/Helpers/CustomLinq.cs deleted file mode 100644 index 2900b2e..0000000 --- a/Gestor.Application/Helpers/CustomLinq.cs +++ /dev/null @@ -1,421 +0,0 @@ -using Gestor.Common.Validation; -using Gestor.Model.Domain.Relatorios; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public static class CustomLinq - { - public static List CustomNot(this List list, List property) - where T : class - { - if (property == null || property.Count == 0) - { - return list; - } - return list.Where((T x) => { - Func func8 = null; - Func func9 = null; - Func func10 = null; - Func func11 = null; - Func func12 = null; - Func func13 = null; - Func func14 = null; - List filtroPersonalizados = property; - Func u003cu003e9_21 = CustomLinq.u003cu003ec__2.u003cu003e9__2_1; - if (u003cu003e9_21 == null) - { - u003cu003e9_21 = (FiltroPersonalizado p) => p.get_Propriedade(); - CustomLinq.u003cu003ec__2.u003cu003e9__2_1 = u003cu003e9_21; - } - return filtroPersonalizados.GroupBy(u003cu003e9_21).ToList>().All>((IGrouping p) => { - Func func; - IGrouping strs = p; - Func u003cu003e9_23 = CustomLinq.u003cu003ec__2.u003cu003e9__2_3; - if (u003cu003e9_23 == null) - { - u003cu003e9_23 = (FiltroPersonalizado s) => s.get_SemValor(); - CustomLinq.u003cu003ec__2.u003cu003e9__2_3 = u003cu003e9_23; - } - if (strs.Any(u003cu003e9_23)) - { - IGrouping strs1 = p; - Func u003cu003e9_4 = func8; - if (u003cu003e9_4 == null) - { - Func func1 = (FiltroPersonalizado v) => { - bool value; - string str; - PropertyInfo propertyInfo1 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo1 != null ? propertyInfo1.GetValue(x) : false); - if (!value) - { - return true; - } - PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade()); - str = (propertyInfo != null ? propertyInfo.GetValue(x).ToString() : null); - return string.IsNullOrWhiteSpace(str); - }; - func = func1; - func8 = func1; - u003cu003e9_4 = func; - } - return strs1.All(u003cu003e9_4); - } - if (p.First().get_Tipo() == typeof(DateTime)) - { - IGrouping strs2 = p; - Func u003cu003e9_5 = func9; - if (u003cu003e9_5 == null) - { - Func func2 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo2 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo2 != null ? propertyInfo2.GetValue(x) : false); - if (!value) - { - return false; - } - return (DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != DateTime.Parse(v.get_ValorIncial()); - }; - func = func2; - func9 = func2; - u003cu003e9_5 = func; - } - return strs2.All(u003cu003e9_5); - } - if (p.First().get_Tipo() == typeof(long)) - { - IGrouping strs3 = p; - Func u003cu003e9_6 = func10; - if (u003cu003e9_6 == null) - { - Func func3 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo3 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo3 != null ? propertyInfo3.GetValue(x) : false); - if (!value) - { - return false; - } - return (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != long.Parse(v.get_ValorIncial()); - }; - func = func3; - func10 = func3; - u003cu003e9_6 = func; - } - return strs3.All(u003cu003e9_6); - } - if (p.First().get_Tipo() == typeof(int)) - { - IGrouping strs4 = p; - Func u003cu003e9_7 = func11; - if (u003cu003e9_7 == null) - { - Func func4 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo4 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo4 != null ? propertyInfo4.GetValue(x) : false); - if (!value) - { - return false; - } - return (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != int.Parse(v.get_ValorIncial()); - }; - func = func4; - func11 = func4; - u003cu003e9_7 = func; - } - return strs4.All(u003cu003e9_7); - } - if (p.First().get_Tipo() == typeof(decimal)) - { - IGrouping strs5 = p; - Func u003cu003e9_8 = func12; - if (u003cu003e9_8 == null) - { - Func func5 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo5 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo5 != null ? propertyInfo5.GetValue(x) : false); - if (!value) - { - return false; - } - return (decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != decimal.Parse(v.get_ValorIncial()); - }; - func = func5; - func12 = func5; - u003cu003e9_8 = func; - } - return strs5.All(u003cu003e9_8); - } - if (p.First().get_Tipo() != typeof(Enum)) - { - IGrouping strs6 = p; - Func u003cu003e9_10 = func14; - if (u003cu003e9_10 == null) - { - Func func6 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo6 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo6 != null ? propertyInfo6.GetValue(x) : false); - if (!value) - { - return false; - } - return !ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim())); - }; - func = func6; - func14 = func6; - u003cu003e9_10 = func; - } - return strs6.All(u003cu003e9_10); - } - IGrouping strs7 = p; - Func u003cu003e9_9 = func13; - if (u003cu003e9_9 == null) - { - Func func7 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo7 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo7 != null ? propertyInfo7.GetValue(x) : false); - if (!value) - { - return false; - } - return !ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x)).ToLower().Contains(v.get_ValorIncial().ToLower()); - }; - func = func7; - func13 = func7; - u003cu003e9_9 = func; - } - return strs7.All(u003cu003e9_9); - }); - }).ToList(); - } - - public static List CustomWhere(this List list, string propertyName, string query) - where T : class - { - PropertyInfo property = typeof(T).GetProperty(propertyName); - return ( - from in list - where property.GetValue(x).ToString().ToLower().Contains(query.ToLower()) - select ).ToList(); - } - - public static List CustomWhere(this List list, List property, bool buscaIgual = false) - where T : class - { - if (property == null || property.Count == 0) - { - return list; - } - return list.Where((T x) => { - Func func7 = null; - Func func8 = null; - Func func9 = null; - Func func10 = null; - Func func11 = null; - Func func12 = null; - Func func13 = null; - List filtroPersonalizados = property; - Func u003cu003e9_11 = CustomLinq.u003cu003ec__1.u003cu003e9__1_1; - if (u003cu003e9_11 == null) - { - u003cu003e9_11 = (FiltroPersonalizado p) => p.get_Propriedade(); - CustomLinq.u003cu003ec__1.u003cu003e9__1_1 = u003cu003e9_11; - } - return filtroPersonalizados.GroupBy(u003cu003e9_11).ToList>().All>((IGrouping p) => { - Func func; - IGrouping strs = p; - Func u003cu003e9_13 = CustomLinq.u003cu003ec__1.u003cu003e9__1_3; - if (u003cu003e9_13 == null) - { - u003cu003e9_13 = (FiltroPersonalizado s) => s.get_SemValor(); - CustomLinq.u003cu003ec__1.u003cu003e9__1_3 = u003cu003e9_13; - } - if (strs.Any(u003cu003e9_13)) - { - IGrouping strs1 = p; - Func u003cu003e9_4 = func7; - if (u003cu003e9_4 == null) - { - Func func1 = (FiltroPersonalizado v) => { - bool value; - string str; - string str1; - PropertyInfo propertyInfo1 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo1 != null ? propertyInfo1.GetValue(x) : false); - if (value) - { - PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade()); - str = (propertyInfo != null ? propertyInfo.GetValue(x).ToString() : null); - if (!string.IsNullOrWhiteSpace(str)) - { - PropertyInfo property1 = typeof(T).GetProperty(v.get_Propriedade()); - str1 = (property1 != null ? property1.GetValue(x).ToString() : null); - return string.IsNullOrEmpty(str1); - } - } - return true; - }; - func = func1; - func7 = func1; - u003cu003e9_4 = func; - } - return strs1.Any(u003cu003e9_4); - } - if (p.First().get_Tipo() == typeof(DateTime)) - { - IGrouping strs2 = p; - Func u003cu003e9_5 = func8; - if (u003cu003e9_5 == null) - { - Func func2 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo2 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo2 != null ? propertyInfo2.GetValue(x) : false); - if (!value || !((DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) >= DateTime.Parse(v.get_ValorIncial()))) - { - return false; - } - DateTime dateTime = (DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x); - DateTime dateTime1 = DateTime.Parse(v.get_ValorFinal()); - dateTime1 = dateTime1.AddDays(1); - return dateTime <= dateTime1.AddSeconds(-1); - }; - func = func2; - func8 = func2; - u003cu003e9_5 = func; - } - return strs2.Any(u003cu003e9_5); - } - if (p.First().get_Tipo() == typeof(long)) - { - IGrouping strs3 = p; - Func u003cu003e9_6 = func9; - if (u003cu003e9_6 == null) - { - Func func3 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo3 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo3 != null ? propertyInfo3.GetValue(x) : false); - if (!value || (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) < long.Parse(v.get_ValorIncial())) - { - return false; - } - return (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= long.Parse(v.get_ValorFinal()); - }; - func = func3; - func9 = func3; - u003cu003e9_6 = func; - } - return strs3.Any(u003cu003e9_6); - } - if (p.First().get_Tipo() == typeof(int)) - { - IGrouping strs4 = p; - Func u003cu003e9_7 = func10; - if (u003cu003e9_7 == null) - { - Func func4 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo4 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo4 != null ? propertyInfo4.GetValue(x) : false); - if (!value || (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) < int.Parse(v.get_ValorIncial())) - { - return false; - } - return (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= int.Parse(v.get_ValorFinal()); - }; - func = func4; - func10 = func4; - u003cu003e9_7 = func; - } - return strs4.Any(u003cu003e9_7); - } - if (p.First().get_Tipo() == typeof(decimal)) - { - IGrouping strs5 = p; - Func u003cu003e9_8 = func11; - if (u003cu003e9_8 == null) - { - Func func5 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo5 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo5 != null ? propertyInfo5.GetValue(x) : false); - if (!value || !((decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) >= decimal.Parse(v.get_ValorIncial()))) - { - return false; - } - return (decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= decimal.Parse(v.get_ValorFinal()); - }; - func = func5; - func11 = func5; - u003cu003e9_8 = func; - } - return strs5.Any(u003cu003e9_8); - } - if (p.First().get_Tipo() != typeof(Enum)) - { - IGrouping strs6 = p; - Func u003cu003e9_10 = func13; - if (u003cu003e9_10 == null) - { - Func cSu0024u003cu003e8_locals1 = (FiltroPersonalizado v) => { - bool value; - bool flag; - if (!buscaIgual) - { - PropertyInfo propertyInfo6 = typeof(T).GetProperty(v.get_Propriedade()); - flag = (propertyInfo6 != null ? propertyInfo6.GetValue(x) : false); - if (!flag) - { - return false; - } - return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim())); - } - PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo != null ? propertyInfo.GetValue(x) : false); - if (!value) - { - return false; - } - return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Equals(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim())); - }; - func = cSu0024u003cu003e8_locals1; - func13 = cSu0024u003cu003e8_locals1; - u003cu003e9_10 = func; - } - return strs6.Any(u003cu003e9_10); - } - IGrouping strs7 = p; - Func u003cu003e9_9 = func12; - if (u003cu003e9_9 == null) - { - Func func6 = (FiltroPersonalizado v) => { - bool value; - PropertyInfo propertyInfo7 = typeof(T).GetProperty(v.get_Propriedade()); - value = (propertyInfo7 != null ? propertyInfo7.GetValue(x) : false); - if (!value) - { - return false; - } - return ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x)).ToLower().Equals(v.get_ValorIncial().ToLower()); - }; - func = func6; - func12 = func6; - u003cu003e9_9 = func; - } - return strs7.Any(u003cu003e9_9); - }); - }).ToList(); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/DataGridExtensions.cs b/Gestor.Application/Helpers/DataGridExtensions.cs deleted file mode 100644 index acffb1d..0000000 --- a/Gestor.Application/Helpers/DataGridExtensions.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Gestor.Common.Validation; -using Gestor.Model.Common; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.CompilerServices; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Media; - -namespace Gestor.Application.Helpers -{ - public static class DataGridExtensions - { - public static void EsconderToggles(this DataGrid grid, TipoTela tela, TipoToggle toggles) - { - try - { - foreach (object item in grid.ItemContainerGenerator.Items) - { - grid.ScrollIntoView(item, grid.Columns[0]); - grid.UpdateLayout(); - DataGridRow dataGridRow = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item); - if (dataGridRow == null) - { - continue; - } - grid.ScrollIntoView(dataGridRow, grid.Columns[4]); - grid.UpdateLayout(); - DataGridCellsPresenter visualChild = DataGridExtensions.GetVisualChild(dataGridRow); - DataGridCell dataGridCell = (DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(0); - if (dataGridCell == null || !dataGridCell.ToString().Contains(ValidationHelper.GetDescription(tela))) - { - continue; - } - if (toggles.HasFlag(TipoToggle.Consultar)) - { - ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(1)).Visibility = Visibility.Hidden; - } - if (toggles.HasFlag(TipoToggle.Incluir)) - { - ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(2)).Visibility = Visibility.Hidden; - } - if (toggles.HasFlag(TipoToggle.Alterar)) - { - ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(3)).Visibility = Visibility.Hidden; - } - if (toggles.HasFlag(TipoToggle.Excluir)) - { - ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(4)).Visibility = Visibility.Hidden; - } - return; - } - } - catch (Exception exception) - { - } - } - - public static T GetVisualChild(Visual parent) - where T : Visual - { - T t = default(T); - int childrenCount = VisualTreeHelper.GetChildrenCount(parent); - for (int i = 0; i < childrenCount; i++) - { - Visual child = (Visual)VisualTreeHelper.GetChild(parent, i); - T visualChild = (T)(child as T); - if (visualChild == null) - { - visualChild = DataGridExtensions.GetVisualChild(child); - } - t = visualChild; - if (t != null) - { - break; - } - } - return t; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/Erro.cs b/Gestor.Application/Helpers/Erro.cs deleted file mode 100644 index 52f70f5..0000000 --- a/Gestor.Application/Helpers/Erro.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Gestor.Application.Views.Generic; -using Gestor.Model.API; -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Windows; -using System.Windows.Threading; - -namespace Gestor.Application.Helpers -{ - public static class Erro - { - public static void RegistrarErro(LogError log, bool abrirTela = true) - { - string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Gestor.Exceptions.log"); - File.AppendAllText(str, string.Format("CORRETORA: {1} - {2}{0} USUÁRIO LOGADO: {3}{0} VERSÃO: {4}{0} DATA: {5}{0} ERRO: {6} - {7}{0} HRESULT: {8}{0} HELPLINK: {9}{0} MESSAGE: {10}{0} SOURCE: {11}{0} STACKTRACE: {12}{0} MAQUINA: {13}{0} USUARIO MAQUINA: {14}{0} LINHA: {15}{0} OBJETO: {16}{0} {0}", new object[] { Environment.NewLine, log.get_IdFornecedor(), log.get_Fornecedor(), log.get_UsuarioLogado(), log.get_Versao(), log.get_Data(), log.get_IdErro(), log.get_Erro(), log.get_HResult(), log.get_HelpLink(), log.get_Message(), log.get_Source(), log.get_StackTrace(), log.get_Maquina(), log.get_UsuarioMaquina(), log.get_Linha(), log.get_Objeto() })); - if (!abrirTela) - { - return; - } - System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => (new ErrorWindow(log.get_IdErro(), false)).ShowDialog())); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/Funcoes.cs b/Gestor.Application/Helpers/Funcoes.cs deleted file mode 100644 index 786f217..0000000 --- a/Gestor.Application/Helpers/Funcoes.cs +++ /dev/null @@ -1,6825 +0,0 @@ -using Agger.Registro; -using ClosedXML.Excel; -using CsQuery.ExtensionMethods; -using Gestor.Application; -using Gestor.Application.Actions; -using Gestor.Application.Properties; -using Gestor.Application.Servicos; -using Gestor.Application.Servicos.Configuracoes; -using Gestor.Application.Servicos.Ferramentas; -using Gestor.Application.Servicos.Generic; -using Gestor.Application.Servicos.Seguros; -using Gestor.Application.Servicos.Seguros.Itens; -using Gestor.Application.ViewModels.Generic; -using Gestor.Application.Views.Generic; -using Gestor.Common.Validation; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Infrastructure.UnitOfWork.Logic; -using Gestor.Model.API; -using Gestor.Model.Attributes; -using Gestor.Model.Common; -using Gestor.Model.Domain.Card; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Configuracoes; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.MalaDireta; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using HtmlAgilityPack; -using MaterialDesignThemes.Wpf; -using Newtonsoft.Json; -using OfxSharpLib; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using System.Web; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Threading; -using Xceed.Wpf.AvalonDock.Controls; - -namespace Gestor.Application.Helpers -{ - public static class Funcoes - { - public static System.Diagnostics.Stopwatch Stopwatch; - - public static DateTime? StartTime; - - public static string AdicionarLog(string html) - { - string innerHtml; - HtmlDocument htmlDocument = new HtmlDocument(); - htmlDocument.LoadHtml(html); - DateTime networkTime = Funcoes.GetNetworkTime(); - using (IEnumerator enumerator = htmlDocument.get_DocumentNode().get_ChildNodes().GetEnumerator()) - { - while (enumerator.MoveNext()) - { - HtmlNode current = enumerator.Current; - if (current.get_Name() != "body") - { - continue; - } - current.set_InnerHtml(string.Format("

{0} ID-{1} {2:g}

{3}
", new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, current.get_InnerHtml() })); - innerHtml = current.get_InnerHtml(); - return innerHtml; - } - return ""; - } - return innerHtml; - } - - public static async Task AtualizarAssistencia(Assistance assistance, string id) - { - string str; - if (await Gestor.Application.Helpers.Connection.Put(string.Concat("Assistance/", id), assistance) == null) - { - str = id; - } - else - { - str = null; - } - return str; - } - - public static async Task AtualizarCartao(Gestor.Model.Domain.Card.Card card, string id) - { - string str; - if (await Gestor.Application.Helpers.Connection.Put(string.Concat("Card/", id), card) == null) - { - str = id; - } - else - { - str = null; - } - return str; - } - - public static async Task Atualizarlogo(Logo logo, string id) - { - string str = await Gestor.Application.Helpers.Connection.Put(string.Concat("Card/Logo/", id), logo); - return str; - } - - public static async Task AtualizarSeguradora(AssistenciaCia cia, string id) - { - string str = await Gestor.Application.Helpers.Connection.Put(string.Concat("Assistance/Seguradora/", id), cia); - return str; - } - - public static async Task BaixarComissao(Parcela parcela, List parcelas, List repasses, [DecimalConstant(0, 0, 0, 0, 2)] decimal tolerancia = default(decimal), bool comissaoAuto = false) - { - Parcela parcela1; - long? nullable1; - Parcela parcela2; - decimal num1; - decimal num2; - bool flag; - object nome; - object apolice; - long? nullable2; - bool flag1; - object empty; - string str; - string proposta; - Funcoes.u003cu003ec__DisplayClass2_0 variable; - Parcela parcela3 = parcela; - ParcelaServico parcelaServico = new ParcelaServico(); - Parcela parcela4 = parcela3; - num1 = (!(parcela3.get_ValorComDesconto() == decimal.Zero) || !(Math.Abs(parcela3.get_ValorComDesconto()) < Math.Abs(parcela3.get_ValorComissao())) ? parcela3.get_ValorComDesconto() : parcela3.get_ValorComissao()); - parcela4.set_ValorComDesconto(num1); - List vendedorParcelas = repasses; - var groupings = - from x in vendedorParcelas - group x by new { Id = x.get_Parcela().get_Id(), vendedor = x.get_Vendedor().get_Id(), tipovendedor = x.get_TipoVendedor().get_Id() }; - BaseDialogViewModel baseDialogViewModel = new BaseDialogViewModel(); - if (!groupings.Any((g) => g.Count() > 1)) - { - DateTime networkTime = Funcoes.GetNetworkTime(); - if (parcela3.get_SubTipo() != 1 || parcela3.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1) - { - List vendedorParcelas1 = repasses.Where((VendedorParcela x) => { - FormaRepasse? nullable; - FormaRepasse? forma; - if (x.get_Parcela().get_Id() != parcela3.get_Id() || x.get_DataPagamento().HasValue) - { - return false; - } - if (x == null) - { - return false; - } - Repasse repasse = x.get_Repasse(); - if (repasse != null) - { - forma = repasse.get_Forma(); - } - else - { - nullable = null; - forma = nullable; - } - nullable = forma; - return nullable.GetValueOrDefault() == 1; - }).ToList(); - vendedorParcelas1.ForEach((VendedorParcela x) => { - x.set_DataPrePagamento(parcela3.get_DataRecebimento()); - x.set_ValorRepasse(new decimal?(Funcoes.CalculaRepasse(x.get_Repasse(), parcela3, false))); - }); - parcela2 = await parcelaServico.Save(parcela3, parcelas, vendedorParcelas1, false); - parcela3 = parcela2; - if (!parcelaServico.Sucesso) - { - await Funcoes.MostrarErro(24); - parcela1 = parcela3; - variable = null; - parcelaServico = null; - baseDialogViewModel = null; - return parcela1; - } - } - else - { - num2 = (parcela3.get_Documento().get_AdicionalComiss() ? parcela3.get_Documento().get_PremioLiquido() + parcela3.get_Documento().get_PremioAdicional() : parcela3.get_Documento().get_PremioLiquido()); - decimal num3 = num2; - decimal comissao = (num3 * parcela3.get_Documento().get_Comissao()) * new decimal(1, 0, 0, false, 2); - List parcelas1 = parcelas; - IEnumerable parcelas2 = parcelas1.Where((Parcela x) => { - if (x.get_SubTipo() != 1) - { - return false; - } - return x.get_DataRecebimento().HasValue; - }); - decimal num4 = parcelas2.Sum((Parcela x) => x.get_ValorComissao()); - decimal num5 = Math.Abs(comissao) - Math.Abs(num4); - flag = (num5 <= tolerancia ? true : num5 < new decimal(1, 0, 0, false, 2)); - bool flag2 = flag; - TipoRecebimento? tipoRecebimento = parcela3.get_Documento().get_TipoRecebimento(); - bool flag3 = tipoRecebimento.GetValueOrDefault() == 1 & flag2; - bool flag4 = true; - if (flag3) - { - List configuracoes = Recursos.Configuracoes; - if (configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 54)) - { - Parcela parcela5 = parcela3; - if (parcela5 != null) - { - Documento documento = parcela5.get_Documento(); - if (documento != null) - { - Controle controle = documento.get_Controle(); - if (controle != null) - { - Cliente cliente = controle.get_Cliente(); - if (cliente != null) - { - nome = cliente.get_Nome(); - } - else - { - nome = null; - } - } - else - { - nome = null; - } - } - else - { - nome = null; - } - } - else - { - nome = null; - } - if (nome == null) - { - nome = string.Empty; - } - string str1 = (string)nome; - if (string.IsNullOrEmpty(str1)) - { - Documento documento1 = parcela3.get_Documento(); - if (documento1 != null) - { - Controle controle1 = documento1.get_Controle(); - if (controle1 != null) - { - Cliente cliente1 = controle1.get_Cliente(); - if (cliente1 != null) - { - nullable2 = new long?(cliente1.get_Id()); - } - else - { - nullable1 = null; - nullable2 = nullable1; - } - } - else - { - nullable1 = null; - nullable2 = nullable1; - } - long? nullable3 = nullable2; - long num6 = (long)0; - flag1 = nullable3.GetValueOrDefault() > num6 & nullable3.HasValue; - } - else - { - flag1 = false; - } - if (flag1) - { - Cliente cliente2 = await (new ClienteServico()).BuscarClienteAsync(parcela3.get_Documento().get_Controle().get_Cliente().get_Id()); - if (cliente2 != null) - { - empty = cliente2.get_Nome(); - } - else - { - empty = null; - } - if (empty == null) - { - empty = string.Empty; - } - str1 = (string)empty; - } - } - if (!string.IsNullOrEmpty(str1)) - { - str1 = string.Concat(", DO CLIENTE ", str1); - } - Parcela parcela6 = parcela3; - if (parcela6 != null) - { - Documento documento2 = parcela6.get_Documento(); - if (documento2 != null) - { - apolice = documento2.get_Apolice(); - } - else - { - apolice = null; - } - } - else - { - apolice = null; - } - if (apolice == null) - { - apolice = string.Empty; - } - string str2 = (string)apolice; - if (!string.IsNullOrEmpty(str2)) - { - str2 = string.Concat(" - APÓLICE ", str2); - } - if (parcela3.get_Documento().get_NumeroParcelas() != parcela3.get_NumeroParcela()) - { - bool flag5 = await baseDialogViewModel.ShowMessage(string.Format("AINDA RESTA {0:c}{1}{2} QUE NÃO SERÁ REPASSADO, CONTINUAR A BAIXA POR ESGOTAMENTO?", num5, str1, str2), "SIM, BAIXAR POR ESGOMENTO", "NÃO", false); - bool flag6 = flag5; - flag3 = flag5; - flag4 = flag6; - } - } - } - List vendedorParcelas2 = repasses.Where((VendedorParcela x) => { - bool valueOrDefault; - if (x.get_Parcela().get_Id() == this.parcela.get_Id()) - { - Repasse repasse = x.get_Repasse(); - valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); - if (valueOrDefault) - { - return !x.get_DataPagamento().HasValue; - } - } - return false; - }).ToList(); - List vendedorParcelas3 = new List(); - Parcela parcela7 = parcelas.FirstOrDefault((Parcela x) => { - if (x.get_SubTipo() != 1) - { - return false; - } - return x.get_NumeroParcela() == this.parcela.get_NumeroParcela() + 1; - }); - Parcela parcela8 = parcela3; - List vendedorParcelas4 = vendedorParcelas2; - ExtensionMethods.ForEach( - from g in vendedorParcelas4 - group g by new { Id = g.get_Parcela().get_Id(), vendedor = g.get_Vendedor().get_Id(), tipovendedor = g.get_TipoVendedor().get_Id() }, (x) => { - if (x.First().get_CoCorretagem()) - { - return; - } - decimal valueOrDefault = x.First().get_ValorRepasse().GetValueOrDefault(); - decimal num = Funcoes.CalculaPagamento(x.First(), parcela8, comissao); - x.First().set_ValorRepasse(new decimal?((Math.Abs(valueOrDefault) > Math.Abs(num) ? num : valueOrDefault))); - x.First().set_DataPrePagamento(parcela8.get_DataRecebimento()); - if (flag4 && (Math.Abs(comissao) - Math.Abs(num4)) <= Math.Abs(tolerancia) || parcela7 == null) - { - return; - } - VendedorParcela vendedorParcela = new VendedorParcela(); - vendedorParcela.set_Repasse(x.First().get_Repasse()); - vendedorParcela.set_Parcela(parcela7); - vendedorParcela.set_Documento(parcela8.get_Documento()); - vendedorParcela.set_ValorRepasse(new decimal?(valueOrDefault - num)); - vendedorParcela.set_Vendedor(x.First().get_Vendedor()); - vendedorParcela.set_ValorTotal(x.First().get_ValorTotal()); - vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); - vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); - vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); - vendedorParcelas3.Add(vendedorParcela); - }); - if (vendedorParcelas3.Count > 0) - { - vendedorParcelas2.AddRange(vendedorParcelas3); - } - if (await parcelaServico.SaveRange(vendedorParcelas2)) - { - parcela2 = await parcelaServico.Save(parcela3, parcelas, null, false); - parcela3 = parcela2; - if (parcelaServico.Sucesso) - { - if (flag3) - { - List parcelas3 = parcelas; - List parcelas4 = parcelas3.Where((Parcela x) => { - if (x.get_DataRecebimento().HasValue) - { - return false; - } - return x.get_SubTipo() == 1; - }).ToList(); - List vendedorParcelas5 = new List(); - parcelas4.ForEach((Parcela x) => { - x.set_Documento(parcela3.get_Documento()); - x.set_DataRecebimento(parcela3.get_DataRecebimento()); - x.set_DataCredito(parcela3.get_DataRecebimento()); - x.set_ValorRealizado(decimal.Zero); - x.set_ValorComissao(decimal.Zero); - x.set_ValorComDesconto(decimal.Zero); - x.set_Irr(decimal.Zero); - x.set_Iss(decimal.Zero); - List list = repasses.Where((VendedorParcela p) => { - bool valueOrDefault; - if (p.get_Parcela().get_Id() == x.get_Id()) - { - Repasse repasse = p.get_Repasse(); - valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); - if (valueOrDefault) - { - Repasse repasse1 = p.get_Repasse(); - if (repasse1 == null) - { - return true; - } - return repasse1.get_Tipo().GetValueOrDefault() != 3; - } - } - return false; - }).ToList(); - list.ForEach((VendedorParcela p) => { - decimal? nullable; - p.set_Parcela(x); - p.set_Documento(parcela3.get_Documento()); - p.set_DataPrePagamento(new DateTime?(networkTime)); - VendedorParcela vendedorParcela = p; - decimal? valorRepasse = p.get_ValorRepasse(); - decimal cSu0024u003cu003e8_locals1 = tolerancia; - if ((valorRepasse.GetValueOrDefault() > cSu0024u003cu003e8_locals1) & valorRepasse.HasValue) - { - cSu0024u003cu003e8_locals1 = new decimal(); - nullable = new decimal?(cSu0024u003cu003e8_locals1); - } - else - { - nullable = p.get_ValorRepasse(); - } - vendedorParcela.set_ValorRepasse(nullable); - }); - vendedorParcelas5.AddRange(list); - }); - await parcelaServico.SaveRange(parcelas); - if (!parcelaServico.Sucesso) - { - await Funcoes.MostrarErro(24); - parcela1 = parcela3; - variable = null; - parcelaServico = null; - baseDialogViewModel = null; - return parcela1; - } - else if (await parcelaServico.SaveRange(vendedorParcelas5)) - { - } - else - { - await Funcoes.MostrarErro(24); - parcela1 = parcela3; - variable = null; - parcelaServico = null; - baseDialogViewModel = null; - return parcela1; - } - } - } - else - { - await Funcoes.MostrarErro(24); - parcela1 = parcela3; - variable = null; - parcelaServico = null; - baseDialogViewModel = null; - return parcela1; - } - } - else - { - await Funcoes.MostrarErro(24); - parcela1 = parcela3; - variable = null; - parcelaServico = null; - baseDialogViewModel = null; - return parcela1; - } - } - if (!comissaoAuto) - { - Funcoes.RegistrarLogBaixa(parcela3.get_Documento().get_Id(), networkTime); - } - parcela1 = parcela3; - } - else - { - Documento documento3 = parcela3.get_Documento(); - if (documento3 != null) - { - str = documento3.get_Apolice(); - } - else - { - str = null; - } - if (string.IsNullOrWhiteSpace(str)) - { - Documento documento4 = parcela3.get_Documento(); - if (documento4 != null) - { - proposta = documento4.get_Apolice(); - } - else - { - proposta = null; - } - } - else - { - Documento documento5 = parcela3.get_Documento(); - if (documento5 != null) - { - proposta = documento5.get_Proposta(); - } - else - { - proposta = null; - } - } - string str3 = proposta; - await baseDialogViewModel.ShowMessage(string.Format("HÁ VENDEDORES DUPLICADOS PARA A PARCELA {0} DO DOCUMENTO {1}, BAIXA DE COMISSÃO INTERROMPIDA.{2}REALIZE A CORREÇÃO DOS VENDEDORES E TENTE NOVAMENTE.", parcela3.get_NumeroParcela(), str3, Environment.NewLine), "OK", "", false); - parcela3.set_DataRecebimento(null); - parcela3.set_ValorComissao(decimal.Zero); - parcela3.set_ValorComDesconto(decimal.Zero); - parcela3.set_Irr(decimal.Zero); - parcela3.set_Iss(decimal.Zero); - parcela3.set_Outros(decimal.Zero); - parcela3.set_Desconto(decimal.Zero); - parcela1 = parcela3; - } - variable = null; - parcelaServico = null; - baseDialogViewModel = null; - return parcela1; - } - - public static string BoolToString(this bool boolean) - { - if (!boolean) - { - return "0"; - } - return "1"; - } - - public static void BringToFront(this string programName) - { - try - { - Process[] processesByName = Process.GetProcessesByName(programName); - if (processesByName.Length != 0) - { - IntPtr mainWindowHandle = processesByName[0].MainWindowHandle; - Funcoes.ShowWindow(mainWindowHandle, 5); - Funcoes.ShowWindow(mainWindowHandle, 9); - Funcoes.SetForegroundWindow(mainWindowHandle); - } - } - catch (Exception exception) - { - } - } - - public static decimal CalculaPagamento(VendedorParcela pagamento, Parcela parcela, decimal comissaoPrevista) - { - TipoRepasse? tipo; - bool valueOrDefault; - bool flag; - bool valueOrDefault1; - bool flag1; - decimal num; - decimal num1 = pagamento.get_PorcentagemRepasse().GetValueOrDefault(); - decimal valueOrDefault2 = pagamento.get_ValorRepasse().GetValueOrDefault(); - decimal valorComDesconto = parcela.get_ValorComDesconto(); - Repasse repasse = pagamento.get_Repasse(); - if (repasse != null) - { - valueOrDefault = repasse.get_Incidencia().GetValueOrDefault() == 2; - } - else - { - valueOrDefault = false; - } - if (valueOrDefault) - { - decimal comissao = (parcela.get_Documento().get_Comissao() * parcela.get_Documento().get_PremioLiquido()) * new decimal(1, 0, 0, false, 2); - num = (parcela.get_ValorComissao() != decimal.Zero ? parcela.get_ValorComissao() / comissao : decimal.Zero); - valorComDesconto = parcela.get_Documento().get_PremioLiquido() * num; - } - Repasse repasse1 = pagamento.get_Repasse(); - if (repasse1 != null) - { - tipo = repasse1.get_Tipo(); - flag = tipo.GetValueOrDefault() != 1; - } - else - { - flag = true; - } - if (flag) - { - decimal? porcentagemRepasse = pagamento.get_PorcentagemRepasse(); - num1 = (valorComDesconto * porcentagemRepasse.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2); - } - Repasse repasse2 = pagamento.get_Repasse(); - if (repasse2 != null) - { - tipo = repasse2.get_Tipo(); - valueOrDefault1 = tipo.GetValueOrDefault() == 1; - } - else - { - valueOrDefault1 = false; - } - if (valueOrDefault1) - { - Repasse repasse3 = pagamento.get_Repasse(); - if (repasse3 != null) - { - flag1 = repasse3.get_Forma().GetValueOrDefault() == 1; - } - else - { - flag1 = false; - } - if (flag1) - { - if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 25)) - { - num1 *= (comissaoPrevista == decimal.Zero ? decimal.One : parcela.get_ValorComissao() / comissaoPrevista); - } - } - } - if (Math.Abs(num1) <= Math.Abs(valueOrDefault2)) - { - return num1; - } - return valueOrDefault2; - } - - public static decimal CalculaRepasse(Repasse repasse, Parcela parcela, bool apolice = true) - { - decimal num; - decimal num1; - decimal num2; - decimal comissao; - decimal num3; - if (repasse == null) - { - return decimal.Zero; - } - NegocioCorretora? negocioCorretora = parcela.get_Documento().get_NegocioCorretora(); - bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; - if (!apolice || parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 || parcela.get_SubTipo() != 1) - { - decimal num4 = (parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela.get_ValorLiquidoFatura() : parcela.get_Valor()); - if (repasse.get_Incidencia().GetValueOrDefault() == 2) - { - num3 = num4; - } - else - { - num3 = (parcela.get_ValorComDesconto() == decimal.Zero ? num4 : parcela.get_ValorComDesconto()); - } - num1 = num3; - num2 = num1; - comissao = (parcela.get_ValorComDesconto() == decimal.Zero ? parcela.get_Comissao() * new decimal(1, 0, 0, false, 2) : decimal.One); - } - else - { - num1 = (parcela.get_Documento().get_AdicionalComiss() ? parcela.get_Documento().get_PremioLiquido() + parcela.get_Documento().get_PremioAdicional() : parcela.get_Documento().get_PremioLiquido()); - num2 = (parcela.get_Documento().get_AdicionalComiss() ? parcela.get_Documento().get_PremioLiquido() + parcela.get_Documento().get_PremioAdicional() : parcela.get_Documento().get_PremioLiquido()); - comissao = parcela.get_Documento().get_Comissao() * new decimal(1, 0, 0, false, 2); - } - num1 = (repasse.get_Incidencia().GetValueOrDefault() == 2 ? num1 : num1 * comissao); - num1 = (repasse.get_Tipo().GetValueOrDefault() == 1 ? num1 : (num1 * (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo())) * new decimal(1, 0, 0, false, 2)); - decimal num5 = (repasse.get_Incidencia().GetValueOrDefault() == 2 ? num2 : num2 * comissao); - if (repasse.get_Tipo().GetValueOrDefault() != 1) - { - num = (num5 * (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo())) * new decimal(1, 0, 0, false, 2); - } - else - { - num = (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo()); - if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 24) && parcela.get_Valor() < decimal.Zero) - { - num = -num; - } - } - if (parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 2 && parcela.get_SubTipo() == 1 && parcela.get_Documento().get_TipoEndosso().GetValueOrDefault() != 2) - { - if (Math.Abs(num) > Math.Abs(num1)) - { - (new BaseDialogViewModel()).ShowMessage("OS VALORES DE REPASSE ULTRAPASSARAM O VALOR DE COMISSÃO FECHADA. REVEJA OS VALORES.", "OK", "", false); - } - if (Math.Abs(num) <= Math.Abs(num1)) - { - return num; - } - return num1; - } - if (parcela.get_ValorComDesconto() != decimal.Zero && Math.Abs(num) > Math.Abs(parcela.get_ValorComDesconto())) - { - if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15)) - { - return parcela.get_ValorComDesconto(); - } - } - return num; - } - - public static string Clear(this string stringToClean) - { - if (stringToClean == null) - { - return null; - } - return Regex.Replace(stringToClean, "[^\\d]", string.Empty); - } - - private static void CloseSlackBar() - { - Thread.Sleep(5000); - Dispatcher dispatcher = App.ProgressRing.Dispatcher; - if (dispatcher == null) - { - return; - } - dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => Funcoes.ToggleSnackBar("", false))); - } - - public static List ColunasRelatorio(Relatorio relatorio, List parametrosAdicionados) - { - long id; - int ordem; - List parametrosRelatorios = new List(); - foreach (PropertyInfo propertyInfo in - from in (IEnumerable)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public) - orderby x.GetDescriptionAttribute() - select ) - { - if (propertyInfo.Name == "ValidationEvent" || propertyInfo.GetTypeAttribute() == "INVALID" || parametrosAdicionados.Any((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name)) - { - continue; - } - ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); - ParametrosRelatorio parametrosRelatorio1 = parametrosAdicionados.FirstOrDefault((ParametrosRelatorio x) => { - if (x.get_IdUsuario() == 0) - { - return false; - } - return x.get_Campo() == propertyInfo.Name; - }); - if (parametrosRelatorio1 != null) - { - id = parametrosRelatorio1.get_Id(); - } - else - { - id = (long)0; - } - parametrosRelatorio.set_Id(id); - parametrosRelatorio.set_Campo(propertyInfo.Name); - parametrosRelatorio.set_Header(propertyInfo.GetDescriptionAttribute()); - parametrosRelatorio.set_IdUsuario(Recursos.Usuario.get_Id()); - parametrosRelatorio.set_Relatorio(relatorio); - parametrosRelatorio.set_Tipo(propertyInfo.GetTypeAttribute()); - parametrosRelatorio.set_Width(0); - ParametrosRelatorio parametrosRelatorio2 = parametrosAdicionados.FirstOrDefault((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name); - if (parametrosRelatorio2 != null) - { - ordem = parametrosRelatorio2.get_Ordem(); - } - else - { - ordem = 0; - } - parametrosRelatorio.set_Ordem(ordem); - parametrosRelatorios.Add(parametrosRelatorio); - } - return parametrosRelatorios; - } - - public static List ConstruirSintetico(this List sintetico, Relatorio relatorio) - { - if (sintetico == null) - { - return null; - } - List sinteticModelLists = new List(); - typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList().ForEach((PropertyInfo props) => { - char chr; - if (props.GetValue(sintetico.First()) == null) - { - return; - } - string descriptionAttribute = props.GetDescriptionAttribute(); - TipoRestricao? nullable = null; - if (descriptionAttribute != null) - { - switch (descriptionAttribute.Length) - { - case 5: - { - if (descriptionAttribute == "VALOR") - { - nullable = new TipoRestricao?(100); - goto Label0; - } - else - { - goto Label0; - } - } - case 7: - { - if (descriptionAttribute == "REPASSE") - { - nullable = new TipoRestricao?(81); - goto Label0; - } - else - { - goto Label0; - } - } - case 8: - { - if (descriptionAttribute == "IMPOSTOS") - { - nullable = new TipoRestricao?(93); - goto Label0; - } - else - { - goto Label0; - } - } - case 10: - { - if (descriptionAttribute == "VALOR PAGO") - { - nullable = new TipoRestricao?(104); - goto Label0; - } - else - { - goto Label0; - } - } - case 11: - { - if (descriptionAttribute == "TOTAL GERAL") - { - nullable = new TipoRestricao?(75); - goto Label0; - } - else - { - goto Label0; - } - } - case 12: - { - chr = descriptionAttribute[0]; - if (chr == 'M') - { - if (descriptionAttribute == "META ATINGIR") - { - nullable = new TipoRestricao?(88); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'P') - { - if (descriptionAttribute == "PRÊMIO TOTAL") - { - nullable = new TipoRestricao?(65); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'V') - { - goto Label0; - } - else if (descriptionAttribute == "VALOR ORÇADO") - { - nullable = new TipoRestricao?(101); - goto Label0; - } - else - { - goto Label0; - } - } - case 13: - { - chr = descriptionAttribute[0]; - if (chr == 'M') - { - if (descriptionAttribute == "META CUMPRIDA") - { - nullable = new TipoRestricao?(89); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'V') - { - goto Label0; - } - else if (descriptionAttribute == "VALOR SALVADO") - { - nullable = new TipoRestricao?(105); - goto Label0; - } - else - { - goto Label0; - } - } - case 14: - { - chr = descriptionAttribute[8]; - switch (chr) - { - case 'A': - { - if (descriptionAttribute == "VALOR FRANQUIA") - { - nullable = new TipoRestricao?(106); - goto Label0; - } - else - { - goto Label0; - } - } - case 'B': - { - if (descriptionAttribute == "VALOR LIBERADO") - { - nullable = new TipoRestricao?(103); - goto Label0; - } - else - { - goto Label0; - } - } - case 'C': - case 'D': - { - goto Label0; - } - case 'E': - { - if (descriptionAttribute == "TOTAL PREVISTO") - { - nullable = new TipoRestricao?(82); - goto Label0; - } - else - { - goto Label0; - } - } - default: - { - if (chr == 'R') - { - if (descriptionAttribute == "TOTAL PARCELAS") - { - nullable = new TipoRestricao?(102); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'Í') - { - goto Label0; - } - else if (descriptionAttribute == "PRÊMIO LÍQUIDO") - { - nullable = new TipoRestricao?(67); - goto Label0; - } - else - { - goto Label0; - } - } - } - break; - } - case 15: - { - if (descriptionAttribute == "VALOR LIQUIDADO") - { - nullable = new TipoRestricao?(86); - goto Label0; - } - else - { - goto Label0; - } - } - case 16: - { - if (descriptionAttribute == "TOTAL DE LÍQUIDO") - { - nullable = new TipoRestricao?(76); - goto Label0; - } - else - { - goto Label0; - } - } - case 17: - { - chr = descriptionAttribute[10]; - if (chr == 'E') - { - if (descriptionAttribute == "COMISSÃO PENDENTE") - { - nullable = new TipoRestricao?(87); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'L') - { - if (descriptionAttribute == "TOTAL DE CLIENTES") - { - goto Label1; - } - goto Label0; - } - else if (chr != 'R') - { - goto Label0; - } - else if (descriptionAttribute == "COMISSÃO PREVISTA") - { - nullable = new TipoRestricao?(80); - goto Label0; - } - else - { - goto Label0; - } - } - case 18: - { - if (descriptionAttribute == "TOTAL DE TERCEIROS") - { - nullable = new TipoRestricao?(83); - goto Label0; - } - else - { - goto Label0; - } - } - case 19: - { - if (descriptionAttribute == "QUANTIDADE PENDENTE") - { - nullable = new TipoRestricao?(85); - goto Label0; - } - else - { - goto Label0; - } - } - case 20: - { - if (descriptionAttribute == "QUANTIDADE LIQUIDADO") - { - nullable = new TipoRestricao?(84); - goto Label0; - } - else - { - goto Label0; - } - } - case 21: - { - if (descriptionAttribute == "QUANTIDADE DE FATURAS") - { - nullable = new TipoRestricao?(74); - goto Label0; - } - else - { - goto Label0; - } - } - case 22: - { - chr = descriptionAttribute[14]; - if (chr == 'A') - { - if (descriptionAttribute == "QUANTIDADE DE APÓLICES") - { - nullable = new TipoRestricao?(72); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'E') - { - goto Label0; - } - else if (descriptionAttribute == "QUANTIDADE DE ENDOSSOS") - { - nullable = new TipoRestricao?(73); - goto Label0; - } - else - { - goto Label0; - } - } - case 23: - { - if (descriptionAttribute == "COMISSÃO RECEBIDA BRUTA") - { - nullable = new TipoRestricao?(79); - goto Label0; - } - else - { - goto Label0; - } - } - case 24: - { - chr = descriptionAttribute[0]; - if (chr == 'M') - { - if (descriptionAttribute == "MÉDIA DE COMISSÃO GERADA") - { - break; - } - goto Label0; - } - else if (chr == 'Q') - { - if (descriptionAttribute == "QUANTIDADE DE RENOVAÇÕES") - { - goto Label2; - } - goto Label0; - } - else if (chr == 'T') - { - if (descriptionAttribute == "TOTAL DE CLIENTES ATIVOS") - { - goto Label1; - } - if (descriptionAttribute == "TOTAL DE COMISSÃO GERADA") - { - nullable = new TipoRestricao?(78); - goto Label0; - } - else - { - goto Label0; - } - } - else - { - goto Label0; - } - } - case 25: - { - chr = descriptionAttribute[0]; - if (chr == 'C') - { - if (descriptionAttribute == "COMISSÃO RECEBIDA LÍQUIDA") - { - nullable = new TipoRestricao?(92); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'M') - { - if (descriptionAttribute == "MÉDIA DE COMISSÃO FECHADA") - { - break; - } - goto Label0; - } - else if (chr != 'Q') - { - goto Label0; - } - else if (descriptionAttribute == "QUANTIDADE DE PROSPECÇÕES") - { - nullable = new TipoRestricao?(77); - goto Label0; - } - else - { - goto Label0; - } - } - case 26: - { - if (descriptionAttribute == "TOTAL DE CLIENTES INATIVOS") - { - goto Label1; - } - goto Label0; - } - case 27: - { - chr = descriptionAttribute[15]; - if (chr == 'A') - { - if (descriptionAttribute == "QUANTIDADE DE CANCELAMENTOS") - { - nullable = new TipoRestricao?(71); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'E') - { - if (descriptionAttribute == "QUANTIDADE DE SEGUROS NOVOS") - { - goto Label2; - } - goto Label0; - } - else if (chr == 'Ã') - { - if (descriptionAttribute == "MÉDIA DE COMISSÃO PONDERADA") - { - break; - } - goto Label0; - } - else - { - goto Label0; - } - } - case 28: - { - if (descriptionAttribute == "QUANTIDADE DE NOVOS NEGÓCIOS") - { - goto Label3; - } - goto Label0; - } - case 31: - { - if (descriptionAttribute == "QUANTIDADE DE NEGÓCIOS PRÓPRIOS") - { - goto Label3; - } - goto Label0; - } - default: - { - goto Label0; - } - } - nullable = new TipoRestricao?(68); - } - Label0: - if (nullable.HasValue) - { - RestricaoUsuario restricaoUsuario = (new RestricaoUsuarioServico()).BuscarRestricao(Recursos.Usuario, nullable.Value); - if (restricaoUsuario != null && restricaoUsuario.get_Restricao()) - { - return; - } - } - List parametrosTotalizacaos = (new ConfuguracoesServico()).BuscarParametroTotalizacao(relatorio); - if (parametrosTotalizacaos != null && parametrosTotalizacaos.Count > 0 && parametrosTotalizacaos.All((ParametrosTotalizacao y) => y.get_Campo() != props.Name) && !props.Name.ToUpperInvariant().Contains("AGRUPAMENTO")) - { - return; - } - SinteticModelList sinteticModelList = new SinteticModelList(); - sinteticModelList.set_Hint(descriptionAttribute); - sinteticModelList.set_Value(new List()); - SinteticModelList sinteticModelList1 = sinteticModelList; - string typeAttribute = props.GetTypeAttribute(); - sintetico.ForEach((Sintetico s) => { - object obj; - DateTime? value; - DateTime valueOrDefault; - object str; - object str1; - string str2 = typeAttribute; - if (str2 == "DATA/TIME" || str2 == "DATA/TIME?") - { - value = (DateTime?)props.GetValue(s); - if (value.HasValue) - { - valueOrDefault = value.GetValueOrDefault(); - str = valueOrDefault.ToString("G"); - } - else - { - str = null; - } - obj = str; - } - else if (str2 == "DATA" || str2 == "DATA?") - { - value = (DateTime?)props.GetValue(s); - if (value.HasValue) - { - valueOrDefault = value.GetValueOrDefault(); - str1 = valueOrDefault.ToString("d"); - } - else - { - str1 = null; - } - obj = str1; - } - else - { - obj = (str2 == "PERCENTUAL" ? string.Format("{0:n2} %", props.GetValue(s)) : (str2 == "VALOR" ? ((decimal)props.GetValue(s)).ToString("c2") : string.Format("{0}", props.GetValue(s)))); - } - sinteticModelList1.get_Value().Add(obj); - }); - sinteticModelLists.Add(sinteticModelList1); - return; - Label1: - nullable = new TipoRestricao?(66); - goto Label0; - Label2: - nullable = new TipoRestricao?(70); - goto Label0; - Label3: - nullable = new TipoRestricao?(69); - goto Label0; - }); - return sinteticModelLists; - } - - public static List ConstruirSintetico(this Sintetico sintetico, Relatorio relatorio) - { - if (sintetico == null) - { - return null; - } - List sinteticModels = new List(); - typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList().ForEach((PropertyInfo x) => { - int length; - char chr; - DateTime? value; - DateTime valueOrDefault; - decimal num; - object str; - SinteticModel sinteticModel; - object obj; - if (x.GetValue(sintetico) == null) - { - return; - } - string descriptionAttribute = x.GetDescriptionAttribute(); - TipoRestricao? nullable = null; - string str1 = null; - if (descriptionAttribute != null) - { - length = descriptionAttribute.Length; - switch (length) - { - case 5: - { - if (descriptionAttribute == "VALOR") - { - nullable = new TipoRestricao?(100); - goto Label0; - } - else - { - goto Label0; - } - } - case 7: - { - if (descriptionAttribute == "REPASSE") - { - nullable = new TipoRestricao?(81); - goto Label0; - } - else - { - goto Label0; - } - } - case 8: - { - if (descriptionAttribute == "IMPOSTOS") - { - nullable = new TipoRestricao?(93); - goto Label0; - } - else - { - goto Label0; - } - } - case 10: - { - if (descriptionAttribute == "VALOR PAGO") - { - nullable = new TipoRestricao?(104); - goto Label0; - } - else - { - goto Label0; - } - } - case 11: - { - if (descriptionAttribute == "TOTAL GERAL") - { - nullable = new TipoRestricao?(75); - str1 = "CONTAGEM GERAL DE DOCUMENTOS"; - goto Label0; - } - else - { - goto Label0; - } - } - case 12: - { - chr = descriptionAttribute[0]; - if (chr == 'M') - { - if (descriptionAttribute == "META ATINGIR") - { - nullable = new TipoRestricao?(88); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'P') - { - if (descriptionAttribute == "PRÊMIO TOTAL") - { - nullable = new TipoRestricao?(65); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'V') - { - goto Label0; - } - else if (descriptionAttribute == "VALOR ORÇADO") - { - nullable = new TipoRestricao?(101); - goto Label0; - } - else - { - goto Label0; - } - } - case 13: - { - chr = descriptionAttribute[0]; - if (chr == 'M') - { - if (descriptionAttribute == "META CUMPRIDA") - { - nullable = new TipoRestricao?(89); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'V') - { - goto Label0; - } - else if (descriptionAttribute == "VALOR SALVADO") - { - nullable = new TipoRestricao?(105); - goto Label0; - } - else - { - goto Label0; - } - } - case 14: - { - chr = descriptionAttribute[8]; - switch (chr) - { - case 'A': - { - if (descriptionAttribute == "VALOR FRANQUIA") - { - nullable = new TipoRestricao?(106); - goto Label0; - } - else - { - goto Label0; - } - } - case 'B': - { - if (descriptionAttribute == "VALOR LIBERADO") - { - nullable = new TipoRestricao?(103); - goto Label0; - } - else - { - goto Label0; - } - } - case 'C': - case 'D': - { - goto Label0; - } - case 'E': - { - if (descriptionAttribute == "TOTAL PREVISTO") - { - nullable = new TipoRestricao?(82); - goto Label0; - } - else - { - goto Label0; - } - } - default: - { - if (chr == 'R') - { - if (descriptionAttribute == "TOTAL PARCELAS") - { - nullable = new TipoRestricao?(102); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'Í') - { - goto Label0; - } - else if (descriptionAttribute == "PRÊMIO LÍQUIDO") - { - nullable = new TipoRestricao?(67); - goto Label0; - } - else - { - goto Label0; - } - } - } - break; - } - case 15: - { - if (descriptionAttribute == "VALOR LIQUIDADO") - { - nullable = new TipoRestricao?(86); - goto Label0; - } - else - { - goto Label0; - } - } - case 16: - { - if (descriptionAttribute == "TOTAL DE LÍQUIDO") - { - nullable = new TipoRestricao?(76); - str1 = "CONTAGEM GERAL DOS DOCUMENTOS ATIVOS"; - goto Label0; - } - else - { - goto Label0; - } - } - case 17: - { - chr = descriptionAttribute[10]; - if (chr == 'E') - { - if (descriptionAttribute == "COMISSÃO PENDENTE") - { - nullable = new TipoRestricao?(87); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'L') - { - if (descriptionAttribute == "TOTAL DE CLIENTES") - { - goto Label1; - } - goto Label0; - } - else if (chr != 'R') - { - goto Label0; - } - else if (descriptionAttribute == "COMISSÃO PREVISTA") - { - nullable = new TipoRestricao?(80); - goto Label0; - } - else - { - goto Label0; - } - } - case 18: - { - if (descriptionAttribute == "TOTAL DE TERCEIROS") - { - nullable = new TipoRestricao?(83); - goto Label0; - } - else - { - goto Label0; - } - } - case 19: - { - if (descriptionAttribute == "QUANTIDADE PENDENTE") - { - nullable = new TipoRestricao?(85); - goto Label0; - } - else - { - goto Label0; - } - } - case 20: - { - if (descriptionAttribute == "QUANTIDADE LIQUIDADO") - { - nullable = new TipoRestricao?(84); - goto Label0; - } - else - { - goto Label0; - } - } - case 21: - { - if (descriptionAttribute == "QUANTIDADE DE FATURAS") - { - nullable = new TipoRestricao?(74); - goto Label0; - } - else - { - goto Label0; - } - } - case 22: - { - chr = descriptionAttribute[14]; - if (chr == 'A') - { - if (descriptionAttribute == "QUANTIDADE DE APÓLICES") - { - nullable = new TipoRestricao?(72); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr != 'E') - { - goto Label0; - } - else if (descriptionAttribute == "QUANTIDADE DE ENDOSSOS") - { - nullable = new TipoRestricao?(73); - goto Label0; - } - else - { - goto Label0; - } - } - case 23: - { - if (descriptionAttribute == "COMISSÃO RECEBIDA BRUTA") - { - nullable = new TipoRestricao?(79); - goto Label0; - } - else - { - goto Label0; - } - } - case 24: - { - chr = descriptionAttribute[0]; - if (chr == 'M') - { - if (descriptionAttribute == "MÉDIA DE COMISSÃO GERADA") - { - break; - } - goto Label0; - } - else if (chr == 'Q') - { - if (descriptionAttribute == "QUANTIDADE DE RENOVAÇÕES") - { - goto Label2; - } - goto Label0; - } - else if (chr == 'T') - { - if (descriptionAttribute == "TOTAL DE CLIENTES ATIVOS") - { - goto Label1; - } - if (descriptionAttribute == "TOTAL DE COMISSÃO GERADA") - { - nullable = new TipoRestricao?(78); - goto Label0; - } - else - { - goto Label0; - } - } - else - { - goto Label0; - } - } - case 25: - { - chr = descriptionAttribute[0]; - if (chr == 'C') - { - if (descriptionAttribute == "COMISSÃO RECEBIDA LÍQUIDA") - { - nullable = new TipoRestricao?(92); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'M') - { - if (descriptionAttribute == "MÉDIA DE COMISSÃO FECHADA") - { - break; - } - goto Label0; - } - else if (chr != 'Q') - { - goto Label0; - } - else if (descriptionAttribute == "QUANTIDADE DE PROSPECÇÕES") - { - nullable = new TipoRestricao?(77); - goto Label0; - } - else - { - goto Label0; - } - } - case 26: - { - if (descriptionAttribute == "TOTAL DE CLIENTES INATIVOS") - { - goto Label1; - } - goto Label0; - } - case 27: - { - chr = descriptionAttribute[15]; - if (chr == 'A') - { - if (descriptionAttribute == "QUANTIDADE DE CANCELAMENTOS") - { - nullable = new TipoRestricao?(71); - goto Label0; - } - else - { - goto Label0; - } - } - else if (chr == 'E') - { - if (descriptionAttribute == "QUANTIDADE DE SEGUROS NOVOS") - { - goto Label2; - } - goto Label0; - } - else if (chr == 'Ã') - { - if (descriptionAttribute == "MÉDIA DE COMISSÃO PONDERADA") - { - break; - } - goto Label0; - } - else - { - goto Label0; - } - } - case 28: - { - if (descriptionAttribute == "QUANTIDADE DE NOVOS NEGÓCIOS") - { - goto Label3; - } - goto Label0; - } - case 31: - { - if (descriptionAttribute == "QUANTIDADE DE NEGÓCIOS PRÓPRIOS") - { - goto Label3; - } - goto Label0; - } - default: - { - goto Label0; - } - } - nullable = new TipoRestricao?(68); - } - Label0: - if (nullable.HasValue) - { - RestricaoUsuario restricaoUsuario = (new RestricaoUsuarioServico()).BuscarRestricao(Recursos.Usuario, nullable.Value); - if (restricaoUsuario != null && restricaoUsuario.get_Restricao()) - { - return; - } - } - List parametrosTotalizacaos = (new ConfuguracoesServico()).BuscarParametroTotalizacao(relatorio); - if (parametrosTotalizacaos != null && parametrosTotalizacaos.Count > 0 && parametrosTotalizacaos.All((ParametrosTotalizacao y) => y.get_Campo() != x.Name)) - { - return; - } - SinteticModel sinteticModel1 = new SinteticModel(); - sinteticModel1.set_Hint(descriptionAttribute); - sinteticModel1.set_DescriptionField(str1); - SinteticModel sinteticModel2 = sinteticModel1; - string typeAttribute = x.GetTypeAttribute(); - if (typeAttribute != null) - { - length = typeAttribute.Length; - switch (length) - { - case 4: - { - if (typeAttribute == "DATA") - { - break; - } - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - case 5: - { - chr = typeAttribute[0]; - if (chr == 'D') - { - if (typeAttribute == "DATA?") - { - break; - } - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - else if (chr != 'V') - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - else if (typeAttribute == "VALOR") - { - num = (decimal)x.GetValue(sintetico); - sinteticModel2.set_Value(num.ToString("c2")); - sinteticModels.Add(sinteticModel2); - return; - } - else - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - } - case 6: - case 7: - case 8: - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - case 9: - { - if (typeAttribute == "DATA/TIME") - { - sinteticModel = sinteticModel2; - value = (DateTime?)x.GetValue(sintetico); - if (value.HasValue) - { - valueOrDefault = value.GetValueOrDefault(); - obj = valueOrDefault.ToString("G"); - } - else - { - obj = null; - } - sinteticModel.set_Value(obj); - sinteticModels.Add(sinteticModel2); - return; - } - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - case 10: - { - chr = typeAttribute[0]; - if (chr == 'D') - { - if (typeAttribute == "DATA/TIME?") - { - sinteticModel = sinteticModel2; - value = (DateTime?)x.GetValue(sintetico); - if (value.HasValue) - { - valueOrDefault = value.GetValueOrDefault(); - obj = valueOrDefault.ToString("G"); - } - else - { - obj = null; - } - sinteticModel.set_Value(obj); - sinteticModels.Add(sinteticModel2); - return; - } - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - else if (chr != 'P') - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - else if (typeAttribute == "PERCENTUAL") - { - sinteticModel2.set_Value(string.Format("{0} %", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - else - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - } - default: - { - if (length == 13) - { - if (typeAttribute != "VALORDECIMAL2") - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - num = (decimal)x.GetValue(sintetico); - sinteticModel2.set_Value(num.ToString("n2")); - sinteticModels.Add(sinteticModel2); - return; - } - else - { - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - } - } - } - SinteticModel sinteticModel3 = sinteticModel2; - value = (DateTime?)x.GetValue(sintetico); - if (value.HasValue) - { - valueOrDefault = value.GetValueOrDefault(); - str = valueOrDefault.ToString("d"); - } - else - { - str = null; - } - sinteticModel3.set_Value(str); - sinteticModels.Add(sinteticModel2); - return; - } - sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico))); - sinteticModels.Add(sinteticModel2); - return; - Label1: - nullable = new TipoRestricao?(66); - goto Label0; - Label2: - nullable = new TipoRestricao?(70); - goto Label0; - Label3: - nullable = new TipoRestricao?(69); - goto Label0; - }); - return sinteticModels; - } - - public static async Task ContruirLista(DataGrid grid, Relatorio relatorio) - { - List list = await (new ConfuguracoesServico()).BuscarParametros(relatorio); - if (list == null || list.Count == 0) - { - list = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Select((PropertyInfo x) => { - ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); - parametrosRelatorio.set_Campo(x.Name); - parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); - parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); - parametrosRelatorio.set_Relatorio(relatorio); - parametrosRelatorio.set_Width(0); - parametrosRelatorio.set_Ordem(0); - return parametrosRelatorio; - }).ToList(); - } - if (!Recursos.Usuario.get_Administrador()) - { - list = await Funcoes.GetRestricoesColunas(list); - } - List parametrosRelatorios = list; - IOrderedEnumerable ordem = - from in parametrosRelatorios - orderby x.get_Ordem() - select ; - ordem.ThenBy((ParametrosRelatorio x) => x.get_Header()).ToList().ForEach((ParametrosRelatorio x) => { - char chr; - object upper; - if (x.get_Tipo() == "INVALID") - { - return; - } - if (x.get_Campo() == "DataControle" && !Recursos.Usuario.get_Administrador()) - { - List configuracoes = Recursos.Configuracoes; - Func u003cu003e9_324 = Funcoes.u003cu003ec__32.u003cu003e9__32_4; - if (u003cu003e9_324 == null) - { - u003cu003e9_324 = (ConfiguracaoSistema c) => c.get_Configuracao() == 33; - Funcoes.u003cu003ec__32.u003cu003e9__32_4 = u003cu003e9_324; - } - if (configuracoes.Any(u003cu003e9_324)) - { - return; - } - } - string str = ""; - Style item = (Style)System.Windows.Application.Current.Resources["VerticalCenterStyle3"]; - Style style = (Style)System.Windows.Application.Current.Resources["MaterialDesignDataGridColumnHeaderNew"]; - string tipo = x.get_Tipo(); - if (tipo != null) - { - int length = tipo.Length; - switch (length) - { - case 4: - { - if (tipo == "DATA") - { - break; - } - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - case 5: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA?") - { - break; - } - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else if (chr != 'V') - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else if (tipo == "VALOR") - { - str = "c"; - item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; - style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"]; - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - } - case 6: - case 7: - case 8: - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - case 9: - { - if (tipo == "DATA/TIME") - { - goto Label1; - } - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - case 10: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA/TIME?") - { - goto Label1; - } - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else if (chr == 'P') - { - if (tipo == "PERCENTUAL") - { - str = "{0:0.00}%"; - item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; - style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"]; - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - } - else if (chr != 'Q') - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else if (tipo == "QUANTIDADE") - { - item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; - style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"]; - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - } - default: - { - if (length != 13) - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else if (tipo == "VALORDECIMAL2") - { - str = "n2"; - item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"]; - style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"]; - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - else - { - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - } - } - } - str = "d"; - item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; - style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"]; - } - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - Label1: - str = "G"; - item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"]; - style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"]; - ObservableCollection columns = grid.Columns; - MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn(); - string header = x.get_Header(); - if (header != null) - { - upper = header.ToUpper(); - } - else - { - upper = null; - } - if (upper == null) - { - upper = x.get_Campo().ToUpper(); - } - materialDataGridTextColumn.Header = upper; - materialDataGridTextColumn.Binding = new Binding() - { - Path = new PropertyPath(x.get_Campo(), Array.Empty()), - StringFormat = str, - Mode = BindingMode.TwoWay, - UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged - }; - materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width()); - materialDataGridTextColumn.ElementStyle = item; - materialDataGridTextColumn.HeaderStyle = style; - columns.Add(materialDataGridTextColumn); - return; - }); - } - - public static string ConvertGaragemTrabalhoEstudoCalculo(this GaragemTrabalhoEstudo garagemTrabalhoEstudo) - { - switch (garagemTrabalhoEstudo) - { - case 0: - { - return "0"; - } - case 1: - { - return "1"; - } - case 2: - { - return "2"; - } - case 3: - { - return string.Empty; - } - case 4: - case 5: - { - return "3"; - } - default: - { - return string.Empty; - } - } - } - - public static TipoTela? ConvertTela(string name) - { - return new TipoTela?(((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList().FirstOrDefault((TipoTela x) => Gestor.Common.Validation.ValidationHelper.GetEntity(x) == name)); - } - - public static TempoHabilitacao ConvertTempoHabilitacao(int tempoHabilitacao = 0) - { - if (tempoHabilitacao == 1) - { - return 0; - } - if (tempoHabilitacao == 2) - { - return 1; - } - if (tempoHabilitacao == 3) - { - return 2; - } - if (tempoHabilitacao == 4) - { - return 3; - } - if (tempoHabilitacao == 5) - { - return 4; - } - if (tempoHabilitacao == 6) - { - return 5; - } - if (tempoHabilitacao == 7) - { - return 6; - } - if (tempoHabilitacao == 8) - { - return 7; - } - if (tempoHabilitacao == 9) - { - return 8; - } - if (tempoHabilitacao == 10) - { - return 9; - } - if (tempoHabilitacao >= 11) - { - return 10; - } - return 0; - } - - public static string ConvertTempoHabilitacaoCalculo(this DateTime tempoHabilitacao) - { - if (tempoHabilitacao == DateTime.MinValue) - { - return "0"; - } - int year = DateTime.Now.Year - tempoHabilitacao.Year; - if (year >= 11) - { - return "11"; - } - return year.ToString(); - } - - public static string ConvertTipoSeguroCalculo(this TipoSeguro tipoSeguro) - { - if (tipoSeguro - 1 <= 1) - { - return "1"; - } - return "0"; - } - - public static void CopyToClipboard(this string text) - { - try - { - Clipboard.SetText(text); - } - catch (Exception exception) - { - } - } - - public static string CreateCard(string title, string body, bool pageBreak = false) - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append((pageBreak ? "
" : "
")); - stringBuilder.Append("
"); - stringBuilder.Append(string.Concat("
", title, "
")); - stringBuilder.Append(body); - stringBuilder.Append("
"); - stringBuilder.Append("
"); - return stringBuilder.ToString(); - } - - public static async Task CriarAssistencia(Assistance assistance) - { - return await Gestor.Application.Helpers.Connection.Post("Assistance", assistance); - } - - public static async Task CriarCartao(Gestor.Model.Domain.Card.Card card) - { - return await Gestor.Application.Helpers.Connection.Post("Card", card); - } - - public static async Task Criarlogo(Logo logo) - { - return await Gestor.Application.Helpers.Connection.Post("Card/Logo", logo); - } - - public static string CriarRecibo(Vendedor vendedor, decimal valor, Filtros filtro, bool segundavia) - { - string str = (segundavia ? " acima listados" : string.Format(" no periodo de {0:d} até {1:d}", filtro.get_Inicio(), filtro.get_Fim())); - string str1 = "CPF"; - if (vendedor.get_Documento() != null && Gestor.Common.Validation.ValidationHelper.OnlyNumber(vendedor.get_Documento()).Length > 12) - { - str1 = "CNPJ"; - } - object[] nome = new object[] { vendedor.get_Nome(), str1, vendedor.get_Documento(), Recursos.Empresa.get_Nome(), valor, str, null }; - nome[6] = Funcoes.GetNetworkTime().Date; - return string.Format("
\r\n
RECIBO DE PAGAMENTO
\r\n
\r\n
Declaração de recebimento de Comissão
\r\n

Eu {0}, portador(a) do {1} {2} declaro que recebi de {3} o valor de {4:c} referente a comissão dos seguros{5}.

\r\n\r\n

Para maior clareza firmo(a) o presente recibo para que produza os seus efeitos, dando plena, rasa e irrevogável quitação, pelo valor recebido.

\r\n\r\n

_____________________________________________________________
{6:d}

\r\n
\r\n
", nome); - } - - public static async Task CriarSeguradora(AssistenciaCia cia) - { - return await Gestor.Application.Helpers.Connection.Post("Assistance/Seguradora", cia); - } - - public static void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) - { - DatePicker datePicker = (DatePicker)sender; - datePicker.Text = Gestor.Common.Validation.ValidationHelper.FormatDate(datePicker.Text); - } - - public static void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e) - { - if (e.Key != Key.Return) - { - return; - } - DatePicker str = (DatePicker)sender; - DateTime date = Funcoes.GetNetworkTime().Date; - str.Text = date.ToString("dd/MM/yyyy"); - } - - public static void Destroy() - where T : Window - { - object obj = System.Windows.Application.Current.Windows.OfType().FirstOrDefault(); - if (obj == null) - { - return; - } - ((Window)obj).Close(); - } - - public static void Destroy(string title) - where T : Window - { - object obj = System.Windows.Application.Current.Windows.OfType().FirstOrDefault((T x) => x.Title == title); - if (obj == null) - { - return; - } - ((Window)obj).Close(); - } - - public static string DiaDaSemana(this int? dia) - { - if (!dia.HasValue) - { - return ""; - } - switch (dia.Value) - { - case 0: - { - return "DOMINGO"; - } - case 1: - { - return "SEGUNDA-FEIRA"; - } - case 2: - { - return "TERÇA-FEIRA"; - } - case 3: - { - return "QUARTA-FEIRA"; - } - case 4: - { - return "QUINTA-FEIRA"; - } - case 5: - { - return "SEXTA-FEIRA"; - } - case 6: - { - return "SABADO"; - } - } - return ""; - } - - public static IEnumerable DistinctBy(IEnumerable source, Func keySelector) - { - HashSet tKeys = new HashSet(); - foreach (TSource tSource in source) - { - if (!tKeys.Add(keySelector(tSource))) - { - continue; - } - yield return tSource; - } - } - - public static bool EnviarWhatsapp(this string numero, string anotacoes = null) - { - bool flag; - Uri uri = (string.IsNullOrEmpty(anotacoes) ? Recursos.WhatsAppLink.SetQuery("phone", numero, true) : Recursos.WhatsAppLink.AddQuery("phone", numero).SetQuery("text", anotacoes, true)); - try - { - Process.Start(new ProcessStartInfo(uri.AbsoluteUri)); - flag = true; - } - catch (Exception exception) - { - uri.AbsoluteUri.CopyToClipboard(); - flag = false; - } - return flag; - } - - public static async Task ExcluirBaixa(Parcela parcela, List repasses, List parcelas = null) - { - Parcela parcela1; - string str; - decimal num1; - List parcelas1; - List parcelas2; - Funcoes.u003cu003ec__DisplayClass9_0 variable; - ParcelaServico parcelaServico; - VendedorServico vendedorServico; - Parcela parcela2 = parcela; - ParcelaServico parcelaServico1 = new ParcelaServico(); - if (parcela2.get_SubTipo() != 1 || parcela2.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1) - { - List list = repasses.Where((VendedorParcela x) => { - if (x.get_Parcela().get_Id() != parcela2.get_Id()) - { - return false; - } - return !x.get_DataPagamento().HasValue; - }).ToList(); - List vendedorParcelas1 = list; - vendedorParcelas1.ForEach((VendedorParcela x) => { - x.set_DataPrePagamento(null); - VendedorParcela vendedorParcela = x; - decimal? valorTotal = x.get_ValorTotal(); - vendedorParcela.set_ValorRepasse(new decimal?((valorTotal.HasValue ? valorTotal.GetValueOrDefault() : Funcoes.CalculaPagamento(x, x.get_Parcela(), decimal.Zero)))); - }); - parcela2.set_ValorComissao(decimal.Zero); - parcela2.set_ValorComDesconto(decimal.Zero); - DateTime? nullable1 = null; - parcela2.set_DataRecebimento(nullable1); - nullable1 = null; - parcela2.set_DataCredito(nullable1); - parcela2.set_ValorRealizado(decimal.Zero); - Parcela parcela3 = await parcelaServico1.Save(parcela2, parcelas, list, false); - parcela2 = parcela3; - if (!parcelaServico1.Sucesso) - { - await Funcoes.MostrarErro(191); - parcela1 = parcela2; - variable = null; - parcelaServico1 = null; - parcelaServico = null; - vendedorServico = null; - return parcela1; - } - } - else - { - List list1 = repasses.Where((VendedorParcela x) => { - bool valueOrDefault; - if (x.get_Parcela().get_SubTipo() == 1) - { - Repasse repasse = x.get_Repasse(); - valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); - if (valueOrDefault) - { - if (x.get_Parcela().get_Id() == this.parcela.get_Id()) - { - return true; - } - return !x.get_DataPrePagamento().HasValue; - } - } - return false; - }).ToList(); - decimal premioLiquido = parcela2.get_Documento().get_PremioLiquido(); - num1 = (parcela2.get_Documento().get_AdicionalComiss() ? parcela2.get_Documento().get_PremioAdicional() : decimal.Zero); - decimal comissao = ((premioLiquido + num1) * parcela2.get_Documento().get_Comissao()) * new decimal(1, 0, 0, false, 2); - List vendedorParcelas2 = list1; - List list2 = ( - from x in vendedorParcelas2 - group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { - TipoRepasse? nullable; - decimal? valorTotal; - decimal num; - TipoRepasse? tipo; - bool valueOrDefault; - bool hasValue; - decimal? valorRepasse; - bool flag; - VendedorParcela vendedorParcela = new VendedorParcela(); - vendedorParcela.set_Repasse(x.First().get_Repasse()); - vendedorParcela.set_Parcela(parcela2); - vendedorParcela.set_Documento(parcela2.get_Documento()); - VendedorParcela vendedorParcela1 = x.First(); - if (vendedorParcela1 != null) - { - Repasse repasse = vendedorParcela1.get_Repasse(); - if (repasse != null) - { - tipo = repasse.get_Tipo(); - } - else - { - nullable = null; - tipo = nullable; - } - nullable = tipo; - valueOrDefault = nullable.GetValueOrDefault() != 3; - } - else - { - valueOrDefault = true; - } - if (valueOrDefault) - { - VendedorParcela vendedorParcela2 = x.First(); - if (vendedorParcela2 != null) - { - valorTotal = vendedorParcela2.get_ValorTotal(); - hasValue = valorTotal.HasValue; - } - else - { - hasValue = false; - } - if (hasValue) - { - VendedorParcela vendedorParcela3 = x.First(); - if (vendedorParcela3 != null) - { - valorTotal = vendedorParcela3.get_ValorTotal(); - num = new decimal(); - flag = !((valorTotal.GetValueOrDefault() == num) & valorTotal.HasValue); - } - else - { - flag = true; - } - if (!flag) - { - goto Label1; - } - VendedorParcela vendedorParcela4 = x.First(); - if (vendedorParcela4 != null) - { - valorRepasse = vendedorParcela4.get_ValorTotal(); - vendedorParcela.set_ValorTotal(valorRepasse); - vendedorParcela.set_Vendedor(x.First().get_Vendedor()); - vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); - vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); - vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); - return vendedorParcela; - } - else - { - valorTotal = null; - valorRepasse = valorTotal; - vendedorParcela.set_ValorTotal(valorRepasse); - vendedorParcela.set_Vendedor(x.First().get_Vendedor()); - vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); - vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); - vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); - return vendedorParcela; - } - } - Label1: - num = comissao; - valorTotal = x.First().get_PorcentagemRepasse(); - valorRepasse = (valorTotal.HasValue ? new decimal?((num * valorTotal.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2)) : null); - } - else - { - valorRepasse = x.First().get_ValorRepasse(); - } - vendedorParcela.set_ValorTotal(valorRepasse); - vendedorParcela.set_Vendedor(x.First().get_Vendedor()); - vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); - vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); - vendedorParcela.set_CoCorretagem(x.First().get_CoCorretagem()); - return vendedorParcela; - }).ToList(); - parcelas1 = (parcelas != null ? parcelas.Where((Parcela x) => { - if (x.get_SubTipo() != 1) - { - return false; - } - return x.get_NumeroParcela() < this.parcela.get_NumeroParcela(); - }).ToList() : new List()); - List parcelas3 = parcelas1; - list2.ForEach((VendedorParcela y) => { - VendedorParcela vendedorParcela = y; - decimal? valorTotal = y.get_ValorTotal(); - IEnumerable vendedorParcelas = repasses.Where((VendedorParcela x) => { - bool valueOrDefault; - if (x.get_Parcela().get_SubTipo() == 1) - { - Repasse repasse = x.get_Repasse(); - valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); - if (valueOrDefault && x.get_Vendedor().get_Id() == y.get_Vendedor().get_Id()) - { - List cSu0024u003cu003e8_locals2 = parcelas3; - Func u003cu003e9_912 = Funcoes.u003cu003ec.u003cu003e9__9_12; - if (u003cu003e9_912 == null) - { - u003cu003e9_912 = (Parcela z) => z.get_Id(); - Funcoes.u003cu003ec.u003cu003e9__9_12 = u003cu003e9_912; - } - return cSu0024u003cu003e8_locals2.Select(u003cu003e9_912).ToList().Contains(x.get_Parcela().get_Id()); - } - } - return false; - }); - Func u003cu003e9_911 = Funcoes.u003cu003ec.u003cu003e9__9_11; - if (u003cu003e9_911 == null) - { - u003cu003e9_911 = (VendedorParcela x) => x.get_ValorRepasse(); - Funcoes.u003cu003ec.u003cu003e9__9_11 = u003cu003e9_911; - } - decimal? nullable = vendedorParcelas.Sum(u003cu003e9_911); - vendedorParcela.set_ValorRepasse((valorTotal.HasValue & nullable.HasValue ? new decimal?(valorTotal.GetValueOrDefault() - nullable.GetValueOrDefault()) : null)); - }); - parcelas2 = (parcelas != null ? parcelas.Where((Parcela x) => { - if (x.get_SubTipo() != 1) - { - return false; - } - return x.get_NumeroParcela() > this.parcela.get_NumeroParcela(); - }).ToList() : new List()); - List list3 = parcelas2; - list3.Add(parcela2); - List vendedorParcelas3 = repasses.Where((VendedorParcela x) => { - bool valueOrDefault; - if (x.get_Parcela().get_SubTipo() == 1) - { - Repasse repasse = x.get_Repasse(); - valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false); - if (valueOrDefault) - { - if (x.get_Parcela().get_NumeroParcela() >= this.parcela.get_NumeroParcela()) - { - return true; - } - return !x.get_DataPrePagamento().HasValue; - } - } - return false; - }).ToList(); - if (!await parcelaServico1.DeletePagamentoRange(vendedorParcelas3)) - { - await Funcoes.MostrarErro(191); - parcela1 = parcela2; - variable = null; - parcelaServico1 = null; - parcelaServico = null; - vendedorServico = null; - return parcela1; - } - else if (await parcelaServico1.SaveRange(list2)) - { - List parcelas4 = list3; - list3 = parcelas4.Where((Parcela dParcela) => { - if (dParcela.get_ValorComissao() != decimal.Zero || dParcela.get_ValorComissao() != decimal.Zero || dParcela.get_DataRecebimento().HasValue || dParcela.get_DataCredito().HasValue) - { - return true; - } - return dParcela.get_ValorRealizado() != decimal.Zero; - }).ToList(); - if (list3 != null && list3.Count > 0) - { - list3.ForEach((Parcela dParcela) => { - dParcela.set_Documento(this.parcela.get_Documento()); - dParcela.set_ValorComissao(decimal.Zero); - dParcela.set_ValorComDesconto(decimal.Zero); - DateTime? nullable = null; - dParcela.set_DataRecebimento(nullable); - nullable = null; - dParcela.set_DataCredito(nullable); - dParcela.set_ValorRealizado(decimal.Zero); - }); - list3 = await parcelaServico1.UpdateRange(list3); - if (parcelaServico1.Sucesso) - { - parcela2 = list3.FirstOrDefault((Parcela x) => x.get_Id() == this.parcela.get_Id()); - } - else - { - await Funcoes.MostrarErro(191); - parcela1 = parcela2; - variable = null; - parcelaServico1 = null; - parcelaServico = null; - vendedorServico = null; - return parcela1; - } - } - list2 = null; - list3 = null; - } - else - { - await Funcoes.MostrarErro(191); - parcela1 = parcela2; - variable = null; - parcelaServico1 = null; - parcelaServico = null; - vendedorServico = null; - return parcela1; - } - } - ApoliceServico apoliceServico = new ApoliceServico(); - parcelaServico = new ParcelaServico(); - vendedorServico = new VendedorServico(); - if (parcela2 != null) - { - Documento documento = await apoliceServico.BuscarApoliceAsync(parcela2.get_Documento().get_Id(), false, false); - Documento documento1 = documento; - ObservableCollection observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id()); - documento1.set_Parcelas(observableCollection); - documento1 = null; - List vendedorParcelas4 = await vendedorServico.BuscaRepasse(documento.get_Id()); - foreach (Parcela parcela4 in documento.get_Parcelas()) - { - foreach (VendedorParcela vendedorParcela5 in vendedorParcelas4) - { - if (vendedorParcela5.get_Parcela().get_Id() != parcela4.get_Id()) - { - continue; - } - if (parcela4.get_Vendedores() == null) - { - parcela4.set_Vendedores(new ObservableCollection()); - } - parcela4.get_Vendedores().Add(vendedorParcela5); - } - } - IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); - RegistroLog registroLog = new RegistroLog(); - registroLog.set_Acao(2); - registroLog.set_Usuario(Recursos.Usuario); - registroLog.set_DataHora(Funcoes.GetNetworkTime()); - Documento documento2 = documento; - JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); - jsonSerializerSetting.set_ReferenceLoopHandling(1); - registroLog.set_Descricao(JsonConvert.SerializeObject(documento2, jsonSerializerSetting)); - registroLog.set_EntidadeId(documento.get_Id()); - registroLog.set_Tela(2); - registroLog.set_NomeMaquina(Environment.MachineName); - registroLog.set_UsuarioMaquina(Environment.UserName); - IPAddress[] addressList = hostEntry.AddressList; - IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); - if (pAddress != null) - { - str = pAddress.ToString(); - } - else - { - str = null; - } - registroLog.set_Ip(str); - RegistroLog registroLog1 = registroLog; - await Task.Run(() => { - using (UnitOfWork commited = Instancia.Commited) - { - commited.get_RegistroLogRepository().SaveOrUpdate(registroLog1); - commited.Commit(); - } - }); - documento = null; - } - parcela1 = parcela2; - variable = null; - parcelaServico1 = null; - parcelaServico = null; - vendedorServico = null; - return parcela1; - } - - public static async Task ExcluirPagamento(VendedorParcela pagamento) - { - pagamento.set_DataPagamento(null); - ParcelaServico parcelaServico = new ParcelaServico() - { - Sucesso = true - }; - await parcelaServico.Save(pagamento); - bool sucesso = parcelaServico.Sucesso; - parcelaServico = null; - return sucesso; - } - - public static string ExportarHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "") - { - string str = string.Format("DATA DE EMISSÃO DO RELATÓRIO EM {0:G}", Funcoes.GetNetworkTime()); - if (tipo.get_Inicio() != DateTime.MinValue && tipo.get_Nome() != "RELATÓRIO DE CLIENTE") - { - str = string.Format("PERÍODO DE {0:d} ATÉ {1:d}. DATA DE EMISSÃO DO RELATÓRIO EM {2:G}", tipo.get_Inicio(), tipo.get_Fim(), Funcoes.GetNetworkTime()); - } - string str1 = (!search ? "" : ""); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(Resources.RelatorioTemplate.Replace("{style}", str1).Replace("Orientation", orientation).Replace("{NomeRelatorio}", string.Concat(Recursos.Empresa.get_NomeSocial(), " - ", tipo.get_Nome())).Replace("{EmissaoRelatorio}", str).Replace("{Grafico}", grafico).Replace("{DadosRelatorio}", dados)); - return stringBuilder.ToString(); - } - - public static string ExportarMultipleHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "") - { - string str = string.Format("DATA DE EMISSÃO DO RELATÓRIO EM {0:G}", Funcoes.GetNetworkTime()); - if (tipo.get_Inicio() != DateTime.MinValue && tipo.get_Nome() != "RELATÓRIO DE CLIENTE") - { - str = string.Format("PERÍODO DE {0:d} ATÉ {1:d}. DATA DE EMISSÃO DO RELATÓRIO EM {2:G}", tipo.get_Inicio(), tipo.get_Fim(), Funcoes.GetNetworkTime()); - } - string str1 = (!search ? "" : ""); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(Resources.RelatorioMultipleTemplate.Replace("{style}", str1).Replace("Orientation", orientation).Replace("{NomeRelatorio}", string.Concat(Recursos.Empresa.get_NomeSocial(), " - ", tipo.get_Nome())).Replace("{EmissaoRelatorio}", str).Replace("{Grafico}", grafico).Replace("{DadosRelatorio}", dados)); - return stringBuilder.ToString(); - } - - public static async Task GenerateMultipleTable(List> analiticos, List colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null) - { - string str4; - string str5; - Action action2 = null; - if (analiticos == null) - { - str4 = ""; - } - else if (analiticos.Count != 0) - { - int tamanhoFonte = 0; - if (config != null) - { - tamanhoFonte = config.get_TamanhoFonte(); - } - str5 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte)); - string str6 = str5; - str4 = await Task.Run(() => { - StringBuilder stringBuilder2 = new StringBuilder(); - int num = 0; - foreach (List analitico in analiticos) - { - StringBuilder stringBuilder3 = new StringBuilder(); - StringBuilder stringBuilder4 = new StringBuilder(); - StringBuilder stringBuilder5 = new StringBuilder(); - int num1 = 0; - stringBuilder4.Append(Resources.HeaderTemplate.Replace("{Align}", "text-start").Replace("{Size}", "").Replace("{FontWeight}", "fw-bold").Replace("{Content}", analitico[0].get_NomeRelatorio())); - stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); - List listagems = analitico; - Action u003cu003e9_1 = action2; - if (u003cu003e9_1 == null) - { - Action action = (Listagem x) => { - Sinal sinal; - string str; - char chr; - string str1; - PropertyInfo[] properties = x.GetType().GetProperties(); - Func u003cu003e9_222 = Funcoes.u003cu003ec.u003cu003e9__22_2; - if (u003cu003e9_222 == null) - { - u003cu003e9_222 = (PropertyInfo b) => b.Name == "Bold"; - Funcoes.u003cu003ec.u003cu003e9__22_2 = u003cu003e9_222; - } - PropertyInfo propertyInfo = ((IEnumerable)properties).FirstOrDefault(u003cu003e9_222); - bool flag = (propertyInfo == null ? false : (bool)propertyInfo.GetValue(x)); - Func u003cu003e9_223 = Funcoes.u003cu003ec.u003cu003e9__22_3; - if (u003cu003e9_223 == null) - { - u003cu003e9_223 = (PropertyInfo b) => b.Name == "Sinal"; - Funcoes.u003cu003ec.u003cu003e9__22_3 = u003cu003e9_223; - } - PropertyInfo propertyInfo1 = ((IEnumerable)properties).FirstOrDefault(u003cu003e9_223); - string str2 = (!(propertyInfo1 != null) || propertyInfo1.GetValue(x) == null || !Enum.TryParse(propertyInfo1.GetValue(x).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;"); - if (flag) - { - string.Concat(""); - } - else - { - string.Concat(""); - } - StringBuilder stringBuilder = new StringBuilder(); - PropertyInfo[] propertyInfoArray = properties; - for (int i = 0; i < (int)propertyInfoArray.Length; i++) - { - PropertyInfo propertyInfo2 = propertyInfoArray[i]; - if (propertyInfo2.Name != "ValidationEvent") - { - object obj = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj != null) - { - string description = ((DescriptionAttribute)obj).Description; - if ((!propertyName || !colunasOcultas.Contains(propertyInfo2.Name)) && (propertyName || !colunasOcultas.Contains(description))) - { - object obj1 = propertyInfo2.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); - string description1 = ""; - if (obj1 != null) - { - description1 = ((TipoAttribute)obj1).get_Description(); - } - string str3 = "text-start"; - if (description1 != null) - { - switch (description1.Length) - { - case 4: - { - chr = description1[0]; - if (chr == 'D') - { - if (description1 == "DATA") - { - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) == null || (DateTime)propertyInfo2.GetValue(x) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo2.GetValue(x))); - goto Label0; - } - else - { - goto Label1; - } - } - else if (chr != 'E') - { - goto Label1; - } - else if (description1 == "ENUM") - { - str = (propertyInfo2.GetValue(x) != null ? Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo2.GetValue(x)) ?? "" : ""); - goto Label0; - } - else - { - goto Label1; - } - } - case 5: - { - chr = description1[0]; - if (chr == 'D') - { - if (description1 == "DATA?") - { - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:d}", (DateTime?)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - else if (chr != 'V') - { - goto Label1; - } - else if (description1 == "VALOR") - { - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - case 6: - { - if (description1 != "VALOR?") - { - goto Label1; - } - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal?)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - case 9: - { - if (description1 == "DATA/TIME") - { - break; - } - goto Label1; - } - case 10: - { - chr = description1[0]; - if (chr == 'D') - { - if (description1 == "DATA/TIME?") - { - break; - } - goto Label1; - } - else if (chr == 'P') - { - if (description1 == "PERCENTUAL") - { - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:p2}", (decimal)propertyInfo2.GetValue(x) * new decimal(1, 0, 0, false, 2)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - else if (chr != 'Q') - { - goto Label1; - } - else if (description1 == "QUANTIDADE") - { - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - default: - { - goto Label1; - } - } - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:G}", (DateTime?)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - Label1: - str1 = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); - str = str1; - Label0: - StringBuilder stringBuilder1 = stringBuilder; - stringBuilder1.Append(Resources.ColumnTemplate.Replace("{Align}", str3).Replace("{Size}", str6).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", str)); - } - } - } - } - }; - Action action1 = action; - action2 = action; - u003cu003e9_1 = action1; - } - listagems.ForEach(u003cu003e9_1); - StringBuilder stringBuilder6 = new StringBuilder(); - if (grafico) - { - stringBuilder5.Append(string.Format("
", num)); - } - num++; - stringBuilder6.Append(Resources.TableMultipleTemplate.Replace("{Head}", stringBuilder3.ToString()).Replace("{Body}", stringBuilder5.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("{1}", num1, footer)) : ""))); - stringBuilder2.Append(stringBuilder6.ToString()); - } - return stringBuilder2.ToString(); - }); - } - else - { - str4 = ""; - } - return str4; - } - - public static async Task GenerateTable(List analitico, List colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null) - { - string str7; - string str8; - if (analitico == null) - { - str7 = ""; - } - else if (analitico.Count != 0) - { - int tamanhoFonte = 0; - if (config != null) - { - tamanhoFonte = config.get_TamanhoFonte(); - } - str8 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte)); - string str9 = str8; - str7 = await Task.Run(() => { - StringBuilder stringBuilder2 = new StringBuilder(); - StringBuilder stringBuilder3 = new StringBuilder(); - StringBuilder stringBuilder4 = new StringBuilder(); - Type type = analitico[0].GetType(); - PropertyInfo[] properties = type.GetProperties(); - int num = 0; - PropertyInfo[] propertyInfoArray3 = properties; - for (int i1 = 0; i1 < (int)propertyInfoArray3.Length; i1++) - { - PropertyInfo propertyInfo3 = propertyInfoArray3[i1]; - if (propertyInfo3.Name != "ValidationEvent") - { - object obj2 = propertyInfo3.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj2 != null) - { - string str4 = ((DescriptionAttribute)obj2).Description; - if ((!propertyName || !colunasOcultas.Contains(propertyInfo3.Name)) && (propertyName || !colunasOcultas.Contains(str4))) - { - object obj3 = propertyInfo3.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); - string str5 = ""; - if (obj3 != null) - { - str5 = ((TipoAttribute)obj3).get_Description(); - } - string str6 = "text-start"; - if (str5 == "PERCENTUAL" || str5 == "VALOR") - { - str6 = "text-center"; - } - else if (str5 == "QUANTIDADE" || str5 == "DATA") - { - str6 = "text-end"; - } - stringBuilder3.Append(Resources.HeaderTemplate.Replace("{Align}", str6).Replace("{Size}", str9).Replace("{FontWeight}", "fw-bold").Replace("{Content}", str4)); - num++; - } - } - } - } - stringBuilder2.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder3.ToString()).Replace("{Color}", "")); - analitico.ForEach((T x) => { - Sinal sinal; - string str; - char chr; - string str1; - type = x.GetType(); - properties = type.GetProperties(); - PropertyInfo[] propertyInfoArray = properties; - Func u003cu003e9_212 = Funcoes.u003cu003ec__21.u003cu003e9__21_2; - if (u003cu003e9_212 == null) - { - u003cu003e9_212 = (PropertyInfo b) => b.Name == "Bold"; - Funcoes.u003cu003ec__21.u003cu003e9__21_2 = u003cu003e9_212; - } - PropertyInfo propertyInfo = ((IEnumerable)propertyInfoArray).FirstOrDefault(u003cu003e9_212); - bool flag = (propertyInfo == null ? false : (bool)propertyInfo.GetValue(x)); - PropertyInfo[] propertyInfoArray1 = properties; - Func u003cu003e9_213 = Funcoes.u003cu003ec__21.u003cu003e9__21_3; - if (u003cu003e9_213 == null) - { - u003cu003e9_213 = (PropertyInfo b) => b.Name == "Sinal"; - Funcoes.u003cu003ec__21.u003cu003e9__21_3 = u003cu003e9_213; - } - PropertyInfo propertyInfo1 = ((IEnumerable)propertyInfoArray1).FirstOrDefault(u003cu003e9_213); - string str2 = (!(propertyInfo1 != null) || propertyInfo1.GetValue(x) == null || !Enum.TryParse(propertyInfo1.GetValue(x).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;"); - if (flag) - { - string.Concat(""); - } - else - { - string.Concat(""); - } - StringBuilder stringBuilder = new StringBuilder(); - PropertyInfo[] propertyInfoArray2 = properties; - for (int i = 0; i < (int)propertyInfoArray2.Length; i++) - { - PropertyInfo propertyInfo2 = propertyInfoArray2[i]; - if (propertyInfo2.Name != "ValidationEvent") - { - object obj = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj != null) - { - string description = ((DescriptionAttribute)obj).Description; - if ((!propertyName || !colunasOcultas.Contains(propertyInfo2.Name)) && (propertyName || !colunasOcultas.Contains(description))) - { - object obj1 = propertyInfo2.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); - string description1 = ""; - if (obj1 != null) - { - description1 = ((TipoAttribute)obj1).get_Description(); - } - string str3 = "text-start"; - if (description1 != null) - { - switch (description1.Length) - { - case 4: - { - chr = description1[0]; - if (chr == 'D') - { - if (description1 == "DATA") - { - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) == null || (DateTime)propertyInfo2.GetValue(x) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo2.GetValue(x))); - goto Label0; - } - else - { - goto Label1; - } - } - else if (chr != 'E') - { - goto Label1; - } - else if (description1 == "ENUM") - { - str = (propertyInfo2.GetValue(x) != null ? Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo2.GetValue(x)) ?? "" : ""); - goto Label0; - } - else - { - goto Label1; - } - } - case 5: - { - chr = description1[0]; - if (chr == 'D') - { - if (description1 == "DATA?") - { - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:d}", (DateTime?)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - else if (chr != 'V') - { - goto Label1; - } - else if (description1 == "VALOR") - { - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - case 6: - { - if (description1 != "VALOR?") - { - goto Label1; - } - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal?)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - case 9: - { - if (description1 == "DATA/TIME") - { - break; - } - goto Label1; - } - case 10: - { - chr = description1[0]; - if (chr == 'D') - { - if (description1 == "DATA/TIME?") - { - break; - } - goto Label1; - } - else if (chr == 'P') - { - if (description1 == "PERCENTUAL") - { - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:p2}", (decimal)propertyInfo2.GetValue(x) * new decimal(1, 0, 0, false, 2)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - else if (chr != 'Q') - { - goto Label1; - } - else if (description1 == "QUANTIDADE") - { - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - case 13: - { - if (description1 == "VALORDECIMAL2") - { - str3 = "text-end"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:n2}", (decimal)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - else - { - goto Label1; - } - } - default: - { - goto Label1; - } - } - str3 = "text-center"; - str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:G}", (DateTime?)propertyInfo2.GetValue(x)) : ""); - goto Label0; - } - Label1: - str1 = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : ""); - str = str1; - Label0: - StringBuilder stringBuilder1 = stringBuilder; - stringBuilder1.Append(Resources.ColumnTemplate.Replace("{Align}", str3).Replace("{Size}", str9).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", str)); - } - } - } - } - stringBuilder4.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder.ToString()).Replace("{Color}", string.Concat("style='", str2, "'"))); - }); - StringBuilder stringBuilder5 = new StringBuilder(); - if (grafico) - { - stringBuilder4.Append(""); - stringBuilder4.Append("
"); - stringBuilder4.Append("
*VALORES NEGATIVOS NÃO SÃO REPRESENTADOS NO GRÁFICO DE PIZZA.
"); - stringBuilder4.Append(""); - } - stringBuilder5.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder2.ToString()).Replace("{Body}", stringBuilder4.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("{1}", num, footer)) : ""))); - return stringBuilder5.ToString(); - }); - } - else - { - str7 = ""; - } - return str7; - } - - public static async Task GenerateTable(List analitico, Relatorio relatorio, bool grafico = false, bool verificarColunas = true, string footer = "", ConfiguracaoImpressao config = null) - { - string str6; - List restricoesColunas; - string str7; - List campos; - int tamanhoFonte = 0; - if (config != null) - { - campos = config.get_Campos(); - tamanhoFonte = config.get_TamanhoFonte(); - } - else - { - if (!verificarColunas) - { - restricoesColunas = null; - } - else - { - restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio); - } - campos = restricoesColunas; - if (campos == null || campos.Count == 0) - { - PropertyInfo[] propertyInfoArray2 = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); - campos = propertyInfoArray2.Select((PropertyInfo x) => { - ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); - parametrosRelatorio.set_Campo(x.Name); - parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); - parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); - parametrosRelatorio.set_Relatorio(relatorio); - parametrosRelatorio.set_Width(0); - parametrosRelatorio.set_Ordem(0); - return parametrosRelatorio; - }).ToList(); - } - } - str7 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte)); - string str8 = str7; - restricoesColunas = await Funcoes.GetRestricoesColunas(campos); - campos = restricoesColunas; - if (analitico == null) - { - str6 = ""; - } - else if (analitico.Count != 0) - { - str6 = await Task.Run(() => { - StringBuilder stringBuilder3 = new StringBuilder(); - StringBuilder stringBuilder4 = new StringBuilder(); - StringBuilder stringBuilder5 = new StringBuilder(); - Type type = analitico[0].GetType(); - PropertyInfo[] properties = type.GetProperties(); - int num = 0; - List parametrosRelatorios1 = campos; - Func u003cu003e9_242 = Funcoes.u003cu003ec__24.u003cu003e9__24_2; - if (u003cu003e9_242 == null) - { - u003cu003e9_242 = (ParametrosRelatorio x) => x.get_Ordem(); - Funcoes.u003cu003ec__24.u003cu003e9__24_2 = u003cu003e9_242; - } - IOrderedEnumerable parametrosRelatorios2 = parametrosRelatorios1.OrderBy(u003cu003e9_242); - Func u003cu003e9_243 = Funcoes.u003cu003ec__24.u003cu003e9__24_3; - if (u003cu003e9_243 == null) - { - u003cu003e9_243 = (ParametrosRelatorio x) => x.get_Header(); - Funcoes.u003cu003ec__24.u003cu003e9__24_3 = u003cu003e9_243; - } - ExtensionMethods.ForEach(parametrosRelatorios2.ThenBy(u003cu003e9_243), (ParametrosRelatorio x) => { - if (x.get_Tipo() == "INVALID") - { - return; - } - PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => p.Name == x.get_Campo()); - if (propertyInfo == null) - { - return; - } - string descriptionAttribute = propertyInfo.GetDescriptionAttribute(); - string str = "text-start"; - string tipo = x.get_Tipo(); - if (tipo == "PERCENTUAL" || tipo == "VALOR") - { - str = "text-center"; - } - else if (tipo == "QUANTIDADE" || tipo == "DATA") - { - str = "text-end"; - } - stringBuilder4.Append(Resources.HeaderTemplate.Replace("{Align}", str).Replace("{Size}", str8).Replace("{FontWeight}", "fw-bold").Replace("{Content}", descriptionAttribute)); - num++; - }); - stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); - analitico.ForEach((T a) => { - Sinal sinal; - StringBuilder stringBuilder2 = new StringBuilder(); - type = a.GetType(); - properties = type.GetProperties(); - PropertyInfo[] propertyInfoArray = properties; - Func u003cu003e9_247 = Funcoes.u003cu003ec__24.u003cu003e9__24_7; - if (u003cu003e9_247 == null) - { - u003cu003e9_247 = (PropertyInfo b) => b.Name == "Bold"; - Funcoes.u003cu003ec__24.u003cu003e9__24_7 = u003cu003e9_247; - } - PropertyInfo propertyInfo1 = ((IEnumerable)propertyInfoArray).FirstOrDefault(u003cu003e9_247); - bool flag = (propertyInfo1 == null ? false : (bool)propertyInfo1.GetValue(a)); - PropertyInfo[] propertyInfoArray1 = properties; - Func u003cu003e9_248 = Funcoes.u003cu003ec__24.u003cu003e9__24_8; - if (u003cu003e9_248 == null) - { - u003cu003e9_248 = (PropertyInfo b) => b.Name == "Sinal"; - Funcoes.u003cu003ec__24.u003cu003e9__24_8 = u003cu003e9_248; - } - PropertyInfo propertyInfo2 = ((IEnumerable)propertyInfoArray1).FirstOrDefault(u003cu003e9_248); - string str5 = (!(propertyInfo2 != null) || propertyInfo2.GetValue(a) == null || !Enum.TryParse(propertyInfo2.GetValue(a).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;"); - if (flag) - { - string.Concat(""); - } - else - { - string.Concat(""); - } - List cSu0024u003cu003e8_locals1 = campos; - Func u003cu003e9_249 = Funcoes.u003cu003ec__24.u003cu003e9__24_9; - if (u003cu003e9_249 == null) - { - u003cu003e9_249 = (ParametrosRelatorio x) => x.get_Ordem(); - Funcoes.u003cu003ec__24.u003cu003e9__24_9 = u003cu003e9_249; - } - IOrderedEnumerable parametrosRelatorios = cSu0024u003cu003e8_locals1.OrderBy(u003cu003e9_249); - Func u003cu003e9_2410 = Funcoes.u003cu003ec__24.u003cu003e9__24_10; - if (u003cu003e9_2410 == null) - { - u003cu003e9_2410 = (ParametrosRelatorio x) => x.get_Header(); - Funcoes.u003cu003ec__24.u003cu003e9__24_10 = u003cu003e9_2410; - } - ExtensionMethods.ForEach(parametrosRelatorios.ThenBy(u003cu003e9_2410), (ParametrosRelatorio x) => { - string str; - char chr; - string str1; - string str2; - string str3; - StringBuilder stringBuilder; - StringBuilder stringBuilder1; - if (x.get_Tipo() == "INVALID") - { - return; - } - PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => p.Name == x.get_Campo()); - if (propertyInfo == null) - { - return; - } - string str4 = "text-start"; - string tipo = x.get_Tipo(); - if (tipo != null) - { - switch (tipo.Length) - { - case 4: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA") - { - str4 = "text-center"; - str = (propertyInfo.GetValue(a) == null || (DateTime)propertyInfo.GetValue(a) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo.GetValue(a))); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - else if (chr != 'E') - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else if (tipo == "ENUM") - { - str = (propertyInfo.GetValue(a) == null || Convert.ToInt32(propertyInfo.GetValue(a)) == 0 ? "" : Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo.GetValue(a)) ?? ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - case 5: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA?") - { - str4 = "text-center"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0:d}", (DateTime?)propertyInfo.GetValue(a)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - else if (chr != 'V') - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else if (tipo == "VALOR") - { - str4 = "text-end"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0:c2}", (decimal)propertyInfo.GetValue(a)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - case 6: - { - if (tipo != "VALOR?") - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - str4 = "text-end"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0:c2}", (decimal?)propertyInfo.GetValue(a)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - case 7: - case 8: - case 11: - case 12: - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - case 9: - { - if (tipo == "DATA/TIME") - { - break; - } - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - case 10: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA/TIME?") - { - break; - } - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else if (chr == 'P') - { - if (tipo == "PERCENTUAL") - { - str4 = "text-end"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0:p2}", (decimal)propertyInfo.GetValue(a) * new decimal(1, 0, 0, false, 2)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - else if (chr != 'Q') - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else if (tipo == "QUANTIDADE") - { - str4 = "text-center"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - case 13: - { - if (tipo == "VALORDECIMAL2") - { - str4 = "text-end"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0:n2}", (decimal)propertyInfo.GetValue(a)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - else - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - default: - { - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - } - str4 = "text-center"; - str = (propertyInfo.GetValue(a) != null ? string.Format("{0:G}", (DateTime?)propertyInfo.GetValue(a)) : ""); - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - return; - } - str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : ""); - str = str1; - stringBuilder = stringBuilder2; - str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8); - str3 = (flag ? "fw-bold" : ""); - stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str)); - }); - stringBuilder5.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", string.Concat("style='", str5, "'"))); - }); - StringBuilder stringBuilder6 = new StringBuilder(); - stringBuilder6.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder3.ToString()).Replace("{Body}", stringBuilder5.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("{1}", num, footer)) : ""))); - return stringBuilder6.ToString(); - }); - } - else - { - str6 = ""; - } - return str6; - } - - public static async Task GenerateTableSintetic(List sintetic, int fontSize = 0) - { - string str; - string str1; - if (sintetic == null || sintetic.Count == 0) - { - str = ""; - } - else - { - str1 = (fontSize == 0 ? "" : string.Format("fs-{0}'", fontSize)); - string str2 = str1; - str = await Task.Run(() => { - StringBuilder stringBuilder = new StringBuilder(); - StringBuilder stringBuilder1 = new StringBuilder(); - StringBuilder stringBuilder2 = new StringBuilder(); - StringBuilder stringBuilder3 = new StringBuilder(); - StringBuilder stringBuilder4 = new StringBuilder(); - sintetic.ForEach((SinteticModel x) => { - stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "fw-bold").Replace("{Content}", x.get_Hint())); - stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "").Replace("{Content}", (x.get_Value() == null ? "" : x.get_Value().ToString()))); - }); - stringBuilder1.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", "")); - stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); - stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder1.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", "")); - return stringBuilder.ToString(); - }); - } - return str; - } - - public static async Task GenerateTableSintetic(List sintetic, int fontSize = 0) - { - string str; - string str1; - if (sintetic == null || sintetic.Count == 0) - { - str = ""; - } - else - { - str1 = (fontSize == 0 ? "" : string.Format("fs-{0}'", fontSize)); - string str2 = str1; - str = await Task.Run(() => { - StringBuilder stringBuilder = new StringBuilder(); - StringBuilder stringBuilder1 = new StringBuilder(); - StringBuilder stringBuilder2 = new StringBuilder(); - StringBuilder stringBuilder3 = new StringBuilder(); - sintetic.ForEach((SinteticModelList x) => stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "fw-bold").Replace("{Content}", x.get_Hint()))); - stringBuilder1.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", "")); - for (int i = 0; i < sintetic.First().get_Value().Count; i++) - { - StringBuilder stringBuilder4 = new StringBuilder(); - bool flag = false; - foreach (SinteticModelList sinteticModelList in sintetic) - { - flag = (flag ? true : (sinteticModelList.get_Value()[0] == null ? false : sinteticModelList.get_Value()[i].ToString() == "TOTAL")); - stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", string.Format("{0}", sinteticModelList.get_Value()[i]))); - } - stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "")); - } - stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder1.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", "")); - return stringBuilder.ToString(); - }); - } - return str; - } - - public static string GeraAssistencia(this long id) - { - string str; - try - { - DateTime now = DateTime.Now; - str = HttpUtility.UrlEncode(string.Format("{0}:{1}:A:{2}", now.Ticks, ApplicationHelper.IdFornecedor, id).Base64Encode()); - } - catch - { - return ""; - } - return str; - } - - public static string GeraCartaoVisita(this long id) - { - string str; - try - { - DateTime now = DateTime.Now; - str = HttpUtility.UrlEncode(string.Format("{0}:{1}:V:{2}", now.Ticks, ApplicationHelper.IdFornecedor, id).Base64Encode()); - } - catch - { - return ""; - } - return str; - } - - public static async Task GerarCsv(List Conteudo, IEnumerable colunasExportacao) - { - PropertyInfo[] array = ( - from in typeof(T).GetProperties() - where colunasExportacao.Contains(p.Name) - select ).ToArray(); - StringBuilder stringBuilder = new StringBuilder(); - StringBuilder stringBuilder1 = stringBuilder; - PropertyInfo[] propertyInfoArray = array; - stringBuilder1.AppendLine(string.Join(";", - from in (IEnumerable)propertyInfoArray - select p.Name)); - foreach (T conteudo in Conteudo) - { - IEnumerable strs = array.Select((PropertyInfo p) => { - object str; - object value = p.GetValue(conteudo, null); - if (value != null) - { - str = value.ToString(); - } - else - { - str = null; - } - if (str == null) - { - str = string.Empty; - } - return str; - }); - stringBuilder.AppendLine(string.Join(";", strs)); - } - return stringBuilder.ToString(); - } - - public static string GerarGrafico(List sinteticoLista) - { - string str = "['NOME', 'VALOR'], "; - sinteticoLista.ForEach((ValorSintetico x) => { - if (x.get_Indice() != "TOTAL" && x.get_Valor() > decimal.Zero) - { - string[] indice = new string[] { str, "[`", x.get_Indice(), " ", x.get_Porcentagem(), "`, ", null, null }; - indice[6] = x.get_Valor().ToString("F2", CultureInfo.InvariantCulture); - indice[7] = "], "; - str = string.Concat(indice); - } - }); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(""); - stringBuilder.Append(""); - return stringBuilder.ToString(); - } - - public static string GerarGraficoUnico(List> sinteticosListas) - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(""); - stringBuilder.Append(""); - return stringBuilder.ToString(); - } - - public static async Task GerarXls(XLWorkbook xlWorkbook, string nome, List analitico, Relatorio relatorio, bool verificarColunas = true) - { - List restricoesColunas; - string str = nome; - str = str.ValidaNomePlanilha("", 0); - if (!verificarColunas) - { - restricoesColunas = null; - } - else - { - restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio); - } - List list = restricoesColunas; - if (list == null || list.Count == 0) - { - PropertyInfo[] propertyInfoArray = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); - list = propertyInfoArray.Select((PropertyInfo x) => { - ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); - parametrosRelatorio.set_Campo(x.Name); - parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); - parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); - parametrosRelatorio.set_Relatorio(relatorio); - parametrosRelatorio.set_Width(0); - parametrosRelatorio.set_Ordem(0); - return parametrosRelatorio; - }).ToList(); - } - restricoesColunas = await Funcoes.GetRestricoesColunas(list); - list = restricoesColunas; - XLWorkbook xLWorkbook1 = await Task.Run(() => { - XLWorkbook xLWorkbook; - try - { - IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(str); - PropertyInfo[] properties = analitico[0].GetType().GetProperties(); - int num1 = 1; - List parametrosRelatorios1 = list; - Func u003cu003e9_252 = Funcoes.u003cu003ec__25.u003cu003e9__25_2; - if (u003cu003e9_252 == null) - { - u003cu003e9_252 = (ParametrosRelatorio x) => x.get_Ordem(); - Funcoes.u003cu003ec__25.u003cu003e9__25_2 = u003cu003e9_252; - } - IOrderedEnumerable parametrosRelatorios2 = parametrosRelatorios1.OrderBy(u003cu003e9_252); - Func u003cu003e9_253 = Funcoes.u003cu003ec__25.u003cu003e9__25_3; - if (u003cu003e9_253 == null) - { - u003cu003e9_253 = (ParametrosRelatorio x) => x.get_Header(); - Funcoes.u003cu003ec__25.u003cu003e9__25_3 = u003cu003e9_253; - } - ExtensionMethods.ForEach(parametrosRelatorios2.ThenBy(u003cu003e9_253), (ParametrosRelatorio x) => { - if (x.get_Tipo() == "INVALID") - { - return; - } - PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => { - if (p.Name == x.get_Campo() || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("VENDEDOR") && str.Equals("SINTÉTICO POR VENDEDOR") && relatorio == 7 || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("SEGURADORA") && str.Equals("SINTÉTICO POR SEGURADORA") && relatorio == 7) - { - return true; - } - if (!p.Name.ToUpper().Equals("NOME") || !x.get_Campo().ToUpper().Equals("RAMO") || !str.Equals("SINTÉTICO POR RAMO")) - { - return false; - } - return relatorio == 7; - }); - if (propertyInfo == null) - { - return; - } - xLWorksheet.Cell(1, num1).set_Value(propertyInfo.GetDescriptionAttribute()); - num1++; - }); - int num2 = 2; - analitico.ForEach((T a) => { - num1 = 1; - int num = num2; - List cSu0024u003cu003e8_locals1 = list; - Func u003cu003e9_257 = Funcoes.u003cu003ec__25.u003cu003e9__25_7; - if (u003cu003e9_257 == null) - { - u003cu003e9_257 = (ParametrosRelatorio x) => x.get_Ordem(); - Funcoes.u003cu003ec__25.u003cu003e9__25_7 = u003cu003e9_257; - } - IOrderedEnumerable parametrosRelatorios = cSu0024u003cu003e8_locals1.OrderBy(u003cu003e9_257); - Func u003cu003e9_258 = Funcoes.u003cu003ec__25.u003cu003e9__25_8; - if (u003cu003e9_258 == null) - { - u003cu003e9_258 = (ParametrosRelatorio x) => x.get_Header(); - Funcoes.u003cu003ec__25.u003cu003e9__25_8 = u003cu003e9_258; - } - ExtensionMethods.ForEach(parametrosRelatorios.ThenBy(u003cu003e9_258), (ParametrosRelatorio x) => { - int cSu0024u003cu003e8_locals3; - char chr; - if (x.get_Tipo() == "INVALID") - { - return; - } - PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo p) => { - if (p.Name == x.get_Campo() || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("VENDEDOR") && str.Equals("SINTÉTICO POR VENDEDOR") && relatorio == 7 || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("SEGURADORA") && str.Equals("SINTÉTICO POR SEGURADORA") && relatorio == 7) - { - return true; - } - if (!p.Name.ToUpper().Equals("NOME") || !x.get_Campo().ToUpper().Equals("RAMO") || !str.Equals("SINTÉTICO POR RAMO")) - { - return false; - } - return relatorio == 7; - }); - if (propertyInfo == null) - { - return; - } - Regex regex = new Regex("\\<[^\\>]*\\>"); - object value = propertyInfo.GetValue(a); - if (value != null && value.ToString().Contains(">") && value.ToString().Contains("<")) - { - value = regex.Replace(value.ToString(), ""); - } - string tipo = x.get_Tipo(); - if (tipo != null) - { - switch (tipo.Length) - { - case 4: - { - if (tipo == "DATA") - { - break; - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - case 5: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA?") - { - break; - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - else if (chr == 'V') - { - if (tipo != "VALOR") - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(2); - xLWorksheet.Cell(num, num1).set_Value(((decimal?)value).GetValueOrDefault()); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - else - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - } - case 6: - case 7: - case 8: - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - case 9: - { - if (tipo == "DATA/TIME") - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy HH:mm:ss"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - case 10: - { - chr = tipo[0]; - if (chr == 'D') - { - if (tipo == "DATA/TIME?") - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy HH:mm:ss"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - else if (chr == 'P') - { - if (tipo == "PERCENTUAL") - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(10); - xLWorksheet.Cell(num, num1).set_Value(((decimal?)value).GetValueOrDefault() * new decimal(1, 0, 0, false, 2)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - else - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - } - else if (chr != 'Q') - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - else if (tipo == "QUANTIDADE") - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(1); - xLWorksheet.Cell(num, num1).set_Value(value); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - else - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - } - default: - { - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - return; - } - xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@"); - xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value)); - cSu0024u003cu003e8_locals3 = num1; - num1 = cSu0024u003cu003e8_locals3 + 1; - }); - num2++; - }); - xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true); - xLWorksheet.Columns().AdjustToContents(); - xLWorkbook = xlWorkbook; - } - catch (Exception exception) - { - xLWorkbook = null; - } - return xLWorkbook; - }); - return xLWorkbook1; - } - - public static async Task GerarXls(XLWorkbook xlWorkbook, string nome, List analitico, List colunasOcultas = null) - { - XLWorkbook xLWorkbook1 = await Task.Run(() => { - XLWorkbook xLWorkbook; - try - { - nome = nome.ValidaNomePlanilha("", 0); - IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(nome); - Type type = analitico[0].GetType(); - PropertyInfo[] properties = type.GetProperties(); - int num = 1; - PropertyInfo[] propertyInfoArray1 = properties; - for (int i1 = 0; i1 < (int)propertyInfoArray1.Length; i1++) - { - PropertyInfo propertyInfo1 = propertyInfoArray1[i1]; - if (propertyInfo1.Name != "ValidationEvent") - { - object obj1 = propertyInfo1.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj1 != null) - { - string str = ((DescriptionAttribute)obj1).Description; - if (colunasOcultas == null || !colunasOcultas.Contains(str)) - { - xLWorksheet.Cell(1, num).set_Value(str); - num++; - } - } - } - } - int num1 = 2; - analitico.ForEach((T x) => { - int i; - num = 1; - type = x.GetType(); - properties = type.GetProperties(); - PropertyInfo[] propertyInfoArray = properties; - for (i = 0; i < (int)propertyInfoArray.Length; i++) - { - PropertyInfo propertyInfo = propertyInfoArray[i]; - if (propertyInfo.Name != "ValidationEvent") - { - object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj != null) - { - string description = ((DescriptionAttribute)obj).Description; - if (colunasOcultas == null || !colunasOcultas.Contains(description)) - { - string name = propertyInfo.Name; - if (name.Contains("Fipe") || name == "NumeroProposta" || name == "NumeroApolice" || name == "NumeroPedidoEndosso") - { - xLWorksheet.Cell(num1, num).get_Style().get_NumberFormat().set_Format("@"); - } - xLWorksheet.Cell(num1, num).set_Value(propertyInfo.GetValue(x)); - num++; - } - } - } - } - i = num1; - num1 = i + 1; - }); - xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true); - xLWorksheet.Columns().AdjustToContents(); - xLWorkbook = xlWorkbook; - } - catch (Exception exception) - { - xLWorkbook = null; - } - return xLWorkbook; - }); - return xLWorkbook1; - } - - public static async Task GerarXlsSintetico(XLWorkbook xlWorkbook, string nome, List sintetic) - { - XLWorkbook xLWorkbook1 = await Task.Run(() => { - XLWorkbook xLWorkbook; - try - { - nome = nome.ValidaNomePlanilha("", 0); - IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(nome); - int num = 1; - sintetic.ForEach((SinteticModel x) => { - xLWorksheet.Cell(1, num).set_Value(x.get_Hint()); - xLWorksheet.Cell(2, num).set_Value(x.get_Value()); - num++; - }); - xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true); - xLWorksheet.Columns().AdjustToContents(); - xLWorkbook = xlWorkbook; - } - catch (Exception exception) - { - xLWorkbook = null; - } - return xLWorkbook; - }); - return xLWorkbook1; - } - - public static string GetBody(this string html) - { - HtmlDocument htmlDocument = new HtmlDocument(); - htmlDocument.LoadHtml(html); - HtmlNode htmlNode = htmlDocument.get_DocumentNode().SelectSingleNode("//body"); - if (htmlNode != null) - { - return htmlNode.get_InnerHtml(); - } - return null; - } - - public static Categoria? GetCategoria(string text) - { - Categoria categorium; - if (text.Contains("caminhao") || text.Contains("caminhão")) - { - return new Categoria?(4); - } - if (text.Contains("onibus") || text.Contains("ônibus")) - { - return new Categoria?(6); - } - if (text.Contains("utilitario") || text.Contains("utilitário")) - { - return new Categoria?(6); - } - if (text.Contains("moto")) - { - return new Categoria?(9); - } - if (!Enum.TryParse(text, true, out categorium)) - { - return null; - } - return new Categoria?((Categoria)Enum.Parse(typeof(Categoria), text, true)); - } - - public static Combustivel? GetCombustivel(string text) - { - Combustivel combustivel; - if (text.Contains("flex")) - { - return new Combustivel?(4); - } - if (text.Contains("gasolina") && (text.Contains("alcool") || text.Contains("álcool"))) - { - if (text.Contains("gnv")) - { - return new Combustivel?(8); - } - if (!text.Contains("eletrico") && !text.Contains("elétrico")) - { - return new Combustivel?(4); - } - return new Combustivel?(12); - } - if (text.Contains("gasolina") && text.Contains("gnv")) - { - return new Combustivel?(7); - } - if (text.Contains("gasolina") && (text.Contains("eletrico") || text.Contains("elétrico"))) - { - return new Combustivel?(9); - } - if (text.Contains("eletrico") || text.Contains("elétrico")) - { - return new Combustivel?(11); - } - if (text.Contains("alcool") || text.Contains("álcool")) - { - return new Combustivel?(1); - } - if (text.Contains("hibrido") || text.Contains("híbrido")) - { - return new Combustivel?(10); - } - if (text.Contains("outro")) - { - return new Combustivel?(6); - } - if (!Enum.TryParse(text, true, out combustivel)) - { - return null; - } - return new Combustivel?((Combustivel)Enum.Parse(typeof(Combustivel), text, true)); - } - - public static Cor? GetCor(string text) - { - Cor cor; - if (text.Contains("outro")) - { - return new Cor?(16); - } - if (!Enum.TryParse(text, true, out cor)) - { - return null; - } - return new Cor?((Cor)Enum.Parse(typeof(Cor), text, true)); - } - - public static Correcao? GetCorrecao(string text) - { - if (text.Contains("mercado")) - { - return new Correcao?(0); - } - if (text.Contains("determinado")) - { - return new Correcao?(1); - } - return null; - } - - public static string GetDescriptionAttribute(this PropertyInfo pi) - { - object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj == null) - { - return pi.Name.ToUpper(); - } - return ((DescriptionAttribute)obj).Description; - } - - public static async Task GetFabricante(string text) - { - Fabricante fabricante; - List fabricantes = await (new BaseServico()).BuscarFabricante(text); - if (fabricantes.Count < 1) - { - fabricante = null; - } - else - { - fabricante = fabricantes.First(); - } - return fabricante; - } - - public static Isencao? GetIsencao(string text) - { - if (text.Contains("sem")) - { - return new Isencao?(0); - } - if (text.Contains("ipi") && text.Contains("icms")) - { - return new Isencao?(3); - } - if (text.Contains("ipi")) - { - return new Isencao?(2); - } - if (text.Contains("icms")) - { - return new Isencao?(1); - } - return null; - } - - public static DateTime GetNetworkTime() - { - DateTime value; - try - { - if (!Funcoes.StartTime.HasValue) - { - byte[] numArray = new byte[48]; - numArray[0] = 27; - IPEndPoint pEndPoint = new IPEndPoint(((IEnumerable)Dns.GetHostEntry("time.google.com").AddressList).First((IPAddress a) => a.AddressFamily == AddressFamily.InterNetwork), 123); - using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) - { - socket.Connect(pEndPoint); - socket.ReceiveTimeout = 3000; - socket.Send(numArray); - socket.Receive(numArray); - socket.Close(); - } - ulong num = (ulong)numArray[40] << 24 | (ulong)numArray[41] << 16 | (ulong)numArray[42] << 8 | (ulong)numArray[43]; - ulong num1 = (ulong)numArray[44] << 24 | (ulong)numArray[45] << 16 | (ulong)numArray[46] << 8 | (ulong)numArray[47]; - ulong num2 = num * (long)1000 + num1 * (long)1000 / 4294967296L; - DateTime dateTime = new DateTime(1900, 1, 1); - dateTime = dateTime.AddMilliseconds((double)num2); - Funcoes.StartTime = new DateTime?(dateTime.ToLocalTime()); - Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); - value = Funcoes.StartTime.Value; - } - else - { - value = Funcoes.StartTime.Value; - value = value.AddMilliseconds((double)Funcoes.Stopwatch.ElapsedMilliseconds); - } - } - catch (Exception exception) - { - Funcoes.StartTime = new DateTime?(DateTime.Now); - Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); - value = Funcoes.StartTime.Value; - } - return value; - } - - private static async Task> GetRestricoesColunas(List parametros) - { - List restricaoUsuarioCamposRelatorios = await (new RestricaoUsuarioServico()).BuscarRestricoesCamposRelatorios(Recursos.Usuario.get_Id()); - List list = restricaoUsuarioCamposRelatorios; - List restricaoUsuarioCamposRelatorios1 = list; - list = ( - from x in restricaoUsuarioCamposRelatorios1 - where x.get_Restricao() - select x).ToList(); - List parametrosRelatorios = ( - from x in parametros - where ( - from y in list - where x.get_Relatorio() == y.get_Relatorio() - select y).All((RestricaoUsuarioCamposRelatorios y) => x.get_Header() != y.get_Campo()) - select x).ToList(); - return parametrosRelatorios; - } - - public static TabelaReferencia? GetTabelaReferencia(string text) - { - TabelaReferencia tabelaReferencium; - if (!Enum.TryParse(text, true, out tabelaReferencium)) - { - return null; - } - return new TabelaReferencia?((TabelaReferencia)Enum.Parse(typeof(TabelaReferencia), text, true)); - } - - public static string GetText(string html) - { - HtmlDocument htmlDocument = new HtmlDocument(); - htmlDocument.LoadHtml(html); - return Funcoes.NodeText(htmlDocument.get_DocumentNode()); - } - - public static TipoCobertura? GetTipoCobertura(string text) - { - TipoCobertura tipoCobertura; - if (text.Contains("incendio") || text.Contains("incêndio")) - { - return new TipoCobertura?(2); - } - if (text.Contains("roubo") && text.Contains("furto")) - { - return new TipoCobertura?(5); - } - if (text.Contains("terceiros")) - { - return new TipoCobertura?(3); - } - if (text.Contains("compreensiva")) - { - return new TipoCobertura?(1); - } - if (!Enum.TryParse(text, true, out tipoCobertura)) - { - return null; - } - return new TipoCobertura?((TipoCobertura)Enum.Parse(typeof(TipoCobertura), text, true)); - } - - public static string GetTypeAttribute(this PropertyInfo pi) - { - object obj = pi.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); - if (obj == null) - { - return ""; - } - return ((TipoAttribute)obj).get_Description(); - } - - public static UsoVeiculo? GetUsoveiculo(string text) - { - UsoVeiculo usoVeiculo; - UsoVeiculo usoVeiculo1; - if (Enum.TryParse(text, true, out usoVeiculo)) - { - usoVeiculo1 = usoVeiculo; - } - else - { - usoVeiculo1 = 0; - } - return new UsoVeiculo?(usoVeiculo1); - } - - public static T GetValueFromType(this object objeto) - { - Type type = typeof(T); - PropertyInfo[] properties = objeto.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); - for (int i = 0; i < (int)properties.Length; i++) - { - PropertyInfo propertyInfo = properties[i]; - if (propertyInfo.PropertyType == type) - { - return (T)propertyInfo.GetValue(objeto); - } - } - return default(T); - } - - public static async Task InativarItens(long id, long ramo, bool delete = true) - { - bool sucesso; - ItemServico itemServico = new ItemServico(); - ObservableCollection observableCollection = await itemServico.BuscarItens(id); - ObservableCollection observableCollection1 = observableCollection; - IEnumerable hasValue = - from x in observableCollection1 - where x.get_Substituicao().HasValue - select x; - if (await Funcoes.ReativarItens(( - from x in hasValue - select x.get_Substituicao().Value).ToList())) - { - if (!delete) - { - List list = observableCollection.ToList(); - list.ForEach((Item x) => x.set_Cancelado(true)); - await itemServico.SaveRange(observableCollection.ToList()); - } - else - { - await itemServico.DeleteRange(observableCollection.ToList(), ramo); - } - sucesso = itemServico.Sucesso; - } - else - { - sucesso = false; - } - itemServico = null; - observableCollection = null; - return sucesso; - } - - public static bool IsEmpty(this string html) - { - int count = Regex.Matches(html, "").Count; - bool flag = true; - int num = 0; - for (int i = 0; i < count; i++) - { - int num1 = html.IndexOf("", num, StringComparison.Ordinal) + 6; - if (num1 == 5) - { - break; - } - int num2 = html.IndexOf("", num, StringComparison.Ordinal); - num = num2 + 7; - flag = string.IsNullOrWhiteSpace(html.Substring(num1, num2 - num1)); - if (!flag) - { - break; - } - } - return flag; - } - - public static Window IsHosterOpen(string name) - { - return System.Windows.Application.Current.Windows.OfType().ToList().FirstOrDefault((HosterWindow x) => { - string str; - ContentControl contentControl = Extentions.FindVisualChildren(x).FirstOrDefault(); - if (contentControl != null) - { - str = contentControl.Tag.ToString(); - } - else - { - str = null; - } - return str == name; - }); - } - - public static bool IsWindowOpen(string title) - where T : Window - { - return System.Windows.Application.Current.Windows.OfType().Any((T x) => x.Title == title); - } - - public static List LogList(this List valores, bool restricaoComissao = false) - { - List> tuples = new List>(); - valores.ForEach((ValorOriginal x) => { - if (restricaoComissao && x.get_Campo().ToUpper().Contains("COMISSÃO")) - { - return; - } - tuples.Add(new Tuple(x.get_Descricao(), (string.IsNullOrEmpty(x.get_ValorAtual()) ? "NÃO PREENCHIDO" : (x.get_ValorAtual() == "True" ? "SIM" : (x.get_ValorAtual() == "False" ? "NÃO" : x.get_ValorAtual()))), "")); - }); - List tupleLists = new List(); - TupleList tupleList = new TupleList(); - tupleList.set_Tuples(new ObservableCollection>(tuples)); - tupleLists.Add(tupleList); - return tupleLists; - } - - public static List LogList(this List valores, bool restricaoComissao = false) - { - List> tuples = new List>(); - valores.ForEach((Diferenca x) => { - if (restricaoComissao && x.get_Campo().ToUpper().Contains("COMISSÃO")) - { - return; - } - tuples.Add(new Tuple(x.get_Descricao(), (string.IsNullOrEmpty(x.get_ValorAtual()) ? "NÃO PREENCHIDO" : (x.get_ValorAtual() == "True" ? "SIM" : (x.get_ValorAtual() == "False" ? "NÃO" : x.get_ValorAtual()))), (string.IsNullOrEmpty(x.get_ValorAnterior()) ? "NÃO PREENCHIDO" : (x.get_ValorAnterior() == "True" ? "SIM" : (x.get_ValorAnterior() == "False" ? "NÃO" : x.get_ValorAnterior()))))); - }); - List tupleLists = new List(); - TupleList tupleList = new TupleList(); - tupleList.set_Tuples(new ObservableCollection>(tuples)); - tupleLists.Add(tupleList); - return tupleLists; - } - - public static async Task MostrarErro(TipoErro erro) - { - await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => (new ErrorWindow(erro, true)).ShowDialog())); - } - - private static string NodeText(HtmlNode node) - { - string innerText = ""; - if (node.get_HasChildNodes()) - { - foreach (HtmlNode childNode in node.get_ChildNodes()) - { - innerText = string.Concat(innerText, (childNode.get_NodeType() == 3 ? childNode.get_InnerText() : Funcoes.NodeText(childNode))); - } - } - else if (node.get_NodeType() == 3) - { - innerText = node.get_InnerText(); - } - return innerText; - } - - public static async Task> OcultarColunas(Relatorio relatorio) - { - List strs; - List strs1 = new List(); - List restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio); - if (restricoesColunas == null || restricoesColunas.Count == 0) - { - strs = strs1; - } - else - { - restricoesColunas = await Funcoes.GetRestricoesColunas(restricoesColunas); - PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); - for (int i = 0; i < (int)properties.Length; i++) - { - PropertyInfo propertyInfo = properties[i]; - object obj = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); - string description = ""; - if (obj != null) - { - description = ((TipoAttribute)obj).get_Description(); - } - string descriptionAttribute = propertyInfo.GetDescriptionAttribute(); - if (description == "INVALID") - { - strs1.Add(descriptionAttribute); - } - if (!restricoesColunas.Any((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name) && !(propertyInfo.Name == "ValidationEvent")) - { - strs1.Add(descriptionAttribute); - } - } - strs = strs1; - } - strs1 = null; - return strs; - } - - public static List OcultarColunasDescricao(Type type, string categoria) - { - List strs = new List(); - PropertyInfo[] properties = type.GetProperties(); - for (int i = 0; i < (int)properties.Length; i++) - { - PropertyInfo propertyInfo = properties[i]; - if (propertyInfo.Name != "ValidationEvent") - { - object obj = propertyInfo.GetCustomAttributes(typeof(CategoryAttribute), true).FirstOrDefault(); - if (obj != null && !(((CategoryAttribute)obj).Category == categoria)) - { - object obj1 = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); - if (obj1 != null) - { - strs.Add(((DescriptionAttribute)obj1).Description); - } - } - } - } - return strs; - } - - public static async Task OrganizarDocumentos(long id) - { - ApoliceServico apoliceServico = new ApoliceServico(); - Controle controle = await apoliceServico.BuscarControleAsync(id); - int num = 1; - IList documentos = controle.get_Documentos(); - IEnumerable excluido = - from x in documentos - where !x.get_Excluido() - select x; - ( - from x in excluido - orderby x.get_Vigencia1() - select x).ToList().ForEach((Documento x) => { - if (x.get_Tipo() == 0) - { - x.set_Ordem(0); - return; - } - x.set_Ordem(num); - num++; - }); - await apoliceServico.UpdateRange(controle); - apoliceServico = null; - } - - public static ParentescoVinculo? ParentescoInverso(ParentescoVinculo? parentesco) - { - if (parentesco.HasValue) - { - switch (parentesco.GetValueOrDefault()) - { - case 0: - { - return new ParentescoVinculo?(1); - } - case 1: - { - return new ParentescoVinculo?(0); - } - case 3: - { - return new ParentescoVinculo?(4); - } - case 4: - { - return new ParentescoVinculo?(3); - } - case 5: - { - return new ParentescoVinculo?(6); - } - case 6: - { - return new ParentescoVinculo?(5); - } - case 7: - { - return new ParentescoVinculo?(8); - } - case 8: - { - return new ParentescoVinculo?(7); - } - case 10: - { - return new ParentescoVinculo?(11); - } - case 11: - { - return new ParentescoVinculo?(10); - } - case 13: - { - return new ParentescoVinculo?(14); - } - case 14: - { - return new ParentescoVinculo?(13); - } - case 19: - { - return new ParentescoVinculo?(20); - } - case 20: - { - return new ParentescoVinculo?(19); - } - case 21: - { - return new ParentescoVinculo?(22); - } - case 22: - { - return new ParentescoVinculo?(21); - } - } - } - return parentesco; - } - - public static TipoPagamento ParseTransactionType(this OfxTransactionType type) - { - switch (type) - { - case 0: - { - return 5; - } - case 1: - case 4: - { - return 7; - } - case 6: - case 13: - { - return 8; - } - case 7: - case 12: - { - return 10; - } - case 10: - { - return 4; - } - case 11: - { - return 15; - } - case 14: - { - return 6; - } - default: - { - return 12; - } - } - } - - public static string PlacaVencimento(string placa, Categoria? categoria) - { - if (string.IsNullOrEmpty(placa)) - { - return ""; - } - string str = placa.Substring(placa.Length - 1, 1); - if (str != null && str.Length == 1) - { - switch (str[0]) - { - case '0': - { - return "DEZEMBRO"; - } - case '1': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "SETEMBRO"; - } - return "ABRIL"; - } - case '2': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "SETEMBRO"; - } - return "MAIO"; - } - case '3': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "OUTUBRO"; - } - return "JUNHO"; - } - case '4': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "OUTUBRO"; - } - return "JULHO"; - } - case '5': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "OUTUBRO"; - } - return "AGOSTO"; - } - case '6': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "NOVEMBRO"; - } - return "AGOSTO"; - } - case '7': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "NOVEMBRO"; - } - return "SETEMBRO"; - } - case '8': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "NOVEMBRO"; - } - return "OUTUBRO"; - } - case '9': - { - if (categoria.HasValue && categoria.GetValueOrDefault() == 4) - { - return "DEZEMBRO"; - } - return "NOVEMBRO"; - } - } - } - return ""; - } - - public static List PopularFiltroFinanceiro() - { - List filtroPersonalizados = new List(); - FiltroPersonalizado filtroPersonalizado = new FiltroPersonalizado(); - filtroPersonalizado.set_Propriedade("Id"); - filtroPersonalizado.set_Nome("ID"); - filtroPersonalizado.set_Tipo(typeof(long)); - filtroPersonalizados.Add(filtroPersonalizado); - FiltroPersonalizado filtroPersonalizado1 = new FiltroPersonalizado(); - filtroPersonalizado1.set_Propriedade("Controle.Fornecedor.NomeSocial"); - filtroPersonalizado1.set_Nome("FORNECEDOR"); - filtroPersonalizado1.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado1); - FiltroPersonalizado filtroPersonalizado2 = new FiltroPersonalizado(); - filtroPersonalizado2.set_Propriedade("Controle.Fornecedor.Ativo"); - filtroPersonalizado2.set_Nome("FORNECEDOR ATIVO"); - filtroPersonalizado2.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado2); - FiltroPersonalizado filtroPersonalizado3 = new FiltroPersonalizado(); - filtroPersonalizado3.set_Propriedade("Historico"); - filtroPersonalizado3.set_Nome("HISTÓRICO"); - filtroPersonalizado3.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado3); - FiltroPersonalizado filtroPersonalizado4 = new FiltroPersonalizado(); - filtroPersonalizado4.set_Propriedade("Parcela"); - filtroPersonalizado4.set_Nome("PARCELA"); - filtroPersonalizado4.set_Tipo(typeof(int)); - filtroPersonalizados.Add(filtroPersonalizado4); - FiltroPersonalizado filtroPersonalizado5 = new FiltroPersonalizado(); - filtroPersonalizado5.set_Propriedade("Documento"); - filtroPersonalizado5.set_Nome("DOCUMENTO"); - filtroPersonalizado5.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado5); - FiltroPersonalizado filtroPersonalizado6 = new FiltroPersonalizado(); - filtroPersonalizado6.set_Propriedade("Competencia"); - filtroPersonalizado6.set_Nome("COMPETÊNCIA"); - filtroPersonalizado6.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado6); - FiltroPersonalizado filtroPersonalizado7 = new FiltroPersonalizado(); - filtroPersonalizado7.set_Propriedade("Complemento"); - filtroPersonalizado7.set_Nome("COMPLEMENTO"); - filtroPersonalizado7.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado7); - FiltroPersonalizado filtroPersonalizado8 = new FiltroPersonalizado(); - filtroPersonalizado8.set_Propriedade("Vencimento"); - filtroPersonalizado8.set_Nome("VENCIMENTO"); - filtroPersonalizado8.set_Tipo(typeof(DateTime)); - filtroPersonalizados.Add(filtroPersonalizado8); - FiltroPersonalizado filtroPersonalizado9 = new FiltroPersonalizado(); - filtroPersonalizado9.set_Propriedade("Valor"); - filtroPersonalizado9.set_Nome("VALOR"); - filtroPersonalizado9.set_Tipo(typeof(decimal)); - filtroPersonalizados.Add(filtroPersonalizado9); - FiltroPersonalizado filtroPersonalizado10 = new FiltroPersonalizado(); - filtroPersonalizado10.set_Propriedade("Baixa"); - filtroPersonalizado10.set_Nome("DATA BAIXA"); - filtroPersonalizado10.set_Tipo(typeof(DateTime)); - filtroPersonalizados.Add(filtroPersonalizado10); - FiltroPersonalizado filtroPersonalizado11 = new FiltroPersonalizado(); - filtroPersonalizado11.set_Propriedade("ValorPago"); - filtroPersonalizado11.set_Nome("VALOR PAGO"); - filtroPersonalizado11.set_Tipo(typeof(decimal)); - filtroPersonalizados.Add(filtroPersonalizado11); - FiltroPersonalizado filtroPersonalizado12 = new FiltroPersonalizado(); - filtroPersonalizado12.set_Propriedade("Pagamento"); - filtroPersonalizado12.set_Nome("PAGAMENTO"); - filtroPersonalizado12.set_Tipo(typeof(DateTime)); - filtroPersonalizados.Add(filtroPersonalizado12); - FiltroPersonalizado filtroPersonalizado13 = new FiltroPersonalizado(); - filtroPersonalizado13.set_Propriedade("Conta.Descricao"); - filtroPersonalizado13.set_Nome("CONTA"); - filtroPersonalizado13.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado13); - FiltroPersonalizado filtroPersonalizado14 = new FiltroPersonalizado(); - filtroPersonalizado14.set_Propriedade("Controle.Plano.Descricao"); - filtroPersonalizado14.set_Nome("PLANO DE CONTAS"); - filtroPersonalizado14.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado14); - FiltroPersonalizado filtroPersonalizado15 = new FiltroPersonalizado(); - filtroPersonalizado15.set_Propriedade("Controle.Centro.Descricao"); - filtroPersonalizado15.set_Nome("CENTRO DE CUSTO"); - filtroPersonalizado15.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado15); - FiltroPersonalizado filtroPersonalizado16 = new FiltroPersonalizado(); - filtroPersonalizado16.set_Propriedade("Sinal"); - filtroPersonalizado16.set_Nome("SINAL"); - filtroPersonalizado16.set_Tipo(typeof(Enum)); - filtroPersonalizados.Add(filtroPersonalizado16); - FiltroPersonalizado filtroPersonalizado17 = new FiltroPersonalizado(); - filtroPersonalizado17.set_Propriedade("TipoPagamento"); - filtroPersonalizado17.set_Nome("FORMA PAGAMENTO"); - filtroPersonalizado17.set_Tipo(typeof(Enum)); - filtroPersonalizados.Add(filtroPersonalizado17); - FiltroPersonalizado filtroPersonalizado18 = new FiltroPersonalizado(); - filtroPersonalizado18.set_Propriedade("Observacao"); - filtroPersonalizado18.set_Nome("OBSERVAÇÃO"); - filtroPersonalizado18.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado18); - FiltroPersonalizado filtroPersonalizado19 = new FiltroPersonalizado(); - filtroPersonalizado19.set_Propriedade("Controle.Plano.Nome"); - filtroPersonalizado19.set_Nome("PLANO"); - filtroPersonalizado19.set_Tipo(typeof(string)); - filtroPersonalizados.Add(filtroPersonalizado19); - return filtroPersonalizados; - } - - public static List PopularFiltroPersonalizado() - { - List filtroPersonalizados = new List(); - foreach (PropertyInfo propertyInfo in - from in (IEnumerable)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public) - orderby Gestor.Common.Validation.ValidationHelper.DescriptionAttribute(x) - select ) - { - if (propertyInfo.Name == "ValidationEvent") - { - continue; - } - FiltroPersonalizado filtroPersonalizado = new FiltroPersonalizado(); - filtroPersonalizado.set_Propriedade(propertyInfo.Name); - filtroPersonalizado.set_Nome(propertyInfo.GetDescriptionAttribute()); - FiltroPersonalizado filtroPersonalizado1 = filtroPersonalizado; - if (propertyInfo.GetTypeAttribute() == "INVALID") - { - continue; - } - Type propertyType = propertyInfo.PropertyType; - if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - propertyType = propertyType.GetGenericArguments()[0]; - } - filtroPersonalizado1.set_Tipo((propertyType.BaseType == typeof(Enum) ? propertyType.BaseType : propertyType)); - filtroPersonalizados.Add(filtroPersonalizado1); - } - return filtroPersonalizados; - } - - public static bool ProgramaEmExecucao(this string programName) - { - return Process.GetProcessesByName(programName).Length != 0; - } - - public static async Task ReativarItens(List ids) - { - ItemServico itemServico = new ItemServico(); - List items = await itemServico.BuscarItems(ids); - List items1 = items; - items1.ForEach((Item x) => { - x.set_Substituido(null); - x.set_Cancelado(false); - x.set_Status(x.get_StatusInclusao()); - }); - await itemServico.SaveRange(items); - bool sucesso = itemServico.Sucesso; - itemServico = null; - return sucesso; - } - - public static async Task RecusarApolice(Documento documento, string motivo, bool estorno) - { - bool flag; - string str; - NegocioCorretora negocioCorretora; - NegocioCorretora negocioCorretora1; - ApoliceServico apoliceServico = new ApoliceServico(); - CriticaApoliceServico criticaApoliceServico = new CriticaApoliceServico(); - if (documento.get_Tipo() != 0 || !string.IsNullOrEmpty(documento.get_Apolice())) - { - str = (documento.get_Tipo() != 0 || string.IsNullOrEmpty(documento.get_Apolice()) ? "ENDOSSO RECUSADO" : "APÓLICE RECUSADA"); - } - else - { - str = "PROPOSTA RECUSADA"; - } - string str1 = str; - if (!string.IsNullOrWhiteSpace(motivo)) - { - Documento documento1 = documento; - object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, motivo, Environment.NewLine, Environment.NewLine, documento.get_Observacao() }; - documento1.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}RECUSA: {4}{5}{6}{7}", nome)); - } - if (documento.get_Tipo() != 0) - { - if (!documento.get_NegocioCorretora().HasValue) - { - Documento documento2 = documento; - negocioCorretora = (!documento.get_Negocio().HasValue || documento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); - documento2.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora)); - } - documento.set_Situacao(7); - documento.set_Apolice("RECUSADA"); - documento.set_Endosso("RECUSADA"); - flag = await apoliceServico.BaixarParcelasCancelamento(documento, estorno); - if (!flag) - { - Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; - if (acessaTela != null) - { - acessaTela(21, ""); - } - else - { - } - } - await apoliceServico.Save(documento, false, false); - if (!apoliceServico.Sucesso) - { - Action action = Gestor.Application.Actions.Actions.AcessaTela; - if (action != null) - { - action(21, ""); - } - else - { - } - } - if (!apoliceServico.Sucesso) - { - Action acessaTela1 = Gestor.Application.Actions.Actions.AcessaTela; - if (acessaTela1 != null) - { - acessaTela1(21, ""); - } - else - { - } - } - flag = await Funcoes.InativarItens(documento.get_Id(), documento.get_Controle().get_Ramo().get_Id(), false); - if (!flag) - { - Action action1 = Gestor.Application.Actions.Actions.AcessaTela; - if (action1 != null) - { - action1(21, ""); - } - else - { - } - } - } - else - { - await apoliceServico.Save(documento, false, false); - Controle controle = await apoliceServico.BuscarControleAsync(documento.get_Controle().get_Id()); - if (controle.get_Id() != 0) - { - foreach (Documento documento3 in controle.get_Documentos()) - { - if (!documento3.get_NegocioCorretora().HasValue) - { - Documento documento4 = documento3; - negocioCorretora1 = (!documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); - documento4.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1)); - } - documento3.set_Situacao(7); - documento3.set_Apolice("RECUSADA"); - flag = await apoliceServico.BaixarParcelasCancelamento(documento3, estorno); - if (flag) - { - continue; - } - Action acessaTela2 = Gestor.Application.Actions.Actions.AcessaTela; - if (acessaTela2 != null) - { - acessaTela2(21, ""); - } - else - { - } - } - flag = await apoliceServico.UpdateRange(controle); - controle = null; - } - else - { - apoliceServico = null; - criticaApoliceServico = null; - str1 = null; - return; - } - } - if (!flag) - { - Action action2 = Gestor.Application.Actions.Actions.AcessaTela; - if (action2 != null) - { - action2(21, ""); - } - else - { - } - } - List criticaApolices = await criticaApoliceServico.BuscarCritica(documento.get_Id()); - if (criticaApolices != null) - { - foreach (CriticaApolice criticaApolouse in criticaApolices) - { - criticaApolouse.set_Critica(new bool?(true)); - await criticaApoliceServico.Save(criticaApolouse); - } - } - Action acessaTela3 = Gestor.Application.Actions.Actions.AcessaTela; - if (acessaTela3 != null) - { - acessaTela3(21, ""); - } - else - { - } - Funcoes.ToggleSnackBar(string.Concat(str1, " COM SUCESSO"), true); - apoliceServico = null; - criticaApoliceServico = null; - str1 = null; - } - - private static async void RegistrarLogBaixa(long id, DateTime now) - { - string str; - ApoliceServico apoliceServico = new ApoliceServico(); - ParcelaServico parcelaServico = new ParcelaServico(); - VendedorServico vendedorServico = new VendedorServico(); - Documento documento = await apoliceServico.BuscarApoliceAsync(id, false, false); - Documento documento1 = documento; - ObservableCollection observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id()); - documento1.set_Parcelas(observableCollection); - documento1 = null; - List vendedorParcelas = await vendedorServico.BuscaRepasse(documento.get_Id()); - foreach (Parcela parcela in documento.get_Parcelas()) - { - foreach (VendedorParcela vendedorParcela in vendedorParcelas) - { - if (vendedorParcela.get_Parcela().get_Id() != parcela.get_Id()) - { - continue; - } - if (parcela.get_Vendedores() == null) - { - parcela.set_Vendedores(new ObservableCollection()); - } - parcela.get_Vendedores().Add(vendedorParcela); - } - } - IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); - RegistroLog registroLog = new RegistroLog(); - registroLog.set_Acao(1); - registroLog.set_Usuario(Recursos.Usuario); - registroLog.set_DataHora(now); - Documento documento2 = documento; - JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); - jsonSerializerSetting.set_ReferenceLoopHandling(1); - registroLog.set_Descricao(JsonConvert.SerializeObject(documento2, jsonSerializerSetting)); - registroLog.set_EntidadeId(documento.get_Id()); - registroLog.set_Tela(2); - registroLog.set_NomeMaquina(Environment.MachineName); - registroLog.set_UsuarioMaquina(Environment.UserName); - IPAddress[] addressList = hostEntry.AddressList; - IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); - if (pAddress != null) - { - str = pAddress.ToString(); - } - else - { - str = null; - } - registroLog.set_Ip(str); - RegistroLog registroLog1 = registroLog; - using (UnitOfWork commited = Instancia.Commited) - { - commited.get_RegistroLogRepository().SaveOrUpdate(registroLog1); - commited.Commit(); - } - parcelaServico = null; - vendedorServico = null; - documento = null; - } - - public static string RemoverAcentos(string text) - { - string str = text.Normalize(NormalizationForm.FormD); - StringBuilder stringBuilder = new StringBuilder(); - foreach (char chr in - from c in str - let unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c) - where unicodeCategory != UnicodeCategory.NonSpacingMark - select c) - { - stringBuilder.Append(chr); - } - return stringBuilder.ToString().Normalize(NormalizationForm.FormC); - } - - [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] - private static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)] - private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - - public static string SubstituirVariaveis(string corpo, MalaDireta envio) - { - DateTime? vigencia2; - DateTime vigencia1; - decimal valor; - decimal? nullable; - bool controle; - bool flag; - string str; - string str1; - string str2; - string str3; - object obj; - string str4; - string str5; - string description; - decimal? nullable1; - string str6; - decimal? nullable2; - string str7; - DateTime networkTime = Funcoes.GetNetworkTime(); - VariaveisMalaDireta[] values = (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta)); - for (int i = 0; i < (int)values.Length; i++) - { - VariaveisMalaDireta variaveisMalaDiretum = values[i]; - switch (variaveisMalaDiretum) - { - case 0: - { - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), networkTime.ToString(new CultureInfo("pt-BR"))); - break; - } - case 1: - { - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(envio.get_Cliente().get_NomeSocialRg()) ? envio.get_Cliente().get_NomeSocialRg() : envio.get_Cliente().get_Nome())); - break; - } - case 2: - { - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Cliente().get_Documento()); - break; - } - case 3: - { - if (envio.get_Apolice() == null) - { - break; - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Proposta()); - break; - } - case 4: - { - if (envio.get_Apolice() == null) - { - break; - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Concat(envio.get_Apolice().get_Apolice(), (envio.get_Apolice().get_Tipo() != 0 ? string.Concat(", endosso de número: ", envio.get_Apolice().get_Endosso()) : ""))); - break; - } - case 5: - { - Documento apolice = envio.get_Apolice(); - if (apolice != null) - { - controle = apolice.get_Controle(); - } - else - { - controle = false; - } - if (!controle) - { - break; - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Controle().get_Ramo().get_Nome()); - break; - } - case 6: - { - Documento documento = envio.get_Apolice(); - if (documento != null) - { - flag = documento.get_Controle(); - } - else - { - flag = false; - } - if (!flag) - { - break; - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Controle().get_Seguradora().get_Nome()); - break; - } - case 7: - { - if (envio.get_Apolice() == null) - { - break; - } - string entity = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - vigencia1 = envio.get_Apolice().get_Vigencia1(); - corpo = corpo.Replace(entity, vigencia1.ToString("d")); - break; - } - case 8: - { - if (envio.get_Apolice() == null) - { - break; - } - string str8 = corpo; - string entity1 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - vigencia2 = envio.get_Apolice().get_Vigencia2(); - if (vigencia2.HasValue) - { - vigencia1 = vigencia2.GetValueOrDefault(); - str = vigencia1.ToString("d"); - } - else - { - str = null; - } - corpo = str8.Replace(entity1, str); - break; - } - case 9: - { - if (envio.get_Parcela() == null) - { - break; - } - string entity2 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - vigencia1 = envio.get_Parcela().get_Vencimento(); - corpo = corpo.Replace(entity2, vigencia1.ToString("d")); - break; - } - case 10: - { - if (envio.get_Parcela() == null) - { - break; - } - string entity3 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - valor = envio.get_Parcela().get_Valor(); - corpo = corpo.Replace(entity3, valor.ToString("c2")); - break; - } - case 11: - { - if (envio.get_Item() == null) - { - break; - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Item().get_Descricao()); - break; - } - case 12: - { - if (envio.get_Sinistro() == null) - { - break; - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Sinistro().get_Numero()); - break; - } - case 13: - { - if (envio.get_Parcela() == null) - { - break; - } - string entity4 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - int numeroParcela = envio.get_Parcela().get_NumeroParcela(); - corpo = corpo.Replace(entity4, numeroParcela.ToString()); - break; - } - case 14: - { - vigencia2 = envio.get_Cliente().get_Nascimento(); - if (!vigencia2.HasValue) - { - break; - } - string str9 = corpo; - string entity5 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - vigencia2 = envio.get_Cliente().get_Nascimento(); - if (vigencia2.HasValue) - { - vigencia1 = vigencia2.GetValueOrDefault(); - str1 = vigencia1.ToString("dd/MM"); - } - else - { - str1 = null; - } - corpo = str9.Replace(entity5, str1); - break; - } - case 15: - { - vigencia2 = envio.get_Cliente().get_Nascimento(); - if (!vigencia2.HasValue) - { - break; - } - string str10 = corpo; - string entity6 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - vigencia2 = envio.get_Cliente().get_Nascimento(); - if (vigencia2.HasValue) - { - vigencia1 = vigencia2.GetValueOrDefault(); - str2 = vigencia1.ToString("d"); - } - else - { - str2 = null; - } - corpo = str10.Replace(entity6, str2); - break; - } - case 16: - { - string str11 = corpo; - string entity7 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - vigencia2 = envio.get_Cliente().get_VencimentoHabilitacao(); - if (vigencia2.HasValue) - { - vigencia1 = vigencia2.GetValueOrDefault(); - str3 = vigencia1.ToString("d"); - } - else - { - str3 = null; - } - corpo = str11.Replace(entity7, str3); - break; - } - case 17: - { - if (envio.get_ArquivoDigital() != null) - { - if (!envio.get_ArquivoDigital().All((IndiceArquivoDigital x) => string.IsNullOrWhiteSpace(x.get_UrlAssinatura()))) - { - string str12 = ""; - ( - from x in envio.get_ArquivoDigital() - where !string.IsNullOrWhiteSpace(x.get_UrlAssinatura()) - select x).ToList().ForEach((IndiceArquivoDigital x) => str12 = string.Concat(new string[] { str12, "" })); - str12 = string.Concat(str12, "
ABAIXO OS DOCUMENTOS PARA ASSINATURA
", x.get_Descricao(), "
"); - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str12); - break; - } - } - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Empty); - break; - } - case 18: - { - string str13 = string.Format("ABAIXO O LINK PARA MEU CARTÃO DE VISITA.
CARTÃO DE VISITA ELETRÔNICO", Address.get_Card(), Recursos.Usuario.get_Id().GeraCartaoVisita()); - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str13); - break; - } - case 19: - { - if (envio.get_Apolice() != null) - { - Uri assistance = Address.get_Assistance(); - if (envio != null) - { - Documento apolice1 = envio.get_Apolice(); - if (apolice1 != null) - { - obj = apolice1.get_Id().GeraAssistencia(); - } - else - { - obj = null; - } - } - else - { - obj = null; - } - string str14 = string.Format("ABAIXO O LINK PARA O SEU CARTÃO ASSISTÊNCIA.
CARTÃO ASSISTÊNCIA", assistance, obj); - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str14); - break; - } - else - { - corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Empty); - break; - } - } - case 20: - { - string str15 = corpo; - string entity8 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - Documento documento1 = envio.get_Apolice(); - if (documento1 != null) - { - str4 = documento1.get_PremioLiquido().ToString("c"); - } - else - { - str4 = null; - } - corpo = str15.Replace(entity8, str4); - break; - } - case 21: - { - string str16 = corpo; - string entity9 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - Documento apolice2 = envio.get_Apolice(); - if (apolice2 != null) - { - str5 = apolice2.get_PremioTotal().ToString("c"); - } - else - { - str5 = null; - } - corpo = str16.Replace(entity9, str5); - break; - } - case 22: - { - string str17 = corpo; - string entity10 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - Documento documento2 = envio.get_Apolice(); - if (documento2 != null) - { - FormaPagamento? formaPagamento = documento2.get_FormaPagamento(); - if (formaPagamento.HasValue) - { - description = Gestor.Common.Validation.ValidationHelper.GetDescription(formaPagamento.GetValueOrDefault()); - } - else - { - description = null; - } - } - else - { - description = null; - } - corpo = str17.Replace(entity10, description); - break; - } - case 23: - { - string str18 = corpo; - string entity11 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - Documento apolice3 = envio.get_Apolice(); - if (apolice3 != null) - { - nullable1 = new decimal?(apolice3.get_NumeroParcelas()); - } - else - { - nullable = null; - nullable1 = nullable; - } - if (!nullable1.HasValue || envio.get_Apolice().get_TipoRecebimento().GetValueOrDefault() == 2) - { - str6 = "Indefinido"; - } - else - { - Documento documento3 = envio.get_Apolice(); - if (documento3 != null) - { - str6 = documento3.get_NumeroParcelas().ToString(); - } - else - { - str6 = null; - } - } - corpo = str18.Replace(entity11, str6); - break; - } - case 24: - { - string str19 = corpo; - string entity12 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum); - Documento apolice4 = envio.get_Apolice(); - if (apolice4 != null) - { - nullable2 = new decimal?(apolice4.get_NumeroParcelas()); - } - else - { - nullable = null; - nullable2 = nullable; - } - if (!nullable2.HasValue || envio.get_Apolice().get_NumeroParcelas() == decimal.Zero || envio.get_Apolice().get_TipoRecebimento().GetValueOrDefault() == 2) - { - str7 = "Verificar documento anexado"; - } - else - { - valor = envio.get_Apolice().get_PremioTotal() / envio.get_Apolice().get_NumeroParcelas(); - str7 = valor.ToString(); - } - corpo = str19.Replace(entity12, str7); - break; - } - } - } - return corpo; - } - - public static void ToggleSnackBar(string message, bool active = true) - { - App.SnackBar.get_Message().Content = message; - App.SnackBar.set_IsActive(active); - if (!active) - { - return; - } - Task.Factory.StartNew(new Action(Funcoes.CloseSlackBar)); - } - - public static List TotalizacoesRelatorio(Relatorio relatorio, List parametrosAdicionados) - { - long id; - List parametrosTotalizacaos = new List(); - List strs = new List(); - switch (relatorio) - { - case 2: - case 3: - { - strs.Add("PremioTotal"); - strs.Add("PremioLiquido"); - strs.Add("MediaComissao"); - strs.Add("ComissaoGerada"); - strs.Add("Cancelamentos"); - strs.Add("Novos"); - strs.Add("NegociosProprios"); - strs.Add("Renovacoes"); - strs.Add("SegurosNovos"); - strs.Add("Apolices"); - strs.Add("Endossos"); - strs.Add("Faturas"); - strs.Add("TotalGeral"); - strs.Add("MediaPonderada"); - goto case 15; - } - case 4: - { - strs.Add("Cancelamentos"); - strs.Add("Novos"); - strs.Add("Renovacoes"); - strs.Add("Apolices"); - strs.Add("Endossos"); - strs.Add("Faturas"); - strs.Add("TotalProspeccao"); - strs.Add("TotalGeral"); - strs.Add("PremioTotal"); - strs.Add("PremioLiquido"); - strs.Add("ComissaoGerada"); - goto case 15; - } - case 5: - { - strs.Add("ComissaoRecebidaBruta"); - strs.Add("ComissaoRecebidaLiquida"); - strs.Add("ComissaoPrevista"); - strs.Add("Repasse"); - strs.Add("Impostos"); - strs.Add("PremioTotal"); - strs.Add("PremioLiquido"); - goto case 15; - } - case 6: - case 16: - { - strs.Add("ComissaoPrevista"); - strs.Add("TotalPrevista"); - strs.Add("TotalGeral"); - strs.Add("TotalParcela"); - goto case 15; - } - case 7: - case 11: - case 12: - case 13: - case 14: - case 15: - { - PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); - foreach (PropertyInfo propertyInfo in - from in (IEnumerable)properties - orderby x.GetDescriptionAttribute() - select ) - { - if (propertyInfo.Name == "ValidationEvent" || propertyInfo.GetTypeAttribute() == "INVALID" || !strs.Contains(propertyInfo.Name) || propertyInfo.Name == "Agrupamento" || parametrosAdicionados.Any((ParametrosTotalizacao x) => x.get_Campo() == propertyInfo.Name)) - { - continue; - } - ParametrosTotalizacao parametrosTotalizacao = new ParametrosTotalizacao(); - ParametrosTotalizacao parametrosTotalizacao1 = parametrosAdicionados.FirstOrDefault((ParametrosTotalizacao x) => { - if (x.get_IdUsuario() == 0) - { - return false; - } - return x.get_Campo() == propertyInfo.Name; - }); - if (parametrosTotalizacao1 != null) - { - id = parametrosTotalizacao1.get_Id(); - } - else - { - id = (long)0; - } - parametrosTotalizacao.set_Id(id); - parametrosTotalizacao.set_Campo(propertyInfo.Name); - parametrosTotalizacao.set_Header(propertyInfo.GetDescriptionAttribute()); - parametrosTotalizacao.set_IdUsuario(Recursos.Usuario.get_Id()); - parametrosTotalizacao.set_Relatorio(relatorio); - parametrosTotalizacaos.Add(parametrosTotalizacao); - } - return parametrosTotalizacaos; - } - case 8: - { - strs.Add("PremioTotal"); - strs.Add("PremioLiquido"); - strs.Add("ComissaoRecebidaBruta"); - strs.Add("MediaComissao"); - strs.Add("TotalPrevista"); - strs.Add("ComissaoGerada"); - strs.Add("Cancelamentos"); - strs.Add("Novos"); - strs.Add("Renovacoes"); - strs.Add("Apolices"); - strs.Add("Endossos"); - strs.Add("Faturas"); - strs.Add("TotalGeral"); - goto case 15; - } - case 9: - case 10: - { - strs.Add("Liquidado"); - strs.Add("ValorLiquidado"); - strs.Add("Pendente"); - strs.Add("TotalGeral"); - strs.Add("TotalClientes"); - strs.Add("TotalTerceiros"); - goto case 15; - } - default: - { - goto case 15; - } - } - } - - public static long UnixTimeStamp() - { - DateTime utcNow = DateTime.UtcNow; - TimeSpan timeSpan = utcNow.Subtract(new DateTime(1970, 1, 1)); - return (long)timeSpan.TotalSeconds; - } - - public static string ValidaNomePlanilha(this string nome, string agrupamento = "", int index = 0) - { - if (string.IsNullOrWhiteSpace(nome)) - { - nome = agrupamento; - } - nome = nome.Replace("/", "_").Replace(":", " ").Replace("*", " ").Replace("?", "").Trim(); - if (index > 0) - { - nome = string.Format("{0} {1}", index, nome); - } - if (nome.Length > 30) - { - nome = nome.Substring(0, 30); - } - return nome; - } - - public static async Task VerificarPagamento(long id) - { - bool[] flagArray = new bool[2]; - List parcelas = await (new ParcelaServico()).BuscarParcelas(id); - if (parcelas.Any((Parcela x) => x.get_DataRecebimento().HasValue)) - { - flagArray[0] = true; - } - List vendedorParcelas = await (new VendedorServico()).BuscaRepasse(id); - if (vendedorParcelas.Any((VendedorParcela x) => x.get_DataPagamento().HasValue)) - { - flagArray[1] = true; - } - bool[] flagArray1 = flagArray; - flagArray = null; - return flagArray1; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/HttpHelper.cs b/Gestor.Application/Helpers/HttpHelper.cs deleted file mode 100644 index e042d1b..0000000 --- a/Gestor.Application/Helpers/HttpHelper.cs +++ /dev/null @@ -1,103 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Net.Http; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading.Tasks; - -namespace Gestor.Application.Helpers -{ - public static class HttpHelper - { - public static Uri AddQuery(this Uri uri, string name, T value) - { - // - // Current member / type: System.Uri Gestor.Application.Helpers.HttpHelper::AddQuery(System.Uri,System.String,T) - // File path: C:\AggerSeguros\Gestor.Application.exe - // - // Product version: 0.0.0.0 - // Exception in: System.Uri AddQuery(System.Uri,System.String,T) - // - // Managed pointer usage not in SSA - // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.CheckForAssignment(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 100 - // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitBinaryExpression(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 80 - // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 - // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitExpressions() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 41 - // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 29 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 - // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 - // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 - // - // mailto: JustDecompilePublicFeedback@telerik.com - - } - - public static Dictionary ParseQueryString(this Uri uri) - { - int num = uri.Query.IndexOf('?') + 1; - return ( - from o in uri.Query.Substring(num).Split(new char[] { '&' }) - select o.Split(new char[] { '=' }) into items - where (int)items.Length == 2 - select items).ToDictionary((string[] pair) => pair[0], (string[] pair) => pair[1]); - } - - public static Uri SetQuery(this Uri uri, string name, string value, bool escapeValue = true) - { - UriBuilder uriBuilder = new UriBuilder(uri); - Dictionary strs = uri.ParseQueryString(); - string str = (escapeValue ? Uri.EscapeDataString(value) : value); - if (strs.ContainsKey(name)) - { - strs.Remove(name); - } - strs.Add(name, str); - List list = ( - from x in strs - select string.Concat(x.Key, "=", x.Value)).ToList(); - uriBuilder.Query = string.Join("&", list); - return uriBuilder.Uri; - } - - public static string ToBase64BasicEncode(this string value) - { - return string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(value))); - } - - public static StringContent ToHttpContent(this T content, Encoding encoding = null, string mediaType = "application/json") - { - return new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, mediaType); - } - - public static JObject ToJObject(this string jsonString) - { - JObject jObject; - try - { - jObject = JObject.Parse(jsonString); - } - catch (Exception exception) - { - jObject = null; - } - return jObject; - } - - public static JObject ToJObject(this HttpContent content) - { - return content.ReadAsStringAsync().Result.ToJObject(); - } - - public static Uri ToUri(this string uri) - { - Uri uri1; - Uri.TryCreate(uri, UriKind.Absolute, out uri1); - return uri1; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/Instancia.cs b/Gestor.Application/Helpers/Instancia.cs deleted file mode 100644 index 5c68db1..0000000 --- a/Gestor.Application/Helpers/Instancia.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Gestor.Application; -using Gestor.Common.Helpers; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Infrastructure.UnitOfWork.Logic; -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - -namespace Gestor.Application.Helpers -{ - public class Instancia - { - public static string Conexao; - - public static Gestor.Application.App App - { - get; - set; - } - - public static UnitOfWork Commited - { - get - { - return Instancia.UnitOfWork(true); - } - } - - public static UnitOfWork Read - { - get - { - return Instancia.UnitOfWork(false); - } - } - - public Instancia() - { - } - - public static void DeleteCfg() - { - string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data"); - string str1 = string.Concat(Connection.Catalog, ".cfg"); - if (File.Exists(string.Concat(str, str1))) - { - File.Delete(string.Concat(str, str1)); - } - } - - public static void ExcluirCfg() - { - File.Delete(string.Concat("Data_", Connection.Catalog, ".cfg")); - File.Delete(string.Concat("File_", Connection.Catalog, ".cfg")); - File.Delete(string.Concat("Sign_", Connection.Catalog, ".cfg")); - } - - private static UnitOfWork UnitOfWork(bool withTransaction = true) - { - DataBaseParameters.set_NovoGestor(true); - Instancia.Conexao = Instancia.Conexao ?? Connection.GetConnection(true); - if (Instancia.Conexao == null) - { - return Instancia.App.ConnectionRetry().Result; - } - UnitOfWork unitOfWork = new UnitOfWork(Instancia.Conexao, withTransaction); - if (unitOfWork.get_HasSession()) - { - return unitOfWork; - } - return Instancia.App.ConnectionRetry().Result; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/InstanciaAssinador.cs b/Gestor.Application/Helpers/InstanciaAssinador.cs deleted file mode 100644 index 6241ae1..0000000 --- a/Gestor.Application/Helpers/InstanciaAssinador.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Assinador.Infrastructure.UnitOfWork.Logic; -using Gestor.Application; -using System; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public class InstanciaAssinador - { - public static string EnderecoConexao; - - public static Gestor.Application.App App - { - get; - set; - } - - public static UnitOfWork Commited - { - get - { - return InstanciaAssinador.UnitOfWork(true); - } - } - - public static UnitOfWork Read - { - get - { - return InstanciaAssinador.UnitOfWork(false); - } - } - - public InstanciaAssinador() - { - } - - private static UnitOfWork UnitOfWork(bool withTransaction = true) - { - InstanciaAssinador.EnderecoConexao = InstanciaAssinador.EnderecoConexao ?? Connection.GetConnection(true); - return new UnitOfWork(InstanciaAssinador.EnderecoConexao, withTransaction); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/LicenseHelper.cs b/Gestor.Application/Helpers/LicenseHelper.cs deleted file mode 100644 index e82c145..0000000 --- a/Gestor.Application/Helpers/LicenseHelper.cs +++ /dev/null @@ -1,572 +0,0 @@ -using Agger.Registro; -using Gestor.Common.Helpers; -using Gestor.Common.Validation; -using Gestor.Model.API; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using Gestor.Model.License; -using Microsoft.Win32; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - -namespace Gestor.Application.Helpers -{ - public class LicenseHelper - { - private string _guid - { - get; - set; - } - - public static DateTime DataAtual - { - get; - private set; - } - - public static int? DiasRestantes - { - get; - set; - } - - public static Gestor.Model.License.Instalacao Instalacao - { - get; - set; - } - - public static List Produtos - { - get; - set; - } - - public static StatusLicenca Status - { - get; - set; - } - - static LicenseHelper() - { - LicenseHelper.Status = 1; - } - - public LicenseHelper() - { - } - - public async Task FindKey() - { - string str; - string str1 = EncryptionHelper.Decrypt((new RegistryHelper(ApplicationHelper.Subkey)).ForceRead("MACHINEID", false)); - str = (string.IsNullOrEmpty(str1) ? string.Concat(this.GetMacAddress(), this.GetMachineSerial()) : str1); - string str2 = str; - string str3 = await Gestor.Application.Helpers.Connection.Get(string.Concat("Installation/Serial/", str2), false, false); - return str3; - } - - public NetworkInterface FindMacAddress(string macToSearch) - { - string[] strArrays = macToSearch.Split(new char[] { '|' }); - return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault((NetworkInterface ni) => strArrays.Contains(ni.GetPhysicalAddress().ToString())); - } - - private string GetFrameworkVersion() - { - try - { - using (RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) - { - if (registryKey != null && registryKey.GetValue("Version") != null) - { - return registryKey.GetValue("Version").ToString(); - } - } - } - catch - { - } - return "<4.5"; - } - - public async Task> GetInstalacoes() - { - List instalacaos = await Gestor.Application.Helpers.Connection.Get>(string.Format("Installation/Machine/{0}", ApplicationHelper.IdFornecedor), true, false); - return instalacaos; - } - - public string GetMacAddress() - { - IEnumerable strs = ((IEnumerable)NetworkInterface.GetAllNetworkInterfaces()).Where((NetworkInterface ni) => { - if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) - { - return true; - } - return ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211; - }).OrderByDescending((NetworkInterface ni) => ni.Id).Select((NetworkInterface x) => x.GetPhysicalAddress().ToString()); - return string.Join("", strs); - } - - private string GetMachineSerial() - { - if (string.IsNullOrEmpty(this._guid)) - { - this._guid = Guid.NewGuid().ToString(); - } - return this._guid; - } - - public async Task Registrar(string chave) - { - string str3 = await Task.Run(() => { - IEnumerable strs; - if (string.IsNullOrEmpty(chave)) - { - return "false"; - } - RegistryHelper registryHelper = new RegistryHelper(""); - string[] strArrays = EncryptionHelper.Decrypt(chave).Split(new char[] { ' ' }); - if ((int)strArrays.Length < 2) - { - return "false"; - } - string str = registryHelper.Verificar(strArrays[0], EncryptionHelper.Encrypt(strArrays[0])); - if (str != "false") - { - if (str == "root") - { - return "root"; - } - ApplicationHelper.NumeroSerial = strArrays[0]; - ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Maintenance/Customer", true, false).Result); - Instancia.Conexao = null; - ApplicationHelper.Subkey = strArrays[0]; - return "true"; - } - DateTime networkTime = Funcoes.GetNetworkTime(); - string result = Gestor.Application.Helpers.Connection.Get("Installation/Time", false, true).Result ?? networkTime.ToString("d"); - if (!ApplicationHelper.Conectado) - { - return "false"; - } - LicenseHelper.DataAtual = DateTime.Parse(string.Format("{0} {1}:{2}:{3}", new object[] { result, networkTime.Hour, networkTime.Minute, networkTime.Second })); - DateTime dateTime = DateTime.Parse(strArrays[1]); - if (Math.Abs((LicenseHelper.DataAtual - dateTime).TotalDays) > 1) - { - return "false"; - } - string str1 = EncryptionHelper.Decrypt(registryHelper.Read("NS", true)); - string str2 = registryHelper.Read("SERIALS", false); - if (string.IsNullOrWhiteSpace(str2) && !string.IsNullOrWhiteSpace(str1)) - { - registryHelper.Write("SERIALS", EncryptionHelper.Encrypt(str1), false); - str2 = registryHelper.Read("SERIALS", false); - } - strs = (str2 != null ? EncryptionHelper.Decrypt(str2).Split(new char[] { ':' }).ToList() : new List()); - List strs1 = new List(); - strs.Distinct().ToList().ForEach((string x) => { - if (registryHelper.Verificar(x, EncryptionHelper.Encrypt(x)) == "false") - { - return; - } - strs1.Add(x); - }); - strs1.Add(strArrays[0]); - registryHelper.Write("SERIALS", EncryptionHelper.Encrypt(string.Join(":", strs1.Distinct())), false); - registryHelper.set_Serial((strs1.Count > 1 ? string.Concat("\\", strArrays[0]) : "")); - ApplicationHelper.Subkey = (strs1.Count > 1 ? strArrays[0] : ""); - ApplicationHelper.NumeroSerial = strArrays[0]; - registryHelper.Write("PERFIL", Gestor.Application.Helpers.Connection.Get(string.Concat("Customer/Name/", strArrays[0]), true, false).Result, true); - registryHelper.Write("CURRENTDATE", EncryptionHelper.Encrypt(result), true); - registryHelper.Write("DATE", result, true); - registryHelper.Write("NS", EncryptionHelper.Encrypt(strArrays[0]), true); - registryHelper.Write("INSTALL", EncryptionHelper.Encrypt(strArrays[0]), true); - ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Maintenance/Customer", true, false).Result); - registryHelper.Write("CUSTOMER", EncryptionHelper.Encrypt(ApplicationHelper.IdFornecedor.ToString()), true); - Instancia.Conexao = null; - return "true"; - }); - return str3; - } - - public async Task RegistrarMaquina() - { - bool flag = await Task.Run(() => { - int quantidade; - string str; - if (!ApplicationHelper.Conectado) - { - return false; - } - List result = this.GetInstalacoes().Result; - Licenca licenca = LicenseHelper.Produtos.FirstOrDefault((Licenca x) => x.get_Produto() == 1); - quantidade = (licenca != null ? licenca.get_Quantidade() : 0); - if (quantidade <= result.Count((Gestor.Model.License.Instalacao x) => x.get_Gerenciador() != null)) - { - return false; - } - string str1 = ""; - RegistryHelper registryHelper = new RegistryHelper(""); - if (LicenseHelper.Instalacao == null) - { - string machineSerial = this.GetMachineSerial(); - str1 = EncryptionHelper.Encrypt(string.Concat(this.GetMacAddress(), " ", machineSerial)); - Gestor.Model.License.Instalacao instalacao = new Gestor.Model.License.Instalacao(); - instalacao.set_IdFornecedor(ApplicationHelper.IdFornecedor); - instalacao.set_Data(LicenseHelper.DataAtual); - instalacao.set_Gerenciador(machineSerial); - instalacao.set_NomeMaquina(Environment.MachineName); - instalacao.set_UsuarioMaquina(Environment.UserName); - instalacao.set_UsuarioId(Recursos.Usuario.get_Id()); - instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome()); - instalacao.set_UltimoAcesso(DateTime.Now); - Gestor.Model.License.Instalacao instalacao1 = instalacao; - IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); - if (pAddress != null) - { - str = pAddress.ToString(); - } - else - { - str = null; - } - instalacao1.set_Ip(str); - instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() })); - LicenseHelper.Instalacao = instalacao; - } - registryHelper.Write("MACHINEID", str1, false); - LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put("Installation/Machine", LicenseHelper.Instalacao).Result; - return true; - }); - return flag; - } - - public async Task> VerificarAcesso() - { - Tuple tuple = await Task.Run>(() => { - DateTime dateTime; - TimeSpan timeSpan; - DateTime liberacao; - RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); - DateTime networkTime = Funcoes.GetNetworkTime(); - DateTime date = networkTime.Date; - if (!ApplicationHelper.Conectado) - { - if ((date - LicenseHelper.DataAtual).TotalDays > 2) - { - return new Tuple(true, "DATA INVÁLIDA"); - } - dateTime = DateTime.Parse(EncryptionHelper.Decrypt(registryHelper.Read("EXPIRATION", true))); - timeSpan = dateTime.AddDays(5) - LicenseHelper.DataAtual; - LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays); - int? diasRestantes = LicenseHelper.DiasRestantes; - if (diasRestantes.GetValueOrDefault() < 1 & diasRestantes.HasValue) - { - return new Tuple(true, "SISTEMA BLOQUEADO"); - } - if (EncryptionHelper.Decrypt(registryHelper.Read("BLOCK", true)) == "TRUE") - { - return new Tuple(true, "SISTEMA BLOQUEADO"); - } - if (EncryptionHelper.Decrypt(registryHelper.Read("CONSULTA", true)) == "TRUE") - { - LicenseHelper.Status = 2; - } - string str = EncryptionHelper.Decrypt(registryHelper.Read("PRODUTOS", true)); - if (string.IsNullOrEmpty(str)) - { - LicenseHelper.Status = 3; - return new Tuple(false, "SISTEMA CANCELADO"); - } - LicenseHelper.Produtos = JsonConvert.DeserializeObject>(str); - LicenseHelper.Status = (LicenseHelper.Status != 2 ? 0 : LicenseHelper.Status); - return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); - } - List result = Gestor.Application.Helpers.Connection.Get>(string.Format("Access/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result; - List nums = new List() - { - (long)2, - (long)3, - (long)4, - (long)5, - (long)24, - (long)10024 - }; - LicenseHelper.Produtos = ( - from x in result - group x by new { ProductId = x.get_ProductId(), Status = x.get_Status() }).Select((x) => { - DateTime expiration; - Licenca licenca = new Licenca(); - licenca.set_Produto((int)x.Key.ProductId.GetValueOrDefault()); - var collection1 = x; - Func> u003cu003e9_2110 = LicenseHelper.u003cu003ec.u003cu003e9__21_10; - if (u003cu003e9_2110 == null) - { - u003cu003e9_2110 = (Access c) => c.get_Control(); - LicenseHelper.u003cu003ec.u003cu003e9__21_10 = u003cu003e9_2110; - } - IEnumerable accessControls1 = collection1.SelectMany(u003cu003e9_2110); - Func u003cu003e9_2111 = LicenseHelper.u003cu003ec.u003cu003e9__21_11; - if (u003cu003e9_2111 == null) - { - u003cu003e9_2111 = (AccessControl l) => l.get_Expiration(); - LicenseHelper.u003cu003ec.u003cu003e9__21_11 = u003cu003e9_2111; - } - AccessControl accessControl1 = accessControls1.OrderByDescending(u003cu003e9_2111).FirstOrDefault(); - expiration = (accessControl1 != null ? accessControl1.get_Expiration() : networkTime.AddDays(-1)); - licenca.set_Liberacao(expiration); - licenca.set_AcessoLiberado(x.All((Access l) => { - if (l.get_AgreementId().HasValue && nums.Contains(l.get_AgreementId().Value)) - { - return true; - } - var collection = x; - Func> u003cu003e9_2114 = LicenseHelper.u003cu003ec.u003cu003e9__21_14; - if (u003cu003e9_2114 == null) - { - u003cu003e9_2114 = (Access c) => c.get_Control(); - LicenseHelper.u003cu003ec.u003cu003e9__21_14 = u003cu003e9_2114; - } - IEnumerable accessControls = collection.SelectMany(u003cu003e9_2114); - Func u003cu003e9_2115 = LicenseHelper.u003cu003ec.u003cu003e9__21_15; - if (u003cu003e9_2115 == null) - { - u003cu003e9_2115 = (AccessControl d) => d.get_Expiration(); - LicenseHelper.u003cu003ec.u003cu003e9__21_15 = u003cu003e9_2115; - } - AccessControl accessControl = accessControls.OrderByDescending(u003cu003e9_2115).FirstOrDefault(); - if (accessControl == null) - { - return false; - } - return accessControl.get_Expiration() >= date; - })); - var collection2 = x; - Func u003cu003e9_2113 = LicenseHelper.u003cu003ec.u003cu003e9__21_13; - if (u003cu003e9_2113 == null) - { - u003cu003e9_2113 = (Access l) => l.get_Ammount().GetValueOrDefault(); - LicenseHelper.u003cu003ec.u003cu003e9__21_13 = u003cu003e9_2113; - } - licenca.set_Quantidade((int)collection2.Sum(u003cu003e9_2113)); - licenca.set_Status(int.Parse(x.Key.Status ?? "1")); - return licenca; - }).ToList(); - if (LicenseHelper.Produtos != null && LicenseHelper.Produtos.Count != 0) - { - if (!LicenseHelper.Produtos.All((Licenca x) => x.get_Status() == 3)) - { - Licenca licenca1 = ( - from x in LicenseHelper.Produtos - orderby x.get_Liberacao() - select x).FirstOrDefault((Licenca x) => { - if (x.get_AcessoLiberado()) - { - return false; - } - return x.get_Status() == 1; - }); - liberacao = (licenca1 != null ? licenca1.get_Liberacao() : networkTime); - DateTime dateTime1 = liberacao; - timeSpan = dateTime1 - date; - LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays); - registryHelper.Write("EXPIRATION", EncryptionHelper.Encrypt(dateTime1.ToString("d")), true); - registryHelper.Write("BLOCK", (dateTime1 >= date ? EncryptionHelper.Encrypt("FALSE") : EncryptionHelper.Encrypt("TRUE")), true); - bool flag = LicenseHelper.Produtos.Any((Licenca x) => { - if (x.get_Produto() != 1) - { - return false; - } - return x.get_Status() == 4; - }); - registryHelper.Write("CONSULTA", EncryptionHelper.Encrypt(flag.ToString().ToUpper()), true); - if (flag) - { - LicenseHelper.Status = 2; - } - LicenseHelper.Status = (dateTime1 < date ? 1 : 0); - if (LicenseHelper.Produtos.Any((Licenca x) => x.get_Produto() == 1) && LicenseHelper.Status == null) - { - registryHelper.Write("P1", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true); - registryHelper.Write("P5", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true); - registryHelper.Write("M1", EncryptionHelper.Encrypt("TRUE"), true); - } - IEnumerable produtos = - from x in LicenseHelper.Produtos - where x.get_Status() == 1 - select x; - JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); - jsonSerializerSetting.set_ReferenceLoopHandling(1); - registryHelper.Write("PRODUTOS", EncryptionHelper.Encrypt(JsonConvert.SerializeObject(produtos, 1, jsonSerializerSetting)), true); - if (LicenseHelper.Produtos.Find((Licenca p) => p.get_Produto() == 86) != null) - { - return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); - } - if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(AssinadorHelper.Key().Result)) - { - List licencas = LicenseHelper.Produtos; - Licenca licenca2 = new Licenca(); - licenca2.set_AcessoLiberado(true); - licenca2.set_Liberacao(date); - licenca2.set_Produto(86); - licenca2.set_Quantidade(0); - licenca2.set_Status(1); - licencas.Add(licenca2); - } - return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); - } - } - dateTime = networkTime.AddDays(-1); - registryHelper.Write("EXPIRATION", EncryptionHelper.Encrypt(dateTime.ToString("d")), true); - registryHelper.Write("BLOCK", EncryptionHelper.Encrypt("TRUE"), true); - LicenseHelper.Status = 3; - return new Tuple(false, ""); - }); - return tuple; - } - - public async Task VerificarMaquina() - { - bool flag = await Task.Run(() => { - Guid guid; - string str; - Gestor.Model.License.Instalacao instalacao; - string str1; - RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); - string macAddress = this.GetMacAddress(); - if (string.IsNullOrEmpty(registryHelper.Read("MACHINEID", false))) - { - registryHelper.Write("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", this.GetMachineSerial())), false); - } - string[] strArrays = EncryptionHelper.Decrypt(registryHelper.Read("MACHINEID", false)).Split(new char[] { ' ' }); - string machineSerial = ((int)strArrays.Length > 1 ? strArrays[1] : strArrays[0]); - if (ApplicationHelper.Conectado) - { - List result = Gestor.Application.Helpers.Connection.Get>(string.Concat("Installation/Machine/", machineSerial, "/GerenciadorList"), true, false).Result; - if (!Guid.TryParse(machineSerial, out guid)) - { - machineSerial = this.GetMachineSerial(); - } - this._guid = machineSerial; - if (result != null) - { - instalacao = result.FirstOrDefault((Gestor.Model.License.Instalacao x) => x.get_IdFornecedor() == ApplicationHelper.IdFornecedor); - } - else - { - instalacao = null; - } - LicenseHelper.Instalacao = instalacao; - if (LicenseHelper.Instalacao != null && LicenseHelper.Instalacao.get_IdFornecedor() != ApplicationHelper.IdFornecedor) - { - LicenseHelper.Instalacao = null; - } - if (LicenseHelper.Instalacao != null) - { - LicenseHelper.Instalacao.set_Gerenciador(machineSerial); - LicenseHelper.Instalacao.set_UsuarioId(Recursos.Usuario.get_Id()); - LicenseHelper.Instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome()); - Gestor.Model.License.Instalacao instalacao1 = LicenseHelper.Instalacao; - IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); - if (pAddress != null) - { - str1 = pAddress.ToString(); - } - else - { - str1 = null; - } - instalacao1.set_Ip(str1); - LicenseHelper.Instalacao.set_UltimoAcesso(DateTime.Now); - LicenseHelper.Instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() })); - LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put("Installation/Machine", LicenseHelper.Instalacao).Result; - registryHelper.Write("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", LicenseHelper.Instalacao.get_Gerenciador())), false); - } - registryHelper.Write("ACCESS", (LicenseHelper.Instalacao != null || this.RegistrarMaquina().Result ? EncryptionHelper.Encrypt("TRUE") : EncryptionHelper.Encrypt("FALSE")), false); - } - else if (EncryptionHelper.Decrypt(registryHelper.Read("ACCESS", false)) == "TRUE") - { - Gestor.Model.License.Instalacao instalacao2 = new Gestor.Model.License.Instalacao(); - instalacao2.set_IdFornecedor(ApplicationHelper.IdFornecedor); - instalacao2.set_Data(LicenseHelper.DataAtual); - instalacao2.set_Gerenciador(machineSerial); - instalacao2.set_NomeMaquina(Environment.MachineName); - instalacao2.set_UsuarioMaquina(Environment.UserName); - instalacao2.set_UsuarioId(Recursos.Usuario.get_Id()); - instalacao2.set_UsuarioSistema(Recursos.Usuario.get_Nome()); - instalacao2.set_UltimoAcesso(DateTime.Now); - IPAddress pAddress1 = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); - if (pAddress1 != null) - { - str = pAddress1.ToString(); - } - else - { - str = null; - } - instalacao2.set_Ip(str); - LicenseHelper.Instalacao = instalacao2; - } - if (!LicenseHelper.Produtos.Any((Licenca x) => x.get_Produto() == 1)) - { - return false; - } - if (LicenseHelper.Instalacao != null) - { - return true; - } - return this.RegistrarMaquina().Result; - }); - return flag; - } - - public async Task VerificarRegistro() - { - bool flag = await Task.Run(() => { - long idFornecedor; - RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); - if (string.IsNullOrEmpty(registryHelper.Read("NS", true))) - { - return false; - } - string str = EncryptionHelper.Decrypt(registryHelper.Read("CUSTOMER", true)); - if (long.TryParse(str, out idFornecedor)) - { - ApplicationHelper.IdFornecedor = long.Parse(str); - } - else - { - ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Configuration/Customer", true, false).Result); - idFornecedor = ApplicationHelper.IdFornecedor; - registryHelper.Write("CUSTOMER", EncryptionHelper.Encrypt(idFornecedor.ToString()), true); - } - string result = Gestor.Application.Helpers.Connection.Get("Installation/Time", false, false).Result ?? Funcoes.GetNetworkTime().ToString("d"); - LicenseHelper.DataAtual = DateTime.Parse(result); - registryHelper.Write("CURRENTDATE", EncryptionHelper.Encrypt(result), true); - registryHelper.Write("DATE", result, true); - List objs = Gestor.Application.Helpers.Connection.Get>(string.Format("Configuration/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result; - ApplicationHelper.Beta = (objs == null ? false : objs.Any((object x) => x.ToString().Contains("\"Tipo\": 45"))); - Address.set_Beta(ApplicationHelper.Beta); - return true; - }); - return flag; - } - - public async Task> VerificarVersao() - { - Tuple tuple = new Tuple(bool.Parse(await Gestor.Application.Helpers.Connection.Get(string.Format("Installation/Version/{0}", ApplicationHelper.IdFornecedor), true, false)), "VERSÃO INDISPONÍVEL"); - return tuple; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/MailHelper.cs b/Gestor.Application/Helpers/MailHelper.cs deleted file mode 100644 index e9f2cde..0000000 --- a/Gestor.Application/Helpers/MailHelper.cs +++ /dev/null @@ -1,745 +0,0 @@ -using CsQuery.ExtensionMethods.Internal; -using Gestor.Application.ViewModels; -using Gestor.Common.Helpers; -using Gestor.Common.Validation; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Infrastructure.UnitOfWork.Logic; -using Gestor.Model.Common; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.MalaDireta; -using Gestor.Model.Domain.Seguros; -using Gestor.Model.Helper; -using Google.Apis.Auth.OAuth2; -using Google.Apis.Gmail.v1; -using Google.Apis.Gmail.v1.Data; -using Google.Apis.Requests; -using Google.Apis.Services; -using Microsoft.Identity.Client; -using MimeKit; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Mail; -using System.Net.Mime; -using System.Net.Sockets; -using System.Runtime.CompilerServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; - -namespace Gestor.Application.Helpers -{ - public class MailHelper - { - public MailHelper() - { - } - - private static StringContent ConverteMailMessageParaStringContent(MailMessage message) - { - StringContent stringContent; - MimeMessage mimeMessage = (MimeMessage)message; - using (MemoryStream memoryStream = new MemoryStream()) - { - mimeMessage.WriteTo(memoryStream, new CancellationToken()); - memoryStream.Position = (long)0; - using (StreamReader streamReader = new StreamReader(memoryStream)) - { - string end = streamReader.ReadToEnd(); - stringContent = new StringContent(Convert.ToBase64String(Encoding.ASCII.GetBytes(end)), Encoding.UTF8, "text/plain"); - } - } - return stringContent; - } - - public static AlternateView CreateAlternateView(string mailBody) - { - int i; - List linkedResources = new List(); - string[] array = ( - from Match m in Regex.Matches(mailBody, "", RegexOptions.IgnoreCase) - select m.Groups[0].Value).ToArray(); - for (i = 0; i < (int)array.Length; i++) - { - string value = Regex.Match(array[i], "(?<=src=\")(.*?)(?=\")", RegexOptions.IgnoreCase).Value; - string str = Regex.Match(value, "file:(///).*\\.(.*)", RegexOptions.IgnoreCase).Groups[2].Value; - if (str == "jpg") - { - str = "jpeg"; - } - if (Uri.IsWellFormedUriString(value, UriKind.Absolute)) - { - Uri uri = new Uri(value); - if (File.Exists(uri.LocalPath)) - { - mailBody = mailBody.Replace(value, string.Concat("data:image/", str, ";base64,", Convert.ToBase64String(File.ReadAllBytes(uri.LocalPath)))); - } - } - } - array = ( - from Match m in Regex.Matches(mailBody, "", RegexOptions.IgnoreCase) - select m.Groups[0].Value).ToArray(); - for (i = 0; i < (int)array.Length; i++) - { - string str1 = array[i]; - string value1 = Regex.Match(str1, "(?<=src=\").*(?=\")", RegexOptions.IgnoreCase).Value; - string value2 = Regex.Match(value1, "(?<=data:).*(?=;)", RegexOptions.IgnoreCase).Value; - if (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(value2) || Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(value1)) - { - mailBody = mailBody.Replace(str1, string.Empty); - } - else - { - byte[] numArray = Convert.FromBase64String(Regex.Match(value1, "(?<=base64,)[^\"]*", RegexOptions.IgnoreCase).Value); - string str2 = Guid.NewGuid().ToString(); - linkedResources.Add(new LinkedResource(new MemoryStream(numArray), value2) - { - ContentId = str2, - TransferEncoding = TransferEncoding.Base64 - }); - string str3 = string.Concat("cid:", str2); - mailBody = mailBody.Replace(value1, str3); - } - } - AlternateView alternateView = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html"); - ExtensionMethods.AddRange(alternateView.LinkedResources, linkedResources); - return alternateView; - } - - public static string Encode(string text) - { - return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).Replace('+', '-').Replace('/', '\u005F').Replace("=", ""); - } - - public List Send(Credencial credencial, List destinatarios, TipoTela tela, long id) - { - List logEnvios1 = new List(); - int num = 100; - destinatarios.ForEach(async (Destinatario i) => { - if (num == 0) - { - num = 100; - await Task.Delay(1000); - } - List logEnvios = logEnvios1; - logEnvios.Add(await this.SendAsync(credencial, i, null, null, 0, false)); - logEnvios = null; - num--; - }); - return logEnvios1; - } - - public async Task SendAsync(Credencial credencial, Destinatario destinatario, FiltroArquivoDigital filtro = null, List maladireta = null, TipoTela tela = 0, bool confirmarLeitura = false) - { - TipoTela tipoTela = new TipoTela(); - IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); - LogEnvio logEnvio2 = await Task.Run(() => { - AuthenticationResult result; - List strs; - string str; - long id; - string str1; - string str2; - string str3; - string str4; - string str5; - string str6; - Action action2 = null; - Action action3 = null; - LogEnvio logEnvio = new LogEnvio(); - logEnvio.set_Credencial(credencial); - logEnvio.set_Destinatario(destinatario); - LogEnvio logEnvio1 = logEnvio; - AlternateView alternateView = MailHelper.CreateAlternateView(destinatario.get_Corpo()); - try - { - MailMessage mailMessage = new MailMessage() - { - From = new MailAddress(credencial.get_Email(), (string.IsNullOrWhiteSpace(credencial.get_Header()) ? Recursos.Empresa.get_Nome() : credencial.get_Header())), - BodyEncoding = Encoding.UTF8, - Subject = destinatario.get_Assunto() - }; - mailMessage.AlternateViews.Add(alternateView); - mailMessage.ReplyToList.Add(new MailAddress((string.IsNullOrWhiteSpace(credencial.get_Replyto()) ? credencial.get_Email() : credencial.get_Replyto()))); - mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; - mailMessage.IsBodyHtml = true; - MailMessage mailMessage1 = mailMessage; - if (confirmarLeitura) - { - mailMessage1.Headers.Add("Disposition-Notification-To", credencial.get_Email()); - } - destinatario.get_Email().Split(new char[] { ';' }).ToList().ForEach((string s) => { - if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s)) - { - return; - } - mailMessage1.To.Add(new MailAddress(s)); - }); - List strs1 = new List(); - List encaminharOculto = destinatario.get_EncaminharOculto(); - if (encaminharOculto != null) - { - encaminharOculto.ForEach((string x) => { - if (string.IsNullOrEmpty(x)) - { - return; - } - if (!x.Contains(";")) - { - if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(x)) - { - return; - } - strs1.Add(x); - return; - } - List list = x.Split(new char[] { ';' }).ToList(); - Action u003cu003e9_6 = action2; - if (u003cu003e9_6 == null) - { - Action action = (string s) => { - if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s)) - { - return; - } - strs1.Add(s); - }; - Action action1 = action; - action2 = action; - u003cu003e9_6 = action1; - } - list.ForEach(u003cu003e9_6); - }); - } - else - { - } - List encaminhar = destinatario.get_Encaminhar(); - if (encaminhar != null) - { - encaminhar.ForEach((string x) => { - if (string.IsNullOrEmpty(x)) - { - return; - } - if (!x.Contains(";")) - { - if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(x)) - { - return; - } - strs1.Add(x); - return; - } - List list = x.Split(new char[] { ';' }).ToList(); - Action u003cu003e9_7 = action3; - if (u003cu003e9_7 == null) - { - Action action = (string s) => { - if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s)) - { - return; - } - strs1.Add(s); - }; - Action action1 = action; - action3 = action; - u003cu003e9_7 = action1; - } - list.ForEach(u003cu003e9_7); - }); - } - else - { - } - strs1.ForEach((string x) => mailMessage1.Bcc.Add(new MailAddress(x))); - List anexos = destinatario.get_Anexos(); - if (anexos != null) - { - anexos.ForEach((Gestor.Model.Domain.Common.ArquivoDigital x) => { - Attachment attachment = new Attachment(new MemoryStream(x.get_Arquivo()), string.Concat(x.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(x.get_Extensao()))); - mailMessage1.Attachments.Add(attachment); - }); - } - else - { - } - if (credencial.get_Email().Contains("@gmail.com")) - { - credencial.set_Tipo(1); - } - TipoEmail tipo = credencial.get_Tipo(); - if (tipo == 1) - { - ClientSecrets clientSecret = new ClientSecrets(); - clientSecret.set_ClientId("378618252089-fm92uqgnk2jivf25mk2tv9s735n4nf6u.apps.googleusercontent.com"); - clientSecret.set_ClientSecret("kUiTfSuwZLLfteqwX7x6glsu"); - UserCredential userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecret, new string[] { GmailService.Scope.GmailSend }, credencial.get_Email(), CancellationToken.None, null, null).Result; - Google.Apis.Gmail.v1.Data.Message message = new Google.Apis.Gmail.v1.Data.Message(); - message.set_Raw(MailHelper.Encode(MimeMessage.CreateFromMailMessage(mailMessage1).ToString())); - Google.Apis.Gmail.v1.Data.Message message1 = message; - BaseClientService.Initializer initializer = new BaseClientService.Initializer(); - initializer.set_HttpClientInitializer(userCredential); - initializer.set_ApplicationName("AGGER GESTOR"); - UsersResource.MessagesResource.SendRequest sendRequest = (new GmailService(initializer)).get_Users().get_Messages().Send(message1, credencial.get_Email()); - logEnvio1.set_Enviado(false); - if (sendRequest.Execute().get_LabelIds().Contains("SENT")) - { - logEnvio1.set_Enviado(true); - } - } - else if (tipo == 2) - { - StringContent stringContent = new StringContent(""); - PublicClientApplicationBuilder publicClientApplicationBuilder = PublicClientApplicationBuilder.Create("8d1c32fe-4c17-4d5b-a21b-55b5529c3e12").WithDefaultRedirectUri(); - CacheOptions cacheOption = new CacheOptions(); - cacheOption.set_UseSharedCache(true); - IPublicClientApplication publicClientApplication = publicClientApplicationBuilder.WithCacheOptions(cacheOption).Build(); - string[] strArrays = new string[] { "user.read", "https://graph.microsoft.com/Mail.Send" }; - try - { - stringContent = MailHelper.ConverteMailMessageParaStringContent(mailMessage1); - IEnumerable accounts = publicClientApplication.GetAccountsAsync().Result; - result = (accounts == null || accounts.Count() == 0 ? publicClientApplication.AcquireTokenInteractive(strArrays).ExecuteAsync().Result : publicClientApplication.AcquireTokenSilent(strArrays, (accounts != null ? accounts.FirstOrDefault() : null)).ExecuteAsync().Result); - } - catch - { - result = publicClientApplication.AcquireTokenInteractive(strArrays).ExecuteAsync().Result; - } - using (HttpClient httpClient = new HttpClient()) - { - httpClient.get_DefaultRequestHeaders().Clear(); - httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Bearer ", (result != null ? result.get_AccessToken() : null))); - logEnvio1.set_Enviado(httpClient.PostAsync("https://graph.microsoft.com/v1.0/me/sendMail", stringContent).Result.get_IsSuccessStatusCode()); - } - } - else - { - NetworkCredential networkCredential = new NetworkCredential() - { - Password = EncryptionHelper.Decrypt(credencial.get_Senha()), - UserName = credencial.get_Usuario() ?? credencial.get_Email() - }; - SmtpClient smtpClient = new SmtpClient() - { - EnableSsl = credencial.get_Seguro(), - Host = credencial.get_Dominio(), - Port = credencial.get_Porta().GetValueOrDefault(587), - UseDefaultCredentials = false, - Credentials = networkCredential - }; - smtpClient.SendCompleted += new SendCompletedEventHandler((object sender, AsyncCompletedEventArgs args) => { - logEnvio1.set_Enviado((!args.Cancelled ? true : args.Error != null)); - if (args.Error != null) - { - logEnvio1.set_Erro(args.Error.ToString()); - } - }); - smtpClient.Send(mailMessage1); - logEnvio1.set_Enviado(true); - } - } - catch (Exception exception1) - { - Exception exception = exception1; - logEnvio1.set_Enviado(false); - logEnvio1.set_Erro((exception.InnerException == null ? exception.Message : string.Concat(exception.Message, " | ", exception.InnerException.Message))); - } - if (tela == 40) - { - return logEnvio1; - } - using (UnitOfWork commited = Instancia.Commited) - { - List strs2 = new List() - { - destinatario.get_Email() - }; - if (destinatario.get_Encaminhar() != null) - { - strs2.AddRange(destinatario.get_Encaminhar()); - } - List strs3 = new List(); - if (destinatario.get_EncaminharOculto() != null) - { - strs3.AddRange(destinatario.get_EncaminharOculto()); - } - List arquivoDigitals = destinatario.get_Anexos(); - if (arquivoDigitals != null) - { - Func u003cu003e9_09 = MailHelper.u003cu003ec.u003cu003e9__0_9; - if (u003cu003e9_09 == null) - { - u003cu003e9_09 = (Gestor.Model.Domain.Common.ArquivoDigital x) => string.Concat(x.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(x.get_Extensao())); - MailHelper.u003cu003ec.u003cu003e9__0_9 = u003cu003e9_09; - } - strs = arquivoDigitals.Select(u003cu003e9_09).ToList(); - } - else - { - strs = null; - } - List strs4 = strs; - DateTime networkTime = Funcoes.GetNetworkTime(); - if (filtro != null) - { - switch (filtro.get_Tipo()) - { - case 1: - { - tipoTela = 1; - break; - } - case 2: - { - tipoTela = 2; - break; - } - case 3: - { - tipoTela = 5; - break; - } - case 4: - { - tipoTela = 3; - break; - } - case 5: - { - tipoTela = 7; - break; - } - case 6: - { - tipoTela = 15; - break; - } - case 7: - { - tipoTela = 23; - break; - } - case 8: - { - tipoTela = 13; - break; - } - case 9: - { - tipoTela = 25; - break; - } - case 10: - { - tipoTela = 24; - break; - } - case 11: - { - tipoTela = 33; - break; - } - case 12: - { - tipoTela = 16; - break; - } - case 13: - { - tipoTela = 18; - break; - } - default: - { - tipoTela = 0; - break; - } - } - if (strs4 != null && logEnvio1.get_Enviado()) - { - LogEmail logEmail = new LogEmail(); - logEmail.set_Credencial(credencial); - logEmail.set_EntityId(filtro.get_Id()); - logEmail.set_Usuario(Recursos.Usuario); - logEmail.set_Data(networkTime); - logEmail.set_Tela(tipoTela); - logEmail.set_Destinatarios(string.Join(";", strs2)); - logEmail.set_Cco(string.Join(";", strs3)); - logEmail.set_Assunto(destinatario.get_Assunto()); - logEmail.set_Corpo(destinatario.get_Corpo()); - logEmail.set_Anexos(string.Join(";", strs4)); - logEmail.set_Versao(LoginViewModel.VersaoAtual); - logEmail.set_NomeMaquina(Environment.MachineName); - logEmail.set_UsuarioMaquina(Environment.UserName); - IPAddress[] addressList = hostEntry.AddressList; - Func u003cu003e9_010 = MailHelper.u003cu003ec.u003cu003e9__0_10; - if (u003cu003e9_010 == null) - { - u003cu003e9_010 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_10 = u003cu003e9_010; - } - IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault(u003cu003e9_010); - if (pAddress != null) - { - str6 = pAddress.ToString(); - } - else - { - str6 = null; - } - logEmail.set_Ip(str6); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail); - } - commited.Commit(); - } - else if (maladireta == null) - { - if (strs4 != null) - { - LogEmail logEmail1 = new LogEmail(); - logEmail1.set_Credencial(credencial); - logEmail1.set_Usuario(Recursos.Usuario); - logEmail1.set_Data(networkTime); - logEmail1.set_Tela(tela); - logEmail1.set_Destinatarios(string.Join(";", strs2)); - logEmail1.set_Cco(string.Join(";", strs3)); - logEmail1.set_Assunto(destinatario.get_Assunto()); - logEmail1.set_Corpo(destinatario.get_Corpo()); - logEmail1.set_Anexos(string.Join(";", strs4)); - logEmail1.set_Versao(LoginViewModel.VersaoAtual); - logEmail1.set_NomeMaquina(Environment.MachineName); - logEmail1.set_UsuarioMaquina(Environment.UserName); - IPAddress[] pAddressArray = hostEntry.AddressList; - Func u003cu003e9_016 = MailHelper.u003cu003ec.u003cu003e9__0_16; - if (u003cu003e9_016 == null) - { - u003cu003e9_016 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_16 = u003cu003e9_016; - } - IPAddress pAddress1 = ((IEnumerable)pAddressArray).FirstOrDefault(u003cu003e9_016); - if (pAddress1 != null) - { - str = pAddress1.ToString(); - } - else - { - str = null; - } - logEmail1.set_Ip(str); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail1); - } - commited.Commit(); - } - else - { - foreach (MalaDireta maladiretum in maladireta) - { - if (maladiretum.get_Tela() == 1) - { - LogEmail logEmail2 = new LogEmail(); - logEmail2.set_Credencial(credencial); - logEmail2.set_Usuario(Recursos.Usuario); - logEmail2.set_EntityId(maladiretum.get_Cliente().get_Id()); - logEmail2.set_Data(networkTime); - logEmail2.set_Tela(maladiretum.get_Tela()); - logEmail2.set_Destinatarios(string.Join(";", strs2)); - logEmail2.set_Cco(string.Join(";", strs3)); - logEmail2.set_Assunto(destinatario.get_Assunto()); - logEmail2.set_Corpo(destinatario.get_Corpo()); - logEmail2.set_Anexos(string.Join(";", strs4)); - logEmail2.set_Versao(LoginViewModel.VersaoAtual); - logEmail2.set_NomeMaquina(Environment.MachineName); - logEmail2.set_UsuarioMaquina(Environment.UserName); - IPAddress[] addressList1 = hostEntry.AddressList; - Func u003cu003e9_011 = MailHelper.u003cu003ec.u003cu003e9__0_11; - if (u003cu003e9_011 == null) - { - u003cu003e9_011 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_11 = u003cu003e9_011; - } - IPAddress pAddress2 = ((IEnumerable)addressList1).FirstOrDefault(u003cu003e9_011); - if (pAddress2 != null) - { - str5 = pAddress2.ToString(); - } - else - { - str5 = null; - } - logEmail2.set_Ip(str5); - logEmail2.set_Relatorio(maladiretum.get_Relatorio()); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail2); - } - else if (maladiretum.get_Tela() == 2) - { - LogEmail logEmail3 = new LogEmail(); - logEmail3.set_Credencial(credencial); - logEmail3.set_Usuario(Recursos.Usuario); - logEmail3.set_EntityId(maladiretum.get_Apolice().get_Id()); - logEmail3.set_Data(networkTime); - logEmail3.set_Tela(maladiretum.get_Tela()); - logEmail3.set_Destinatarios(string.Join(";", strs2)); - logEmail3.set_Cco(string.Join(";", strs3)); - logEmail3.set_Assunto(destinatario.get_Assunto()); - logEmail3.set_Corpo(destinatario.get_Corpo()); - logEmail3.set_Anexos(string.Join(";", strs4)); - logEmail3.set_Versao(LoginViewModel.VersaoAtual); - logEmail3.set_NomeMaquina(Environment.MachineName); - logEmail3.set_UsuarioMaquina(Environment.UserName); - IPAddress[] pAddressArray1 = hostEntry.AddressList; - Func u003cu003e9_012 = MailHelper.u003cu003ec.u003cu003e9__0_12; - if (u003cu003e9_012 == null) - { - u003cu003e9_012 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_12 = u003cu003e9_012; - } - IPAddress pAddress3 = ((IEnumerable)pAddressArray1).FirstOrDefault(u003cu003e9_012); - if (pAddress3 != null) - { - str4 = pAddress3.ToString(); - } - else - { - str4 = null; - } - logEmail3.set_Ip(str4); - logEmail3.set_Relatorio(maladiretum.get_Relatorio()); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail3); - } - else if (maladiretum.get_Tela() == 5) - { - LogEmail logEmail4 = new LogEmail(); - logEmail4.set_Credencial(credencial); - logEmail4.set_Usuario(Recursos.Usuario); - logEmail4.set_EntityId(maladiretum.get_Parcela().get_Id()); - logEmail4.set_Data(networkTime); - logEmail4.set_Tela(maladiretum.get_Tela()); - logEmail4.set_Destinatarios(string.Join(";", strs2)); - logEmail4.set_Cco(string.Join(";", strs3)); - logEmail4.set_Assunto(destinatario.get_Assunto()); - logEmail4.set_Corpo(destinatario.get_Corpo()); - logEmail4.set_Anexos(string.Join(";", strs4)); - logEmail4.set_Versao(LoginViewModel.VersaoAtual); - logEmail4.set_NomeMaquina(Environment.MachineName); - logEmail4.set_UsuarioMaquina(Environment.UserName); - IPAddress[] addressList2 = hostEntry.AddressList; - Func u003cu003e9_013 = MailHelper.u003cu003ec.u003cu003e9__0_13; - if (u003cu003e9_013 == null) - { - u003cu003e9_013 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_13 = u003cu003e9_013; - } - IPAddress pAddress4 = ((IEnumerable)addressList2).FirstOrDefault(u003cu003e9_013); - if (pAddress4 != null) - { - str3 = pAddress4.ToString(); - } - else - { - str3 = null; - } - logEmail4.set_Ip(str3); - logEmail4.set_Relatorio(maladiretum.get_Relatorio()); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail4); - } - else if (maladiretum.get_Tela() != 7) - { - if (maladiretum.get_Tela() != null) - { - continue; - } - LogEmail logEmail5 = new LogEmail(); - logEmail5.set_Credencial(credencial); - logEmail5.set_Usuario(Recursos.Usuario); - Documento apolice = maladiretum.get_Apolice(); - id = (apolice != null ? apolice.get_Id() : (long)0); - logEmail5.set_EntityId(id); - logEmail5.set_Data(networkTime); - logEmail5.set_Tela(2); - logEmail5.set_Destinatarios(string.Join(";", strs2)); - logEmail5.set_Cco(string.Join(";", strs3)); - logEmail5.set_Assunto(destinatario.get_Assunto()); - logEmail5.set_Corpo(destinatario.get_Corpo()); - logEmail5.set_Anexos(string.Join(";", strs4)); - logEmail5.set_Versao(LoginViewModel.VersaoAtual); - logEmail5.set_NomeMaquina(Environment.MachineName); - logEmail5.set_UsuarioMaquina(Environment.UserName); - IPAddress[] pAddressArray2 = hostEntry.AddressList; - Func u003cu003e9_015 = MailHelper.u003cu003ec.u003cu003e9__0_15; - if (u003cu003e9_015 == null) - { - u003cu003e9_015 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_15 = u003cu003e9_015; - } - IPAddress pAddress5 = ((IEnumerable)pAddressArray2).FirstOrDefault(u003cu003e9_015); - if (pAddress5 != null) - { - str1 = pAddress5.ToString(); - } - else - { - str1 = null; - } - logEmail5.set_Ip(str1); - logEmail5.set_Relatorio(maladiretum.get_Relatorio()); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail5); - } - else - { - LogEmail logEmail6 = new LogEmail(); - logEmail6.set_Credencial(credencial); - logEmail6.set_Usuario(Recursos.Usuario); - logEmail6.set_EntityId(maladiretum.get_Sinistro().get_Id()); - logEmail6.set_Data(networkTime); - logEmail6.set_Tela(maladiretum.get_Tela()); - logEmail6.set_Destinatarios(string.Join(";", strs2)); - logEmail6.set_Cco(string.Join(";", strs3)); - logEmail6.set_Assunto(destinatario.get_Assunto()); - logEmail6.set_Corpo(destinatario.get_Corpo()); - logEmail6.set_Anexos(string.Join(";", strs4)); - logEmail6.set_Versao(LoginViewModel.VersaoAtual); - logEmail6.set_NomeMaquina(Environment.MachineName); - logEmail6.set_UsuarioMaquina(Environment.UserName); - IPAddress[] addressList3 = hostEntry.AddressList; - Func u003cu003e9_014 = MailHelper.u003cu003ec.u003cu003e9__0_14; - if (u003cu003e9_014 == null) - { - u003cu003e9_014 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork; - MailHelper.u003cu003ec.u003cu003e9__0_14 = u003cu003e9_014; - } - IPAddress pAddress6 = ((IEnumerable)addressList3).FirstOrDefault(u003cu003e9_014); - if (pAddress6 != null) - { - str2 = pAddress6.ToString(); - } - else - { - str2 = null; - } - logEmail6.set_Ip(str2); - logEmail6.set_Relatorio(maladiretum.get_Relatorio()); - commited.get_RegistroLogRepository().SaveOrUpdate(logEmail6); - } - } - commited.Commit(); - } - } - return logEnvio1; - }); - return logEnvio2; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs b/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs deleted file mode 100644 index 955e38b..0000000 --- a/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public static class NotifyPropertyChangedExtension - { - public static void MutateVerbose(this INotifyPropertyChanged instance, ref TField field, TField newValue, Action raise, [CallerMemberName] string propertyName = null) - { - if (EqualityComparer.Default.Equals(field, newValue)) - { - return; - } - field = newValue; - if (raise != null) - { - raise(new PropertyChangedEventArgs(propertyName)); - } - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/ObrigatorioValidationRule.cs b/Gestor.Application/Helpers/ObrigatorioValidationRule.cs deleted file mode 100644 index ff5dc58..0000000 --- a/Gestor.Application/Helpers/ObrigatorioValidationRule.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Windows.Controls; - -namespace Gestor.Application.Helpers -{ - public class ObrigatorioValidationRule : ValidationRule - { - public bool IsRequired - { - get; - set; - } - - public ObrigatorioValidationRule() - { - } - - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - string str = value as string; - if (str == null) - { - return new ValidationResult(false, "OBRIGATÓRIO"); - } - if (str == null || !this.IsRequired || !string.IsNullOrWhiteSpace(str)) - { - return ValidationResult.ValidResult; - } - return new ValidationResult(false, "OBRIGATÓRIO"); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/PasswordBoxAssistant.cs b/Gestor.Application/Helpers/PasswordBoxAssistant.cs deleted file mode 100644 index 8944bc7..0000000 --- a/Gestor.Application/Helpers/PasswordBoxAssistant.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Controls; - -namespace Gestor.Application.Helpers -{ - public static class PasswordBoxAssistant - { - public readonly static DependencyProperty BoundPassword; - - public readonly static DependencyProperty BindPassword; - - private readonly static DependencyProperty UpdatingPassword; - - static PasswordBoxAssistant() - { - PasswordBoxAssistant.BoundPassword = DependencyProperty.RegisterAttached("BoundPassword", typeof(string), typeof(PasswordBoxAssistant), new PropertyMetadata(string.Empty, new PropertyChangedCallback(PasswordBoxAssistant.OnBoundPasswordChanged))); - PasswordBoxAssistant.BindPassword = DependencyProperty.RegisterAttached("BindPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false, new PropertyChangedCallback(PasswordBoxAssistant.OnBindPasswordChanged))); - PasswordBoxAssistant.UpdatingPassword = DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false)); - } - - public static bool GetBindPassword(DependencyObject dp) - { - return (bool)dp.GetValue(PasswordBoxAssistant.BindPassword); - } - - public static string GetBoundPassword(DependencyObject dp) - { - return (string)dp.GetValue(PasswordBoxAssistant.BoundPassword); - } - - private static bool GetUpdatingPassword(DependencyObject dp) - { - return (bool)dp.GetValue(PasswordBoxAssistant.UpdatingPassword); - } - - private static void HandlePasswordChanged(object sender, RoutedEventArgs e) - { - PasswordBox passwordBox = sender as PasswordBox; - PasswordBoxAssistant.SetUpdatingPassword(passwordBox, true); - PasswordBoxAssistant.SetBoundPassword(passwordBox, passwordBox.Password); - PasswordBoxAssistant.SetUpdatingPassword(passwordBox, false); - } - - private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e) - { - PasswordBox passwordBox = dp as PasswordBox; - if (passwordBox == null) - { - return; - } - bool oldValue = (bool)e.OldValue; - bool newValue = (bool)e.NewValue; - if (oldValue) - { - passwordBox.PasswordChanged -= new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); - } - if (newValue) - { - passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); - } - } - - private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - PasswordBox passwordBox = d as PasswordBox; - if (d == null || !PasswordBoxAssistant.GetBindPassword(d)) - { - return; - } - passwordBox.PasswordChanged -= new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); - string newValue = (string)e.NewValue; - if (!PasswordBoxAssistant.GetUpdatingPassword(passwordBox)) - { - passwordBox.Password = newValue; - } - passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged); - } - - public static void SetBindPassword(DependencyObject dp, bool value) - { - dp.SetValue(PasswordBoxAssistant.BindPassword, value); - } - - public static void SetBoundPassword(DependencyObject dp, string value) - { - dp.SetValue(PasswordBoxAssistant.BoundPassword, value); - } - - private static void SetUpdatingPassword(DependencyObject dp, bool value) - { - dp.SetValue(PasswordBoxAssistant.UpdatingPassword, value); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/PipeClient.cs b/Gestor.Application/Helpers/PipeClient.cs deleted file mode 100644 index 5e8d841..0000000 --- a/Gestor.Application/Helpers/PipeClient.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.IO; -using System.IO.Pipes; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public class PipeClient - { - private string _pipeName; - - private NamedPipeClientStream Pipe - { - get; - set; - } - - public PipeClient(string pipeName) - { - this._pipeName = pipeName; - } - - public bool Send(dynamic message) - { - bool flag; - try - { - this.Pipe = new NamedPipeClientStream(".", this._pipeName, PipeDirection.Out, PipeOptions.Asynchronous); - this.Pipe.Connect(1000); - if (this.Pipe.IsConnected) - { - using (StreamWriter streamWriter = new StreamWriter(this.Pipe)) - { - streamWriter.AutoFlush = true; - streamWriter.WriteLine(JsonConvert.SerializeObject(message)); - this.Pipe.WaitForPipeDrain(); - } - return true; - } - else - { - flag = false; - } - } - catch (TimeoutException timeoutException) - { - flag = false; - } - return flag; - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/PipeServer.cs b/Gestor.Application/Helpers/PipeServer.cs deleted file mode 100644 index fa42e03..0000000 --- a/Gestor.Application/Helpers/PipeServer.cs +++ /dev/null @@ -1,115 +0,0 @@ -using Assinador.Model.Common; -using Gestor.Application.Actions; -using Newtonsoft.Json; -using System; -using System.IO; -using System.IO.Pipes; -using System.Runtime.CompilerServices; -using System.Security.AccessControl; -using System.Security.Principal; - -namespace Gestor.Application.Helpers -{ - public class PipeServer : IDisposable - { - private string _pipeName; - - private NamedPipeServerStream Pipe - { - get; - set; - } - - public PipeServer() - { - } - - private bool Create() - { - bool flag; - bool flag1 = true; - try - { - (new NamedPipeClientStream(".", this._pipeName, PipeDirection.Out, PipeOptions.Asynchronous)).Connect(1000); - } - catch (TimeoutException timeoutException) - { - flag1 = false; - } - catch (Exception exception) - { - flag = false; - return flag; - } - if (flag1) - { - return true; - } - try - { - PipeSecurity pipeSecurity = new PipeSecurity(); - SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); - securityIdentifier.Translate(typeof(NTAccount)); - pipeSecurity.SetAccessRule(new PipeAccessRule(securityIdentifier, PipeAccessRights.ReadWrite, AccessControlType.Allow)); - this.Pipe = new NamedPipeServerStream(this._pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, pipeSecurity); - this.Pipe.BeginWaitForConnection(new AsyncCallback(this.WaitForConnectionCallBack), this.Pipe); - return true; - } - catch (Exception exception1) - { - flag = false; - } - return flag; - } - - public bool CreateServer(string name) - { - this._pipeName = name; - return this.Create(); - } - - public void Dispose() - { - this.Pipe.Dispose(); - } - - private void Handle(string message) - { - if (message == null) - { - return; - } - PipeMessageResult pipeMessageResult = JsonConvert.DeserializeObject(message); - Action acessarHoster = Gestor.Application.Actions.Actions.AcessarHoster; - if (acessarHoster == null) - { - return; - } - acessarHoster(pipeMessageResult); - } - - private void WaitForConnectionCallBack(IAsyncResult iar) - { - try - { - NamedPipeServerStream asyncState = (NamedPipeServerStream)iar.AsyncState; - asyncState.EndWaitForConnection(iar); - using (StreamReader streamReader = new StreamReader(this.Pipe)) - { - string str = streamReader.ReadLine(); - if ((str == null ? false : str.IndexOf("exit", StringComparison.InvariantCultureIgnoreCase) > -1)) - { - this.Dispose(); - } - this.Handle(str); - } - asyncState.Close(); - asyncState = null; - this.Create(); - } - catch - { - } - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/QueryableHelper.cs b/Gestor.Application/Helpers/QueryableHelper.cs deleted file mode 100644 index 5670bf2..0000000 --- a/Gestor.Application/Helpers/QueryableHelper.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public static class QueryableHelper - { - public static IOrderedQueryable OrderBy(this IQueryable source, string propertyName) - { - return source.OrderBy(QueryableHelper.ToLambda(propertyName)); - } - - public static IOrderedQueryable OrderByDescending(this IQueryable source, string propertyName) - { - return source.OrderByDescending(QueryableHelper.ToLambda(propertyName)); - } - - private static Expression> ToLambda(string propertyName) - { - ParameterExpression parameterExpression = Expression.Parameter(typeof(T)); - return Expression.Lambda>(Expression.Convert(Expression.Property(parameterExpression, propertyName), typeof(object)), new ParameterExpression[] { parameterExpression }); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/Recursos.cs b/Gestor.Application/Helpers/Recursos.cs deleted file mode 100644 index 8800d53..0000000 --- a/Gestor.Application/Helpers/Recursos.cs +++ /dev/null @@ -1,170 +0,0 @@ -using Agger.Registro; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Configuracoes; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Financeiro; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Net; -using System.Runtime.CompilerServices; - -namespace Gestor.Application.Helpers -{ - public static class Recursos - { - public const string AppStore = "https://apps.apple.com/br/app/agger-mobile/id1463091598"; - - public const string PlayStore = "https://play.google.com/store/apps/details?id=br.com.aggermobile&hl=pt&gl=US"; - - public const int DefaultMaxSize = 14336; - - public static Uri ApiArquivo - { - get; - } - - public static List BancosContas - { - get; - set; - } - - public static List Coberturas - { - get; - set; - } - - public static List Configuracoes - { - get; - set; - } - - public static List Descricao - { - get; - set; - } - - public static Gestor.Model.Domain.Common.Empresa Empresa - { - get; - set; - } - - public static List Empresas - { - get; - set; - } - - public static List Estipulantes - { - get; - set; - } - - public static List Fabricantes - { - get; - set; - } - - public static IPHostEntry Host - { - get; - set; - } - - public static List Parametros - { - get; - set; - } - - public static List Parceiros - { - get; - set; - } - - public static List Produtos - { - get; - set; - } - - public static List Ramos - { - get; - set; - } - - public static string Registrar - { - get; - set; - } - - public static List Seguradoras - { - get; - set; - } - - public static List Status - { - get; - set; - } - - public static List StatusProspeccao - { - get; - set; - } - - public static List TiposTarefa - { - get; - set; - } - - public static List TipoVendedor - { - get; - set; - } - - public static Gestor.Model.Domain.Seguros.Usuario Usuario - { - get; - set; - } - - public static List Usuarios - { - get; - set; - } - - public static List Vendedores - { - get; - set; - } - - public static Uri WhatsAppLink - { - get; - } - - static Recursos() - { - Recursos.WhatsAppLink = new Uri("https://api.whatsapp.com/send?"); - Recursos.ApiArquivo = Address.get_ApiArquivo(); - } - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/TipoToggle.cs b/Gestor.Application/Helpers/TipoToggle.cs deleted file mode 100644 index 294a15d..0000000 --- a/Gestor.Application/Helpers/TipoToggle.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Gestor.Application.Helpers -{ - [Flags] - public enum TipoToggle - { - None = 0, - Consultar = 1, - Incluir = 2, - Alterar = 4, - Excluir = 8 - } -} \ No newline at end of file diff --git a/Gestor.Application/Helpers/ViewHelper.cs b/Gestor.Application/Helpers/ViewHelper.cs deleted file mode 100644 index 9c17374..0000000 --- a/Gestor.Application/Helpers/ViewHelper.cs +++ /dev/null @@ -1,462 +0,0 @@ -using CurrencyTextBoxControl; -using Gestor.Application.Componentes; -using Gestor.Model.Helper; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Dynamic; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Data; -using System.Windows.Media; -using Xceed.Wpf.Toolkit; -using Xceed.Wpf.Toolkit.Primitives; - -namespace Gestor.Application.Helpers -{ - public static class ViewHelper - { - internal static void BindData(this CheckComboBox comboBox, bool withSelect = true, bool enumDefault = true, string defaultValue = "", bool orderByLabel = false) - { - ViewHelper.DefaultBinding(comboBox, withSelect, enumDefault, defaultValue, string.Empty, orderByLabel); - } - - public static void ClearInvalid(this DependencyObject dependencyObject) - { - foreach (Control control in ViewHelper.FindChildren(dependencyObject)) - { - control.SetInvalid(null, null); - } - } - - private static bool Compare(Control currentControl) - { - object resolvedSource; - DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(currentControl); - if (dependencyProperty == null) - { - return false; - } - BindingExpression bindingExpression = currentControl.GetBindingExpression(dependencyProperty); - if (bindingExpression != null) - { - resolvedSource = bindingExpression.ResolvedSource; - } - else - { - resolvedSource = null; - } - dynamic obj = resolvedSource; - dynamic obj1 = obj != (dynamic)null; - return (bool)((!obj1 ? obj1 : obj1 & (bool)obj.HasChange())); - } - - public static void ControlLostFocus(object sender, RoutedEventArgs e) - { - dynamic obj; - Control control; - Control control1 = null; - if (sender is CustomItemValidation) - { - control1 = ViewHelper.FindChildren(sender as CustomItemValidation).FirstOrDefault((Control currentControl) => { - if (currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox || currentControl is Button) - { - return true; - } - return currentControl is CustomPasswordBox; - }); - } - if (sender is CustomIsReadOnlyControl) - { - CustomIsReadOnlyControl customIsReadOnlyControl = sender as CustomIsReadOnlyControl; - if (!customIsReadOnlyControl.HasValidation) - { - control = null; - } - else - { - control = ViewHelper.FindChildren(customIsReadOnlyControl).LastOrDefault((Control currentControl) => { - if (currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox) - { - return true; - } - return currentControl is Button; - }); - } - control1 = control; - } - if (control1 == null) - { - return; - } - ComboBox comboBox = control1 as ComboBox; - if (comboBox != null && comboBox.IsDropDownOpen) - { - return; - } - if (control1 is TextBox && ((TextBox)control1).IsReadOnly) - { - return; - } - DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(control1); - if (dependencyProperty == null) - { - return; - } - BindingExpression bindingExpression = control1.GetBindingExpression(dependencyProperty); - if (bindingExpression == null) - { - return; - } - Validation.ClearInvalid(bindingExpression); - List list = bindingExpression.ParentBinding.Path.Path.Split(new char[] { '.' }).ToList(); - Type type = bindingExpression.DataItem.GetType(); - if (!list.Any()) - { - return; - } - PropertyInfo property = type.GetProperty(list.First()); - if (property == null) - { - return; - } - dynamic value = property.GetValue(bindingExpression.DataItem, null); - List> keyValuePairs = new List>(); - if ((dynamic)(!ViewHelper.HasMethod(value, "ValidationEvent"))) - { - dynamic resolvedSource = bindingExpression.ResolvedSource; - if (resolvedSource is Control) - { - return; - } - if ((dynamic)(!ViewHelper.HasMethod(resolvedSource, "ValidationEvent"))) - { - return; - } - obj = resolvedSource; - if ((obj != null ? obj.ValidationEvent : null) == (dynamic)null) - { - return; - } - Func>> func = resolvedSource.ValidationEvent as Func>>; - if (func != null) - { - keyValuePairs = func(); - } - if (keyValuePairs.Count == 0) - { - return; - } - } - if (keyValuePairs.Count == 0) - { - obj = value; - if ((obj != null ? obj.ValidationEvent : null) == (dynamic)null) - { - return; - } - Func>> func1 = value.ValidationEvent as Func>>; - if (func1 != null) - { - keyValuePairs = func1(); - } - } - if (keyValuePairs == null || !keyValuePairs.Any>()) - { - return; - } - string str = (list.Last() == "Id" ? list[list.Count - 2] : list.Last()); - string valueExact = ValidationHelper.GetValueExact(keyValuePairs, str); - if (string.IsNullOrEmpty(valueExact)) - { - valueExact = ValidationHelper.GetValueExact(keyValuePairs, str); - if (string.IsNullOrEmpty(valueExact)) - { - return; - } - } - Validation.MarkInvalid(bindingExpression, new ValidationError(new ExceptionValidationRule(), bindingExpression) - { - ErrorContent = valueExact - }); - } - - private static void DefaultBinding(CheckComboBox comboBox, bool withSelect, bool enumDefault, string defaultValue = "", string defaultText = "", bool orderByLabel = false) - { - List> keyValuePairs = BindingHelper.BindingData(withSelect, enumDefault, defaultValue, defaultText, orderByLabel, false, false); - comboBox.ItemsSource = keyValuePairs; - comboBox.set_ValueMemberPath("Key"); - comboBox.DisplayMemberPath = "Value"; - comboBox.set_SelectedItem(keyValuePairs.First>()); - } - - public static IEnumerable FindAncestor(DependencyObject dependencyObject) - where T : DependencyObject - { - for (DependencyObject i = VisualTreeHelper.GetParent(dependencyObject); i != null; i = VisualTreeHelper.GetParent(i)) - { - T t = (T)(i as T); - if (t != null) - { - yield return t; - } - } - } - - public static IEnumerable FindChildren(DependencyObject depObj) - where T : DependencyObject - { - if (depObj != null) - { - IEnumerator enumerator = LogicalTreeHelper.GetChildren(depObj).GetEnumerator(); - while (enumerator.MoveNext()) - { - object current = enumerator.Current; - T t = (T)(current as T); - if (t != null) - { - ContentControl contentControl = (object)t as ContentControl; - if (contentControl == null || (object)t as UserControl != null) - { - yield return t; - } - } - foreach (T t1 in ViewHelper.FindChildren(current as DependencyObject)) - { - yield return t1; - } - current = null; - } - enumerator = null; - } - else - { - } - } - - public static IEnumerable FindParent(DependencyObject depObj) - where T : DependencyObject - { - if (depObj != null) - { - DependencyObject parent = LogicalTreeHelper.GetParent(depObj); - T t = (T)(parent as T); - if (t != null) - { - yield return t; - } - foreach (T t1 in ViewHelper.FindParent(parent)) - { - yield return t1; - } - } - else - { - } - } - - private static DependencyProperty GetDependencyProperty(Control currentControl) - { - DependencyProperty selectedValueProperty = null; - if (currentControl is CheckComboBox) - { - selectedValueProperty = Xceed.Wpf.Toolkit.Primitives.Selector.SelectedValueProperty; - } - if (currentControl is DatePicker) - { - selectedValueProperty = DatePicker.SelectedDateProperty; - } - if (currentControl is AutoCompleteBox) - { - selectedValueProperty = AutoCompleteBox.SelectedItemProperty; - } - if (currentControl is TextBox) - { - selectedValueProperty = TextBox.TextProperty; - } - if (currentControl is MaskedTextBox) - { - selectedValueProperty = TextBox.TextProperty; - } - if (currentControl is ComboBox) - { - selectedValueProperty = System.Windows.Controls.Primitives.Selector.SelectedValueProperty; - } - if (currentControl is CurrencyTextBox) - { - selectedValueProperty = CurrencyTextBox.NumberProperty; - } - if (currentControl is ToggleButton) - { - selectedValueProperty = ToggleButton.IsCheckedProperty; - } - if (currentControl is CustomPasswordBox) - { - selectedValueProperty = CustomPasswordBox.TextProperty; - } - return selectedValueProperty; - } - - public static bool HasMethod(object objectToCheck, string methodName) - { - if (objectToCheck == null) - { - return false; - } - return objectToCheck.GetType().GetProperty(methodName) != null; - } - - public static bool IsPropertyExist(dynamic settings, string name) - { - if (settings is ExpandoObject) - { - return ((IDictionary)settings).ContainsKey(name); - } - return (bool)(settings.GetType().GetProperty(name) != (dynamic)null); - } - - public static bool IsValid(this DependencyObject obj) - { - if (Validation.GetHasError(obj)) - { - return false; - } - return LogicalTreeHelper.GetChildren(obj).OfType().All(new Func(ViewHelper.IsValid)); - } - - public static bool IsWindowOpen(string name = "") - where T : Window - { - if (string.IsNullOrEmpty(name)) - { - return System.Windows.Application.Current.Windows.OfType().Any(); - } - return System.Windows.Application.Current.Windows.OfType().Any((T w) => w.Name.Equals(name)); - } - - public static Control SetInvalid(this Control currentControl, List> errorMessages = null, string specificKey = null) - { - DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(currentControl); - if (dependencyProperty == null) - { - return null; - } - BindingExpression bindingExpression = currentControl.GetBindingExpression(dependencyProperty); - if (errorMessages == null) - { - dynamic obj = (bindingExpression != null ? bindingExpression.ResolvedSource : null); - if (obj is Control) - { - return null; - } - if ((dynamic)(!ViewHelper.HasMethod(obj, "ValidationEvent"))) - { - return null; - } - dynamic obj1 = obj; - if ((obj1 != null ? obj1.ValidationEvent : null) == (dynamic)null) - { - return null; - } - Func>> func = obj.ValidationEvent as Func>>; - if (func != null) - { - errorMessages = func(); - } - } - if (bindingExpression == null) - { - return null; - } - BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(currentControl, dependencyProperty); - if (bindingExpressionBase == null) - { - return null; - } - Validation.ClearInvalid(bindingExpressionBase); - if (errorMessages == null || !errorMessages.Any>()) - { - return null; - } - string[] strArrays = bindingExpression.ParentBinding.Path.Path.Split(new char[] { '.' }); - string str = specificKey ?? (strArrays.Last() == "Id" ? strArrays[(int)strArrays.Length - 2] : strArrays.Last()); - string valueExact = ValidationHelper.GetValueExact(errorMessages, str); - if (string.IsNullOrEmpty(valueExact)) - { - valueExact = ValidationHelper.GetValueExact(errorMessages, str); - if (string.IsNullOrEmpty(valueExact)) - { - return null; - } - } - Validation.MarkInvalid(bindingExpressionBase, new ValidationError(new ExceptionValidationRule(), bindingExpression) - { - ErrorContent = valueExact - }); - return currentControl; - } - - public static void SetInvalid(Control control, string error, bool valid) - { - DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(control); - if (dependencyProperty == null) - { - return; - } - BindingExpression bindingExpression = control.GetBindingExpression(dependencyProperty); - if (bindingExpression == null) - { - return; - } - ValidationError validationError = new ValidationError(new ExceptionValidationRule(), bindingExpression) - { - ErrorContent = error - }; - BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(control, dependencyProperty); - if (bindingExpressionBase == null) - { - return; - } - Validation.ClearInvalid(bindingExpressionBase); - if (valid) - { - return; - } - Validation.MarkInvalid(bindingExpressionBase, validationError); - } - - public static void ValidateFields(this DependencyObject dependencyObject, List> errorMessages, bool focusField = true) - { - if ((errorMessages == null ? true : !errorMessages.Any>())) - { - dependencyObject.ClearInvalid(); - return; - } - Control control = null; - foreach (Control control1 in ViewHelper.FindChildren(dependencyObject)) - { - Control control2 = control1.SetInvalid(errorMessages, null); - if (control != null || control2 == null) - { - continue; - } - control = control2; - } - if (focusField && control != null) - { - control.Focus(); - } - } - - public static T Window() - where T : Window - { - return System.Windows.Application.Current.Windows.OfType().FirstOrDefault(); - } - } -} \ No newline at end of file -- cgit v1.2.3