summaryrefslogtreecommitdiff
path: root/Decompiler/Gestor.Application.Helpers
diff options
context:
space:
mode:
authorLucas Faria Mendes <lucas.fariamo08@gmail.com>2026-03-30 15:29:41 +0000
committerLucas Faria Mendes <lucas.fariamo08@gmail.com>2026-03-30 15:29:41 +0000
commit225aa1499e37faf9d38257caabbadc68d78b427e (patch)
tree102bb7a40c58595348ae9d3c7076201759fe0720 /Decompiler/Gestor.Application.Helpers
parent1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1 (diff)
downloadgestor-225aa1499e37faf9d38257caabbadc68d78b427e.tar.gz
gestor-225aa1499e37faf9d38257caabbadc68d78b427e.zip
decompiler.com
Diffstat (limited to 'Decompiler/Gestor.Application.Helpers')
-rw-r--r--Decompiler/Gestor.Application.Helpers/ApplicationHelper.cs54
-rw-r--r--Decompiler/Gestor.Application.Helpers/ArquivoDigital.cs38
-rw-r--r--Decompiler/Gestor.Application.Helpers/AssinadorHelper.cs183
-rw-r--r--Decompiler/Gestor.Application.Helpers/BindingEnumHelper.cs45
-rw-r--r--Decompiler/Gestor.Application.Helpers/BindingHelper.cs327
-rw-r--r--Decompiler/Gestor.Application.Helpers/Connection.cs544
-rw-r--r--Decompiler/Gestor.Application.Helpers/ConnectionHelper.cs470
-rw-r--r--Decompiler/Gestor.Application.Helpers/CustomLinq.cs55
-rw-r--r--Decompiler/Gestor.Application.Helpers/DataGridExtensions.cs83
-rw-r--r--Decompiler/Gestor.Application.Helpers/Erro.cs25
-rw-r--r--Decompiler/Gestor.Application.Helpers/Funcoes.cs4086
-rw-r--r--Decompiler/Gestor.Application.Helpers/HttpHelper.cs83
-rw-r--r--Decompiler/Gestor.Application.Helpers/Instancia.cs53
-rw-r--r--Decompiler/Gestor.Application.Helpers/InstanciaAssinador.cs22
-rw-r--r--Decompiler/Gestor.Application.Helpers/LicenseHelper.cs455
-rw-r--r--Decompiler/Gestor.Application.Helpers/MailHelper.cs746
-rw-r--r--Decompiler/Gestor.Application.Helpers/NotifyPropertyChangedExtension.cs18
-rw-r--r--Decompiler/Gestor.Application.Helpers/ObrigatorioValidationRule.cs26
-rw-r--r--Decompiler/Gestor.Application.Helpers/PasswordBoxAssistant.cs92
-rw-r--r--Decompiler/Gestor.Application.Helpers/PipeClient.cs41
-rw-r--r--Decompiler/Gestor.Application.Helpers/PipeServer.cs96
-rw-r--r--Decompiler/Gestor.Application.Helpers/QueryableHelper.cs24
-rw-r--r--Decompiler/Gestor.Application.Helpers/Recursos.cs70
-rw-r--r--Decompiler/Gestor.Application.Helpers/TipoToggle.cs13
-rw-r--r--Decompiler/Gestor.Application.Helpers/ViewHelper.cs878
25 files changed, 8527 insertions, 0 deletions
diff --git a/Decompiler/Gestor.Application.Helpers/ApplicationHelper.cs b/Decompiler/Gestor.Application.Helpers/ApplicationHelper.cs
new file mode 100644
index 0000000..97acd7d
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/ApplicationHelper.cs
@@ -0,0 +1,54 @@
+using System;
+using Agger.Registro;
+using Gestor.Common.Helpers;
+
+namespace Gestor.Application.Helpers;
+
+public class ApplicationHelper
+{
+ private static string _numeroSerial;
+
+ private const string ChaveSerial = "NS";
+
+ public static string NumeroSerial
+ {
+ get
+ {
+ return _numeroSerial ?? GetSerialNumber();
+ }
+ set
+ {
+ _numeroSerial = value;
+ }
+ }
+
+ public static bool Conectado { get; set; } = true;
+
+
+ public static bool Beta { get; set; } = false;
+
+
+ public static long IdFornecedor { get; set; }
+
+ public static string Subkey { get; set; }
+
+ public static DateTime ChecagemVersao { get; set; } = Funcoes.GetNetworkTime();
+
+
+ public static Version Versao { get; set; }
+
+ internal static string GetSerialNumber()
+ {
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ try
+ {
+ string text = new RegistryHelper(Subkey).Read("NS", true);
+ NumeroSerial = (string.IsNullOrEmpty(text) ? null : EncryptionHelper.Decrypt(text));
+ return NumeroSerial;
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/ArquivoDigital.cs b/Decompiler/Gestor.Application.Helpers/ArquivoDigital.cs
new file mode 100644
index 0000000..4926944
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/ArquivoDigital.cs
@@ -0,0 +1,38 @@
+using ArquivoDigital.Infrastructure.UnitOfWork.Logic;
+using Gestor.Application.Servicos.Generic;
+using Gestor.Model.Domain.Common;
+
+namespace Gestor.Application.Helpers;
+
+public static class ArquivoDigital
+{
+ public static string ConexaoAd = null;
+
+ public static UnitOfWork Commited => UnitOfWork();
+
+ public static UnitOfWork Read => UnitOfWork(withTransaction: false);
+
+ public static string Banco { get; set; }
+
+ public static string Tabela { get; set; } = "arquivodigital";
+
+
+ private static UnitOfWork UnitOfWork(bool withTransaction = true, bool reconect = false)
+ {
+ //IL_001c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0022: Expected O, but got Unknown
+ if (ConexaoAd == null)
+ {
+ SetConnection();
+ }
+ return new UnitOfWork(ConexaoAd, Tabela, withTransaction);
+ }
+
+ public static void SetConnection(string banco = "")
+ {
+ ControleArquivoDigital val = (string.IsNullOrEmpty(banco) ? new BaseServico().ArquivoDigital().Result : new BaseServico().ArquivoDigital(banco).Result);
+ Banco = val.Catalogo;
+ Tabela = (string.IsNullOrWhiteSpace(val.Tabela) ? "arquivodigital" : val.Tabela);
+ ConexaoAd = "Server=" + Connection.Server + ";initial catalog=" + val.Catalogo + ";user=" + Connection.User + ";password=" + Connection.Password + ";";
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/AssinadorHelper.cs b/Decompiler/Gestor.Application.Helpers/AssinadorHelper.cs
new file mode 100644
index 0000000..ecc002f
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/AssinadorHelper.cs
@@ -0,0 +1,183 @@
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text;
+using System.Threading.Tasks;
+using Agger.Registro;
+using Assinador.Model.Domain;
+using Newtonsoft.Json;
+using Sign.Modelos;
+
+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 Remetente Remetente { get; set; }
+
+ public static ParametrosAssinaturaAssinador Parametros
+ {
+ get
+ {
+ return _parametros;
+ }
+ set
+ {
+ //IL_000a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_001a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0026: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0032: Unknown result type (might be due to invalid IL or missing references)
+ //IL_003e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_004e: Expected O, but got Unknown
+ _parametros = value;
+ if (value != null)
+ {
+ Remetente = new Remetente
+ {
+ Id = ApplicationHelper.IdFornecedor,
+ Documento = value.Documento,
+ Email = value.Email,
+ Nome = value.Nome,
+ Serial = ApplicationHelper.NumeroSerial
+ };
+ }
+ }
+ }
+
+ public static async Task<string> Key()
+ {
+ string key = null;
+ try
+ {
+ key = await string.Format("{0}{1}/86", Address.AssinadorApi(), "Authorization").Get<string>(ApplicationHelper.NumeroSerial.BasicKey(), basic: true);
+ }
+ catch (Exception)
+ {
+ }
+ return key;
+ }
+
+ public static async Task<int> Licencas(string key)
+ {
+ if (key == null)
+ {
+ return 0;
+ }
+ int licencas = 0;
+ try
+ {
+ licencas = int.Parse(await string.Format("{0}{1}/{2}", Address.AssinadorApi(), "Sign/Availble", ApplicationHelper.IdFornecedor).Get<string>(key));
+ }
+ catch (Exception)
+ {
+ }
+ return licencas;
+ }
+
+ public static async Task<bool> Contratado(long id)
+ {
+ return await string.Format("{0}{1}/{2}/86", Address.GestorApi(), "Purchase", id).Get<string>(ApplicationHelper.NumeroSerial.BasicKey(), basic: true) == "true";
+ }
+
+ public static string BasicKey(this string serial)
+ {
+ return Base64EncodeBasic($"{serial}:{Funcoes.GetNetworkTime().ToUniversalTime().Ticks}");
+ }
+
+ private static string Base64EncodeBasic(string plainText)
+ {
+ return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
+ }
+
+ public static async Task<HttpStatusCode> Get(this string command, string token = null, bool basic = false)
+ {
+ string text = (basic ? "Basic" : "Token");
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient val = new HttpClient();
+ if (!string.IsNullOrWhiteSpace(token))
+ {
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(text, token);
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage val2;
+ try
+ {
+ val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
+ }
+ catch (Exception)
+ {
+ return HttpStatusCode.InternalServerError;
+ }
+ return val2.StatusCode;
+ }
+
+ internal static async Task<T> Get<T>(this string command, string token = null, bool basic = false) where T : class
+ {
+ string text = (basic ? "Basic" : "Token");
+ Uri uri = new Uri(command);
+ HttpClient val = new HttpClient();
+ if (!string.IsNullOrWhiteSpace(token))
+ {
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(text, token);
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage val2;
+ try
+ {
+ val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ if (val2.StatusCode != HttpStatusCode.OK)
+ {
+ return null;
+ }
+ _ = val2.Content.ReadAsStringAsync().Result;
+ return JsonConvert.DeserializeObject<T>(val2.Content.ReadAsStringAsync().Result);
+ }
+
+ internal static async Task<T> Put<T>(this string command, T keyValues, string token = null, bool basic = false) where T : class
+ {
+ string text = (basic ? "Basic" : "Token");
+ Uri uri = new Uri(command);
+ StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ }), Encoding.UTF8, "application/json");
+ HttpClient val2 = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ if (!string.IsNullOrWhiteSpace(token))
+ {
+ val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(text, token);
+ }
+ HttpResponseMessage val3 = await val2.PutAsync(uri, (HttpContent)(object)val);
+ if (val3.StatusCode != HttpStatusCode.OK && val3.StatusCode != HttpStatusCode.NoContent)
+ {
+ return null;
+ }
+ if (val3.StatusCode == HttpStatusCode.NoContent)
+ {
+ return null;
+ }
+ return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/BindingEnumHelper.cs b/Decompiler/Gestor.Application.Helpers/BindingEnumHelper.cs
new file mode 100644
index 0000000..aa28e3a
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/BindingEnumHelper.cs
@@ -0,0 +1,45 @@
+using System;
+using System.ComponentModel;
+using System.Text;
+
+namespace Gestor.Application.Helpers;
+
+public class BindingEnumHelper
+{
+ public static string ConcatenarDescricoesEnum<TEnum>(string valores) where TEnum : Enum
+ {
+ if (valores == null)
+ {
+ return null;
+ }
+ return ConcatenarDescricoesEnum<TEnum>(Array.ConvertAll(valores.Split(new char[1] { ',' }), int.Parse));
+ }
+
+ private static string ConcatenarDescricoesEnum<TEnum>(int[] valores) where TEnum : Enum
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ foreach (int num in valores)
+ {
+ if (Enum.IsDefined(typeof(TEnum), num))
+ {
+ string text = ObterDescricaoEnum((TEnum)Enum.ToObject(typeof(TEnum), num));
+ stringBuilder.Append(text + ", ");
+ }
+ else
+ {
+ stringBuilder.Append("Valor desconhecido, ");
+ }
+ }
+ return stringBuilder.ToString().TrimEnd(',', ' ');
+ }
+
+ private static string ObterDescricaoEnum<TEnum>(TEnum valor) where TEnum : Enum
+ {
+ DescriptionAttribute[] array = (DescriptionAttribute[])valor.GetType().GetField(valor.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), inherit: false);
+ if (array != null && array.Length != 0)
+ {
+ return array[0].Description;
+ }
+ return valor.ToString();
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/BindingHelper.cs b/Decompiler/Gestor.Application.Helpers/BindingHelper.cs
new file mode 100644
index 0000000..cece7c8
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/BindingHelper.cs
@@ -0,0 +1,327 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using CurrencyTextBoxControl;
+using Gestor.Common.Helpers;
+using Gestor.Common.Validation;
+using Gestor.Model.Helper;
+
+namespace Gestor.Application.Helpers;
+
+public static class BindingHelper
+{
+ public static void DeleteValidationRule(object control)
+ {
+ //IL_0038: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0047: Expected O, but got Unknown
+ //IL_006b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_004b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0050: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0057: Unknown result type (might be due to invalid IL or missing references)
+ //IL_007e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_008d: Expected O, but got Unknown
+ //IL_00b1: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0091: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0096: Unknown result type (might be due to invalid IL or missing references)
+ //IL_009d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00c4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00d3: Expected O, but got Unknown
+ //IL_00f7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00d7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00dc: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00e3: Unknown result type (might be due to invalid IL or missing references)
+ switch (control.GetType().Name)
+ {
+ case "TextBox":
+ {
+ Binding val = (Binding)(((object)BindingOperations.GetBinding((DependencyObject)(TextBox)control, TextBox.TextProperty)) ?? ((object)new Binding
+ {
+ Mode = (BindingMode)0,
+ UpdateSourceTrigger = (UpdateSourceTrigger)1
+ }));
+ val.ValidationRules.Clear();
+ ((FrameworkElement)(TextBox)control).SetBinding(TextBox.TextProperty, (BindingBase)(object)val);
+ break;
+ }
+ case "DatePicker":
+ {
+ Binding val = (Binding)(((object)BindingOperations.GetBinding((DependencyObject)(DatePicker)control, DatePicker.SelectedDateProperty)) ?? ((object)new Binding
+ {
+ Mode = (BindingMode)0,
+ UpdateSourceTrigger = (UpdateSourceTrigger)1
+ }));
+ val.ValidationRules.Clear();
+ ((FrameworkElement)(DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, (BindingBase)(object)val);
+ break;
+ }
+ case "CurrencyTextBox":
+ {
+ Binding val = (Binding)(((object)BindingOperations.GetBinding((DependencyObject)(CurrencyTextBox)control, CurrencyTextBox.NumberProperty)) ?? ((object)new Binding
+ {
+ Mode = (BindingMode)0,
+ UpdateSourceTrigger = (UpdateSourceTrigger)1
+ }));
+ val.ValidationRules.Clear();
+ ((FrameworkElement)(CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, (BindingBase)(object)val);
+ break;
+ }
+ }
+ }
+
+ public static string GetPath(object control)
+ {
+ //IL_005a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0069: Expected O, but got Unknown
+ //IL_0080: Unknown result type (might be due to invalid IL or missing references)
+ //IL_008f: Expected O, but got Unknown
+ //IL_00a3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00b2: Expected O, but got Unknown
+ //IL_00c6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00d5: Expected O, but got Unknown
+ //IL_00e9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00f8: Expected O, but got Unknown
+ PropertyPath path;
+ switch (control.GetType().Name)
+ {
+ default:
+ return "";
+ case "TextBox":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(TextBox)control, TextBox.TextProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ break;
+ }
+ case "DatePicker":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(DatePicker)control, DatePicker.SelectedDateProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ break;
+ }
+ case "CurrencyTextBox":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(CurrencyTextBox)control, CurrencyTextBox.NumberProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ break;
+ }
+ case "ComboBox":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(ComboBox)control, Selector.SelectedItemProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ break;
+ }
+ case "AutoCompleteBox":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(AutoCompleteBox)control, AutoCompleteBox.SelectedItemProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ break;
+ }
+ }
+ return path.Path;
+ }
+
+ public static void AddValidationRule(object control, ValidationRule rule = null)
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0012: Unknown result type (might be due to invalid IL or missing references)
+ //IL_001a: Expected O, but got Unknown
+ //IL_004f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_005e: Expected O, but got Unknown
+ //IL_00c3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00d2: Expected O, but got Unknown
+ //IL_0085: Unknown result type (might be due to invalid IL or missing references)
+ //IL_008f: Expected O, but got Unknown
+ //IL_013d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_014c: Expected O, but got Unknown
+ //IL_00b0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ff: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0109: Expected O, but got Unknown
+ //IL_00e9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_012a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0179: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0183: Expected O, but got Unknown
+ //IL_0163: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01a4: Unknown result type (might be due to invalid IL or missing references)
+ Type type = control.GetType();
+ Binding val = new Binding
+ {
+ Mode = (BindingMode)0,
+ UpdateSourceTrigger = (UpdateSourceTrigger)1
+ };
+ switch (type.Name)
+ {
+ case "TextBox":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(TextBox)control, TextBox.TextProperty);
+ if (binding != null)
+ {
+ PropertyPath path = binding.Path;
+ if (rule != null)
+ {
+ val.ValidationRules.Add(rule);
+ }
+ val.Path = new PropertyPath(path.Path, Array.Empty<object>());
+ if (val.ValidationRules.Count > 0)
+ {
+ val.ValidationRules[0].ValidatesOnTargetUpdated = true;
+ }
+ ((FrameworkElement)(TextBox)control).SetBinding(TextBox.TextProperty, (BindingBase)(object)val);
+ }
+ break;
+ }
+ case "DatePicker":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(DatePicker)control, DatePicker.SelectedDateProperty);
+ if (binding != null)
+ {
+ PropertyPath path = binding.Path;
+ val.ValidationRules.Add((ValidationRule)(((object)rule) ?? ((object)new ValidacaoData())));
+ val.Path = new PropertyPath(path.Path, Array.Empty<object>());
+ if (val.ValidationRules.Count > 0)
+ {
+ val.ValidationRules[0].ValidatesOnTargetUpdated = true;
+ }
+ ((FrameworkElement)(DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, (BindingBase)(object)val);
+ }
+ break;
+ }
+ case "CurrencyTextBox":
+ {
+ Binding binding = BindingOperations.GetBinding((DependencyObject)(CurrencyTextBox)control, CurrencyTextBox.NumberProperty);
+ if (binding != null)
+ {
+ PropertyPath path = binding.Path;
+ val.ValidationRules.Add((ValidationRule)(((object)rule) ?? ((object)new ValidacaoDouble())));
+ val.Path = new PropertyPath(path.Path, Array.Empty<object>());
+ if (val.ValidationRules.Count > 0)
+ {
+ val.ValidationRules[0].ValidatesOnTargetUpdated = true;
+ }
+ ((FrameworkElement)(CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, (BindingBase)(object)val);
+ }
+ break;
+ }
+ }
+ }
+
+ public static void AddBinding(object control, string path, ValidationRule rule = null)
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0012: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0019: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0020: Unknown result type (might be due to invalid IL or missing references)
+ //IL_002a: Expected O, but got Unknown
+ //IL_002b: Expected O, but got Unknown
+ //IL_007b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_008e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00a1: Unknown result type (might be due to invalid IL or missing references)
+ Type type = control.GetType();
+ Binding val = new Binding
+ {
+ Mode = (BindingMode)0,
+ UpdateSourceTrigger = (UpdateSourceTrigger)1,
+ Path = new PropertyPath(path, Array.Empty<object>())
+ };
+ if (rule != null)
+ {
+ val.ValidationRules.Add(rule);
+ val.ValidationRules[0].ValidatesOnTargetUpdated = true;
+ }
+ switch (type.Name)
+ {
+ case "TextBox":
+ ((FrameworkElement)(TextBox)control).SetBinding(TextBox.TextProperty, (BindingBase)(object)val);
+ break;
+ case "DatePicker":
+ ((FrameworkElement)(DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, (BindingBase)(object)val);
+ break;
+ case "CurrencyTextBox":
+ ((FrameworkElement)(CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, (BindingBase)(object)val);
+ break;
+ }
+ }
+
+ public static List<KeyValuePair<string, string>> BindingData<T>(bool withSelect = true, bool enumDefault = true, string defaultValue = "", string defaultText = "", bool orderByLabel = false, bool showAll = false, bool orderbyAttr = false)
+ {
+ List<KeyValuePair<string, string>> comboData = BeforeTreatment<T>(defaultValue, defaultText);
+ Type enumType = typeof(T);
+ List<KeyValuePair<string, string>> comboValues = Enum.GetNames(enumType).AsEnumerable().Where(delegate(string x)
+ {
+ if (showAll)
+ {
+ return true;
+ }
+ T obj = (T)Enum.Parse(enumType, x);
+ bool? @default = EnumHelper.GetDefault<T>(obj);
+ bool hidden = EnumHelper.GetHidden<T>(obj);
+ return (!@default.HasValue || @default.Value == enumDefault) && !hidden;
+ })
+ .Select(delegate(string x)
+ {
+ T val = (T)Enum.Parse(enumType, x);
+ return new KeyValuePair<string, string>(EnumHelper.Value<T>(val), EnumHelper.GetDescription<T>(val));
+ })
+ .ToList();
+ return AfterTreatment<T>(withSelect, orderByLabel, comboData, comboValues, orderbyAttr);
+ }
+
+ private static List<KeyValuePair<string, string>> BeforeTreatment<T>(string defaultValue, string defaultText)
+ {
+ defaultText = ((defaultText == string.Empty) ? "Selecione" : defaultText);
+ return new List<KeyValuePair<string, string>>
+ {
+ new KeyValuePair<string, string>(defaultValue, defaultText)
+ };
+ }
+
+ private static List<KeyValuePair<string, string>> AfterTreatment<T>(bool withSelect, bool orderByLabel, List<KeyValuePair<string, string>> comboData, List<KeyValuePair<string, string>> comboValues, bool orderbyAttr = false)
+ {
+ if (!withSelect)
+ {
+ comboData.RemoveAt(0);
+ }
+ comboData.AddRange(comboValues);
+ if (orderbyAttr)
+ {
+ Type enumType = typeof(T);
+ comboData = comboData.OrderBy((KeyValuePair<string, string> s) => (s.Key == string.Empty) ? new int?(0) : EnumHelper.GetOrder<T>((T)Enum.Parse(enumType, s.Key))).ToList();
+ return comboData;
+ }
+ if (!orderByLabel)
+ {
+ return comboData;
+ }
+ comboData = (from x in comboData
+ orderby Math.Sign(ValidationHelper.ToFloat(x.Key)), Math.Abs(ValidationHelper.ToFloat(x.Key))
+ select x).ToList();
+ comboData = (from s in comboData
+ orderby comboData.IndexOf(s) != 0, s.Value
+ select s).ToList();
+ return comboData;
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/Connection.cs b/Decompiler/Gestor.Application.Helpers/Connection.cs
new file mode 100644
index 0000000..20ca14c
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/Connection.cs
@@ -0,0 +1,544 @@
+using System;
+using System.Collections.Generic;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text;
+using System.Threading.Tasks;
+using Agger.Registro;
+using Gestor.Common.Security;
+using Gestor.Common.Validation;
+using Gestor.Model.API;
+using Newtonsoft.Json;
+
+namespace Gestor.Application.Helpers;
+
+public static class Connection
+{
+ private const bool defaultUsaAzureStorage = false;
+
+ private const string defaultAzureStorage = "ad1";
+
+ public static string Server;
+
+ public static string Catalog;
+
+ public static string User;
+
+ public static string Password;
+
+ public static string Pool;
+
+ public static string Type;
+
+ public static ConnectionAddress ConnectionAddress { get; set; }
+
+ public static string LinkAggilizador { get; set; }
+
+ public static string UrlCentralSegurado { get; set; }
+
+ public static string BasicKey()
+ {
+ return $"{ApplicationHelper.NumeroSerial}:{Funcoes.GetNetworkTime().ToUniversalTime().Ticks}".Base64Encode();
+ }
+
+ public static string Base64Encode(this string plainText)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ return new Token().Encrypt(plainText);
+ }
+
+ public static string EncodeBase64(this string plainText)
+ {
+ try
+ {
+ return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
+ }
+ catch
+ {
+ }
+ return string.Empty;
+ }
+
+ public static async Task<string> GetPool()
+ {
+ ConnectionAddress val = await Get<ConnectionAddress>("Server/Pool");
+ if (val == null)
+ {
+ return "";
+ }
+ Pool = new Token().Decrypt(val.Pool);
+ return Pool;
+ }
+
+ public static string GetConnection(bool tryconnect = true)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0006: Expected O, but got Unknown
+ //IL_000b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0011: Expected O, but got Unknown
+ //IL_03a5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03aa: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03b5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03c0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03cb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03d6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03e1: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03ec: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03f7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03fe: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0405: Unknown result type (might be due to invalid IL or missing references)
+ //IL_042d: Expected O, but got Unknown
+ try
+ {
+ Token val = new Token();
+ RegistryHelper val2 = new RegistryHelper(ApplicationHelper.Subkey);
+ bool flag = false;
+ string azureStorage = "ad1";
+ if (ApplicationHelper.Conectado)
+ {
+ List<ConnectionAddress> result = Get<List<ConnectionAddress>>($"Server/{ApplicationHelper.IdFornecedor}").Result;
+ for (int i = 0; i < result.Count; i++)
+ {
+ string text = val.AggerEncrypt(val.Decrypt(result[i].Server));
+ string text2 = val.AggerEncrypt(val.Decrypt(result[i].Catalog));
+ string text3 = val.AggerEncrypt(val.Decrypt(result[i].User));
+ string text4 = val.AggerEncrypt(val.Decrypt(result[i].Password));
+ string text5 = val.AggerEncrypt(val.Decrypt(result[i].Pool));
+ string text6 = result[i].Type.ToString();
+ LinkAggilizador = (string.IsNullOrEmpty(result[i].Aggilizador) ? null : result[i].Aggilizador);
+ UrlCentralSegurado = (string.IsNullOrEmpty(result[i].UrlCentralSegurado) ? null : result[0].UrlCentralSegurado);
+ flag = result[i].UsaAzureStorage;
+ azureStorage = (string.IsNullOrEmpty(result[i].AzureStorage) ? "ad1" : val.Decrypt(result[i].AzureStorage));
+ val2.Write<string>($"SERVER{i + 1}", text, true);
+ val2.Write<string>($"DB{i + 1}", text2, true);
+ val2.Write<string>($"USER{i + 1}", text3, true);
+ val2.Write<string>($"PASSWORD{i + 1}", text4, true);
+ val2.Write<string>($"POOL{i + 1}", text5, true);
+ val2.Write<string>($"TYPE{i + 1}", text6, true);
+ }
+ }
+ string result2 = "";
+ for (int j = 0; j < 3 && val2.Read($"SERVER{j + 1}", true) != null; j++)
+ {
+ if (val2.Read($"TYPE{j + 1}", true) == "4")
+ {
+ continue;
+ }
+ Server = val.AggerDecrypt(val2.Read($"SERVER{j + 1}", true));
+ Catalog = val.AggerDecrypt(val2.Read($"DB{j + 1}", true));
+ User = val.AggerDecrypt(val2.Read($"USER{j + 1}", true));
+ Password = val.AggerDecrypt(val2.Read($"PASSWORD{j + 1}", true));
+ Pool = val.AggerDecrypt(val2.Read($"POOL{j + 1}", true));
+ Type = val2.Read($"TYPE{j + 1}", true);
+ if (!flag)
+ {
+ flag = Task.Run(async () => await SaveInAzureStorage()).Result;
+ }
+ ConnectionAddress = new ConnectionAddress
+ {
+ Server = Server,
+ Catalog = Catalog,
+ User = User,
+ Password = Password,
+ Pool = Pool,
+ Aggilizador = LinkAggilizador,
+ UrlCentralSegurado = UrlCentralSegurado,
+ UsaAzureStorage = flag,
+ AzureStorage = azureStorage,
+ Type = int.Parse(ValidationHelper.IsNotNullOrEmpty(Type) ? "0" : Type)
+ };
+ string connectionString = GetConnectionString();
+ if (!tryconnect || TryConnect(connectionString))
+ {
+ result2 = connectionString;
+ break;
+ }
+ }
+ return result2;
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ public static string GetConnectionString()
+ {
+ return "Server=" + Server + ";initial catalog=" + Catalog + ";user=" + User + ";password=" + Password + ";";
+ }
+
+ internal static bool TryConnect(string connectionString, int retryCount = 1)
+ {
+ //IL_000c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0012: Expected O, but got Unknown
+ List<Exception> list = new List<Exception>();
+ for (int i = 0; i < retryCount; i++)
+ {
+ try
+ {
+ SqlConnection val = new SqlConnection(connectionString);
+ try
+ {
+ ((DbConnection)(object)val).Open();
+ }
+ finally
+ {
+ ((IDisposable)val)?.Dispose();
+ }
+ return true;
+ }
+ catch (Exception item)
+ {
+ list.Add(item);
+ }
+ }
+ return list.Count == 0;
+ }
+
+ public static string GetAdConnection(string serial)
+ {
+ ApplicationHelper.NumeroSerial = serial;
+ if (string.IsNullOrWhiteSpace(Server))
+ {
+ GetAdConnection(serial);
+ }
+ return "Server=" + Server + ";initial catalog=" + Catalog + "AD;user=" + User + ";password=" + Password + ";";
+ }
+
+ public static async Task<T> Get<T>(string command, bool autorizar = true, bool verificarConexao = false) where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient val = new HttpClient();
+ if (autorizar)
+ {
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage val2;
+ try
+ {
+ val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
+ }
+ catch (Exception)
+ {
+ ApplicationHelper.Conectado = false;
+ return null;
+ }
+ if (verificarConexao)
+ {
+ ApplicationHelper.Conectado = true;
+ }
+ if (val2.StatusCode == HttpStatusCode.NoContent)
+ {
+ return null;
+ }
+ if (val2.StatusCode != HttpStatusCode.OK)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
+ }
+ return JsonConvert.DeserializeObject<T>(val2.Content.ReadAsStringAsync().Result);
+ }
+
+ public static async Task<HttpStatusCode> Get(string command, bool autorizar = true)
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient val = new HttpClient();
+ if (autorizar)
+ {
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage val2;
+ try
+ {
+ val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
+ }
+ catch (Exception)
+ {
+ return HttpStatusCode.InternalServerError;
+ }
+ return val2.StatusCode;
+ }
+
+ public static async Task<T> Post<T>(string command, T keyValues) where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1,
+ MissingMemberHandling = (MissingMemberHandling)0
+ }), Encoding.UTF8, "application/json");
+ HttpClient val2 = new HttpClient();
+ val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage val3 = await val2.PostAsync(uri, (HttpContent)(object)val);
+ if (val3.StatusCode == HttpStatusCode.NoContent)
+ {
+ return null;
+ }
+ if (val3.StatusCode != HttpStatusCode.OK)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
+ }
+ return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
+ }
+
+ public static async Task<T> Post<T>(string command, object keyValues) where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ StringContent val = new StringContent(JsonConvert.SerializeObject(keyValues, (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1,
+ MissingMemberHandling = (MissingMemberHandling)0
+ }), Encoding.UTF8, "application/json");
+ HttpClient val2 = new HttpClient();
+ val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage val3 = await val2.PostAsync(uri, (HttpContent)(object)val);
+ if (val3.StatusCode == HttpStatusCode.NoContent)
+ {
+ return null;
+ }
+ if (val3.StatusCode != HttpStatusCode.OK)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
+ }
+ return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
+ }
+
+ public static async Task<T> Put<T>(string command, T keyValues) where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ }), Encoding.UTF8, "application/json");
+ HttpClient val2 = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ HttpResponseMessage obj = await val2.PutAsync(uri, (HttpContent)(object)val);
+ if (obj.StatusCode != HttpStatusCode.OK)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
+ }
+ return JsonConvert.DeserializeObject<T>(obj.Content.ReadAsStringAsync().Result);
+ }
+
+ public static async Task<T> Put<T>(string command, object keyValues) where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ StringContent val = new StringContent(JsonConvert.SerializeObject(keyValues, (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ }), Encoding.UTF8, "application/json");
+ HttpClient val2 = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ HttpResponseMessage val3 = await val2.PutAsync(uri, (HttpContent)(object)val);
+ if (val3.StatusCode == HttpStatusCode.NoContent)
+ {
+ return null;
+ }
+ if (val3.StatusCode != HttpStatusCode.OK)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
+ }
+ return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
+ }
+
+ public static async void PutError<T>(T keyValues) where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), "Error/Objeto");
+ StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ }), Encoding.UTF8, "application/json");
+ HttpClient val2 = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ if ((await val2.PutAsync(uri, (HttpContent)(object)val)).StatusCode != HttpStatusCode.NoContent)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " Error", null);
+ }
+ }
+
+ public static async Task<bool> Delete(string command)
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient val = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
+ if ((await val.DeleteAsync(uri)).StatusCode != HttpStatusCode.OK)
+ {
+ throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
+ }
+ return true;
+ }
+
+ internal static async Task<byte[]> DownloadFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad", bool forceDownload = false)
+ {
+ azureStorage = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
+ Uri uri = Address.ApiAD.Append(AdApiV2(azureStorage)).Append(path).Append(ano.ToString())
+ .Append(id.ToString())
+ .Append(extensao.Replace(".", string.Empty));
+ try
+ {
+ string path2 = $"{Path.GetTempPath()}{id}{extensao}";
+ if (!forceDownload && File.Exists(path2))
+ {
+ return File.ReadAllBytes(path2);
+ }
+ HttpClient client = new HttpClient();
+ try
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ ((HttpHeaders)client.DefaultRequestHeaders).Clear();
+ ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
+ HttpResponseMessage val = await client.GetAsync(uri);
+ if (val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NotFound)
+ {
+ return await val.Content.ReadAsByteArrayAsync();
+ }
+ }
+ finally
+ {
+ ((IDisposable)client)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return null;
+ }
+
+ internal static async Task<bool> SaveInAzureStorage()
+ {
+ string text = $"{Address.GestorApi()}Data";
+ try
+ {
+ HttpClient client = new HttpClient();
+ try
+ {
+ ((HttpHeaders)client.DefaultRequestHeaders).Clear();
+ ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
+ HttpResponseMessage val = await client.GetAsync(text);
+ if (val.IsSuccessStatusCode)
+ {
+ return await val.Content.ReadAsStringAsync() == "true";
+ }
+ }
+ finally
+ {
+ ((IDisposable)client)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return false;
+ }
+
+ internal static async Task<bool> UploadFile(UploadFile upload, string path = "ad")
+ {
+ Uri uri = Address.ApiAD.Append(AdApiV2(ConnectionAddress.AzureStorage)).Append(path);
+ try
+ {
+ HttpClient client = new HttpClient();
+ try
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ ((HttpHeaders)client.DefaultRequestHeaders).Clear();
+ ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
+ HttpResponseMessage val = await client.PutAsync(uri, (HttpContent)new StringContent(JsonConvert.SerializeObject((object)upload), Encoding.UTF8, "application/json"));
+ return val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent;
+ }
+ finally
+ {
+ ((IDisposable)client)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return false;
+ }
+
+ internal static async Task<bool> DeleteFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad")
+ {
+ azureStorage = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
+ Uri uri = Address.ApiAD.Append(AdApiV2(azureStorage)).Append(path).Append(ano.ToString())
+ .Append(id.ToString())
+ .Append(extensao.Replace(".", string.Empty));
+ try
+ {
+ HttpClient client = new HttpClient();
+ try
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ ((HttpHeaders)client.DefaultRequestHeaders).Clear();
+ ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
+ HttpResponseMessage val = await client.DeleteAsync(uri);
+ return val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent;
+ }
+ finally
+ {
+ ((IDisposable)client)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return false;
+ }
+
+ internal static async Task<double> EspacoUsadoAzureInBytes(string path = "")
+ {
+ Uri uri = Address.ApiAD.Append(AdApiV2(ConnectionAddress.AzureStorage)).Append("tamanho");
+ if (!string.IsNullOrEmpty(path))
+ {
+ uri.Append(path);
+ }
+ try
+ {
+ HttpClient client = new HttpClient();
+ try
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ ((HttpHeaders)client.DefaultRequestHeaders).Clear();
+ ((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
+ HttpResponseMessage val = await client.GetAsync(uri);
+ if (val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent)
+ {
+ return double.Parse(await val.Content.ReadAsStringAsync());
+ }
+ }
+ finally
+ {
+ ((IDisposable)client)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return 0.0;
+ }
+
+ private static string AdApiV2(string storage)
+ {
+ if (Address.ApiAD.ToString().Contains("/api/v1"))
+ {
+ return string.Empty;
+ }
+ return storage;
+ }
+
+ internal static Uri Append(this Uri uri, params string[] paths)
+ {
+ return new Uri(paths.Aggregate(uri.AbsoluteUri, (string current, string path) => current.TrimEnd(new char[1] { '/' }) + "/" + path.TrimStart(new char[1] { '/' })));
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/ConnectionHelper.cs b/Decompiler/Gestor.Application.Helpers/ConnectionHelper.cs
new file mode 100644
index 0000000..8bb8e98
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/ConnectionHelper.cs
@@ -0,0 +1,470 @@
+using System;
+using System.Collections.Generic;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading;
+using System.Threading.Tasks;
+using Agger.Registro;
+using Gestor.Application.Migration;
+using Gestor.Common.Exceptions;
+
+namespace Gestor.Application.Helpers;
+
+public class ConnectionHelper
+{
+ public static bool BancoAtualizado { get; set; }
+
+ private static async Task<string> Get(string command, bool autorizar = true)
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient val = new HttpClient
+ {
+ Timeout = new TimeSpan(0, 2, 0)
+ };
+ if (autorizar)
+ {
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", Connection.BasicKey());
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ HttpResponseMessage val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
+ if (val2.StatusCode != HttpStatusCode.OK)
+ {
+ return await val2.Content.ReadAsStringAsync();
+ }
+ return null;
+ }
+ catch (Exception)
+ {
+ return "ERRO INTERNO";
+ }
+ }
+
+ private static async Task<string> Post(string command)
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient val = new HttpClient();
+ val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", Connection.BasicKey());
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ HttpResponseMessage val2 = await val.PostAsync(uri, (HttpContent)null);
+ if (val2.StatusCode != HttpStatusCode.OK)
+ {
+ return await val2.Content.ReadAsStringAsync();
+ }
+ return null;
+ }
+ catch (Exception)
+ {
+ return "ERRO INTERNO";
+ }
+ }
+
+ private static async Task<string> DatabaseTest()
+ {
+ return await Get("Data/Verify");
+ }
+
+ public async Task<string> AtualizarBanco()
+ {
+ bool num = await new Migrator().Execute();
+ BancoAtualizado = num;
+ return num ? null : "HOUVE UM PROBLEMA AO ATUALIZAR O BANCO DE DADOS.";
+ }
+
+ internal static async Task<bool> TryConnect(string connectionString, int retryCount = 1)
+ {
+ return await Task.Run(delegate
+ {
+ //IL_001b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0021: Expected O, but got Unknown
+ List<Exception> list = new List<Exception>();
+ for (int i = 0; i < retryCount; i++)
+ {
+ try
+ {
+ SqlConnection val = new SqlConnection(connectionString + "Connection Timeout=5");
+ try
+ {
+ ((DbConnection)(object)val).Open();
+ }
+ finally
+ {
+ ((IDisposable)val)?.Dispose();
+ }
+ return true;
+ }
+ catch (Exception item)
+ {
+ list.Add(item);
+ }
+ }
+ return list.Count == 0;
+ });
+ }
+
+ internal static async Task<bool> HasLogin(string connectionString)
+ {
+ return await Task.Run(delegate
+ {
+ //IL_000c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0012: Expected O, but got Unknown
+ List<Exception> list = new List<Exception>();
+ try
+ {
+ SqlConnection val = new SqlConnection(connectionString);
+ try
+ {
+ ((DbConnection)(object)val).Open();
+ SqlCommand val2 = val.CreateCommand();
+ try
+ {
+ ((DbCommand)(object)val2).CommandText = "SELECT 1 FROM [dbo].[usuario] WHERE [removido] IS NULL OR [removido] = '0'";
+ SqlDataReader val3 = val2.ExecuteReader();
+ if (!((DbDataReader)(object)val3).HasRows)
+ {
+ return false;
+ }
+ ((DbDataReader)(object)val3).Close();
+ ((DbCommand)(object)val2).CommandText = "SELECT 1 FROM [dbo].[empresa] WHERE [idempresa] = 1";
+ val3 = val2.ExecuteReader();
+ if (!((DbDataReader)(object)val3).HasRows)
+ {
+ return false;
+ }
+ ((DbDataReader)(object)val3).Close();
+ ((DbCommand)(object)val2).CommandText = "SELECT 1 FROM [dbo].[vendedor] WHERE [corretora] = '1'";
+ val3 = val2.ExecuteReader();
+ if (!((DbDataReader)(object)val3).HasRows)
+ {
+ return false;
+ }
+ ((DbDataReader)(object)val3).Close();
+ return true;
+ }
+ finally
+ {
+ ((IDisposable)val2)?.Dispose();
+ }
+ }
+ finally
+ {
+ ((IDisposable)val)?.Dispose();
+ }
+ }
+ catch (Exception item)
+ {
+ list.Add(item);
+ }
+ return list.Count == 0;
+ });
+ }
+
+ public async Task<Tuple<bool, bool>> PrimeiroAcesso()
+ {
+ string conn = Connection.GetConnection(tryconnect: false);
+ if (!(await TryConnect(conn)))
+ {
+ if (!(await DatabaseExists()))
+ {
+ return new Tuple<bool, bool>(item1: false, item2: false);
+ }
+ bool flag = !(await LoginExists());
+ if (flag)
+ {
+ flag = !(await CreateLogin());
+ }
+ if (flag)
+ {
+ return new Tuple<bool, bool>(item1: false, item2: false);
+ }
+ flag = !(await UserExists());
+ if (flag)
+ {
+ flag = !(await CreateUser());
+ }
+ if (flag)
+ {
+ return new Tuple<bool, bool>(item1: false, item2: false);
+ }
+ }
+ return (!(await HasLogin(conn))) ? new Tuple<bool, bool>(item1: true, item2: false) : new Tuple<bool, bool>(item1: true, item2: true);
+ }
+
+ public bool BDConvertido()
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000c: Expected O, but got Unknown
+ try
+ {
+ SqlConnection val = new SqlConnection(Connection.GetConnection(tryconnect: false));
+ try
+ {
+ ((DbConnection)(object)val).Open();
+ SqlCommand val2 = val.CreateCommand();
+ try
+ {
+ ((DbCommand)(object)val2).CommandText = "SELECT OBJECT_ID('dbo.AtualizacaoDados', 'U')";
+ if (((DbCommand)(object)val2).ExecuteScalar() == DBNull.Value)
+ {
+ return true;
+ }
+ }
+ finally
+ {
+ ((IDisposable)val2)?.Dispose();
+ }
+ SqlCommand val3 = val.CreateCommand();
+ try
+ {
+ ((DbCommand)(object)val3).CommandText = "SELECT COUNT(IdArquivo) FROM AtualizacaoDados";
+ return (int)((DbCommand)(object)val3).ExecuteScalar() == 0;
+ }
+ finally
+ {
+ ((IDisposable)val3)?.Dispose();
+ }
+ }
+ finally
+ {
+ ((IDisposable)val)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return true;
+ }
+
+ public bool ExisteEmpresa()
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000c: Expected O, but got Unknown
+ try
+ {
+ SqlConnection val = new SqlConnection(Connection.GetConnection(tryconnect: false));
+ try
+ {
+ ((DbConnection)(object)val).Open();
+ SqlCommand val2 = val.CreateCommand();
+ try
+ {
+ ((DbCommand)(object)val2).CommandText = "SELECT OBJECT_ID (N'empresa', N'U')";
+ if (((DbCommand)(object)val2).ExecuteScalar() == DBNull.Value)
+ {
+ return false;
+ }
+ }
+ finally
+ {
+ ((IDisposable)val2)?.Dispose();
+ }
+ SqlCommand val3 = val.CreateCommand();
+ try
+ {
+ ((DbCommand)(object)val3).CommandText = "SELECT COUNT(idempresa) FROM empresa WHERE idempresa = 1";
+ return (int)((DbCommand)(object)val3).ExecuteScalar() > 0;
+ }
+ finally
+ {
+ ((IDisposable)val3)?.Dispose();
+ }
+ }
+ finally
+ {
+ ((IDisposable)val)?.Dispose();
+ }
+ }
+ catch
+ {
+ }
+ return true;
+ }
+
+ public async Task<string> VerifyConnection()
+ {
+ _ = 3;
+ try
+ {
+ if (await TryConnect(Connection.GetConnection(tryconnect: false)))
+ {
+ return null;
+ }
+ string text = await DatabaseTest();
+ if (text != null)
+ {
+ return text;
+ }
+ string text2 = Connection.ConnectionAddress.Catalog + ".cfg";
+ string path = AppDomain.CurrentDomain.BaseDirectory + "Data_" + text2;
+ string path2 = AppDomain.CurrentDomain.BaseDirectory + "Files_" + text2;
+ string path3 = AppDomain.CurrentDomain.BaseDirectory + "Sign_" + text2;
+ if (File.Exists(path))
+ {
+ File.Delete(path);
+ }
+ if (File.Exists(path2))
+ {
+ File.Delete(path2);
+ }
+ if (File.Exists(path3))
+ {
+ File.Delete(path3);
+ }
+ string returnMessage = await CheckDatabase();
+ await Task.Delay(2000);
+ return returnMessage;
+ }
+ catch (Exception)
+ {
+ return "ERRO AO CONECTAR NO BANCO DE DADOS DA CORRETORA";
+ }
+ }
+
+ public static async Task<string> CheckDatabase()
+ {
+ _ = 5;
+ try
+ {
+ bool hasDatabase = await DatabaseExists();
+ bool hasLogin = await LoginExists();
+ bool hasUser = await UserExists();
+ bool created = false;
+ if (hasDatabase && hasLogin && hasUser)
+ {
+ return null;
+ }
+ if (!hasDatabase)
+ {
+ hasDatabase = await CreateDatabase();
+ }
+ if (!hasDatabase)
+ {
+ return "ERRO AO CRIAR BANCO DE DADOS";
+ }
+ if (!hasLogin)
+ {
+ bool num = await CreateLogin();
+ bool flag = num;
+ created = num;
+ hasLogin = flag;
+ }
+ if (!hasLogin)
+ {
+ return "ERRO AO CRIAR LOGIN";
+ }
+ if (!hasUser)
+ {
+ hasUser = await CreateUser();
+ }
+ if (created)
+ {
+ int num2 = 10;
+ while (num2 > 1)
+ {
+ try
+ {
+ SqlConnection val = new SqlConnection(Connection.GetConnection());
+ try
+ {
+ ((DbConnection)(object)val).Open();
+ }
+ finally
+ {
+ ((IDisposable)val)?.Dispose();
+ }
+ }
+ catch
+ {
+ Thread.Sleep(10000);
+ num2--;
+ continue;
+ }
+ break;
+ }
+ }
+ return (!hasUser) ? "ERRO AO CRIAR USUÁRIO" : null;
+ }
+ catch (ValidationException val2)
+ {
+ return ((Exception)val2).Message;
+ }
+ catch (Exception)
+ {
+ return "ERRO AO CRIAR BANCO DE DADOS";
+ }
+ }
+
+ private static async Task<bool> CreateDatabase()
+ {
+ string text = Uri.EscapeDataString(ApplicationHelper.NumeroSerial);
+ if (await Post("Data/CreateData?token=" + text) == "ERRO INTERNO")
+ {
+ return false;
+ }
+ int tries = 0;
+ bool flag = false;
+ while (tries < 24 && !flag)
+ {
+ await Task.Delay(5000);
+ tries++;
+ flag = await DatabaseExists();
+ }
+ return flag;
+ }
+
+ private static async Task<bool> CreateLogin()
+ {
+ if (await Post("Data/CreateLogin") == "ERRO INTERNO")
+ {
+ return false;
+ }
+ int tries = 0;
+ bool flag = false;
+ while (tries < 24 && !flag)
+ {
+ await Task.Delay(5000);
+ tries++;
+ flag = await Get("Data/ServerLoginExists") == null;
+ }
+ return flag;
+ }
+
+ private static async Task<bool> CreateUser()
+ {
+ if (await Post("Data/CreateUser") == "ERRO INTERNO")
+ {
+ return false;
+ }
+ int tries = 0;
+ bool flag = false;
+ while (tries < 24 && !flag)
+ {
+ await Task.Delay(5000);
+ tries++;
+ flag = await Get("Data/UserExists") == null;
+ }
+ return flag;
+ }
+
+ private static async Task<bool> DatabaseExists()
+ {
+ return await Get("Data/DataExists") == null;
+ }
+
+ private static async Task<bool> LoginExists()
+ {
+ return await Get("Data/ServerLoginExists") == null;
+ }
+
+ private static async Task<bool> UserExists()
+ {
+ return await Get("Data/UserExists") == null;
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/CustomLinq.cs b/Decompiler/Gestor.Application.Helpers/CustomLinq.cs
new file mode 100644
index 0000000..b07854b
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/CustomLinq.cs
@@ -0,0 +1,55 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using Gestor.Common.Validation;
+using Gestor.Model.Domain.Relatorios;
+
+namespace Gestor.Application.Helpers;
+
+public static class CustomLinq
+{
+ public static List<T> CustomWhere<T>(this List<T> list, string propertyName, string query) where T : class
+ {
+ PropertyInfo pi = typeof(T).GetProperty(propertyName);
+ return list.Where((T x) => pi.GetValue(x).ToString().ToLower()
+ .Contains(query.ToLower())).ToList();
+ }
+
+ public static List<T> CustomWhere<T>(this List<T> list, List<FiltroPersonalizado> property, bool buscaIgual = false) where T : class
+ {
+ if (property == null || property.Count == 0)
+ {
+ return list;
+ }
+ return list.Where((T x) => (from p in property
+ group p by p.Propriedade).ToList().All((IGrouping<string, FiltroPersonalizado> p) => (!p.Any((FiltroPersonalizado s) => s.SemValor)) ? ((!(p.First().Tipo == typeof(DateTime))) ? ((!(p.First().Tipo == typeof(long))) ? ((!(p.First().Tipo == typeof(int))) ? ((!(p.First().Tipo == typeof(decimal))) ? ((!(p.First().Tipo == typeof(Enum))) ? p.Any(delegate(FiltroPersonalizado v)
+ {
+ if (!buscaIgual)
+ {
+ if (typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null)
+ {
+ return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.Propriedade).GetValue(x).ToString()
+ .ToLower()
+ .Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.ValorIncial.ToLower().Trim()));
+ }
+ return false;
+ }
+ return typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.Propriedade).GetValue(x).ToString()
+ .ToLower()
+ .Trim()).Equals(ValidationHelper.AlphanumericAndSpace(v.ValorIncial.ToLower().Trim()));
+ }) : p.Any((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.Propriedade).GetValue(x)).ToLower().Equals(v.ValorIncial.ToLower()))) : p.Any((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (decimal)typeof(T).GetProperty(v.Propriedade).GetValue(x) >= decimal.Parse(v.ValorIncial) && (decimal)typeof(T).GetProperty(v.Propriedade).GetValue(x) <= decimal.Parse(v.ValorFinal))) : p.Any((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (int)typeof(T).GetProperty(v.Propriedade).GetValue(x) >= int.Parse(v.ValorIncial) && (int)typeof(T).GetProperty(v.Propriedade).GetValue(x) <= int.Parse(v.ValorFinal))) : p.Any((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (long)typeof(T).GetProperty(v.Propriedade).GetValue(x) >= long.Parse(v.ValorIncial) && (long)typeof(T).GetProperty(v.Propriedade).GetValue(x) <= long.Parse(v.ValorFinal))) : p.Any((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (DateTime)typeof(T).GetProperty(v.Propriedade).GetValue(x) >= DateTime.Parse(v.ValorIncial) && (DateTime)typeof(T).GetProperty(v.Propriedade).GetValue(x) <= DateTime.Parse(v.ValorFinal).AddDays(1.0).AddSeconds(-1.0))) : p.Any((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) == null || string.IsNullOrWhiteSpace(typeof(T).GetProperty(v.Propriedade)?.GetValue(x).ToString()) || string.IsNullOrEmpty(typeof(T).GetProperty(v.Propriedade)?.GetValue(x).ToString())))).ToList();
+ }
+
+ public static List<T> CustomNot<T>(this List<T> list, List<FiltroPersonalizado> property) where T : class
+ {
+ if (property == null || property.Count == 0)
+ {
+ return list;
+ }
+ return list.Where((T x) => (from p in property
+ group p by p.Propriedade).ToList().All((IGrouping<string, FiltroPersonalizado> p) => (!p.Any((FiltroPersonalizado s) => s.SemValor)) ? ((!(p.First().Tipo == typeof(DateTime))) ? ((!(p.First().Tipo == typeof(long))) ? ((!(p.First().Tipo == typeof(int))) ? ((!(p.First().Tipo == typeof(decimal))) ? ((!(p.First().Tipo == typeof(Enum))) ? p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && !ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.Propriedade).GetValue(x).ToString()
+ .ToLower()
+ .Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.ValorIncial.ToLower().Trim()))) : p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && !ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.Propriedade).GetValue(x)).ToLower().Contains(v.ValorIncial.ToLower()))) : p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (decimal)typeof(T).GetProperty(v.Propriedade).GetValue(x) != decimal.Parse(v.ValorIncial))) : p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (int)typeof(T).GetProperty(v.Propriedade).GetValue(x) != int.Parse(v.ValorIncial))) : p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (long)typeof(T).GetProperty(v.Propriedade).GetValue(x) != long.Parse(v.ValorIncial))) : p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) != null && (DateTime)typeof(T).GetProperty(v.Propriedade).GetValue(x) != DateTime.Parse(v.ValorIncial))) : p.All((FiltroPersonalizado v) => typeof(T).GetProperty(v.Propriedade)?.GetValue(x) == null || string.IsNullOrWhiteSpace(typeof(T).GetProperty(v.Propriedade)?.GetValue(x).ToString())))).ToList();
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/DataGridExtensions.cs b/Decompiler/Gestor.Application.Helpers/DataGridExtensions.cs
new file mode 100644
index 0000000..0ddd601
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/DataGridExtensions.cs
@@ -0,0 +1,83 @@
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Media;
+using Gestor.Common.Validation;
+using Gestor.Model.Common;
+
+namespace Gestor.Application.Helpers;
+
+public static class DataGridExtensions
+{
+ public static T GetVisualChild<T>(Visual parent) where T : Visual
+ {
+ //IL_001a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0020: Expected O, but got Unknown
+ T val = default(T);
+ int childrenCount = VisualTreeHelper.GetChildrenCount((DependencyObject)(object)parent);
+ for (int i = 0; i < childrenCount; i++)
+ {
+ Visual val2 = (Visual)VisualTreeHelper.GetChild((DependencyObject)(object)parent, i);
+ val = ((T)(object)((val2 is T) ? val2 : null)) ?? GetVisualChild<T>(val2);
+ if (val != null)
+ {
+ break;
+ }
+ }
+ return val;
+ }
+
+ public static void EsconderToggles(this DataGrid grid, TipoTela tela, TipoToggle toggles)
+ {
+ //IL_0042: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0048: Expected O, but got Unknown
+ //IL_007a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0081: Expected O, but got Unknown
+ //IL_008f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00c3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ed: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0117: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0141: Unknown result type (might be due to invalid IL or missing references)
+ try
+ {
+ foreach (object item in ((ItemsControl)grid).ItemContainerGenerator.Items)
+ {
+ grid.ScrollIntoView(item, grid.Columns[0]);
+ ((UIElement)grid).UpdateLayout();
+ DataGridRow val = (DataGridRow)((ItemsControl)grid).ItemContainerGenerator.ContainerFromItem(item);
+ if (val == null)
+ {
+ continue;
+ }
+ grid.ScrollIntoView((object)val, grid.Columns[4]);
+ ((UIElement)grid).UpdateLayout();
+ DataGridCellsPresenter visualChild = DataGridExtensions.GetVisualChild<DataGridCellsPresenter>((Visual)(object)val);
+ DataGridCell val2 = (DataGridCell)((ItemsControl)visualChild).ItemContainerGenerator.ContainerFromIndex(0);
+ if (val2 != null && ((object)val2).ToString().Contains(ValidationHelper.GetDescription((Enum)(object)tela)))
+ {
+ if (toggles.HasFlag(TipoToggle.Consultar))
+ {
+ ((UIElement)(DataGridCell)((ItemsControl)visualChild).ItemContainerGenerator.ContainerFromIndex(1)).Visibility = (Visibility)1;
+ }
+ if (toggles.HasFlag(TipoToggle.Incluir))
+ {
+ ((UIElement)(DataGridCell)((ItemsControl)visualChild).ItemContainerGenerator.ContainerFromIndex(2)).Visibility = (Visibility)1;
+ }
+ if (toggles.HasFlag(TipoToggle.Alterar))
+ {
+ ((UIElement)(DataGridCell)((ItemsControl)visualChild).ItemContainerGenerator.ContainerFromIndex(3)).Visibility = (Visibility)1;
+ }
+ if (toggles.HasFlag(TipoToggle.Excluir))
+ {
+ ((UIElement)(DataGridCell)((ItemsControl)visualChild).ItemContainerGenerator.ContainerFromIndex(4)).Visibility = (Visibility)1;
+ }
+ break;
+ }
+ }
+ }
+ catch (Exception)
+ {
+ }
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/Erro.cs b/Decompiler/Gestor.Application.Helpers/Erro.cs
new file mode 100644
index 0000000..485c8c2
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/Erro.cs
@@ -0,0 +1,25 @@
+using System;
+using System.IO;
+using System.Windows;
+using System.Windows.Threading;
+using Gestor.Application.Views.Generic;
+using Gestor.Model.API;
+
+namespace Gestor.Application.Helpers;
+
+public static class Erro
+{
+ public static void RegistrarErro(LogError log, bool abrirTela = true)
+ {
+ string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Gestor.Exceptions.log");
+ string contents = 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}", Environment.NewLine, log.IdFornecedor, log.Fornecedor, log.UsuarioLogado, log.Versao, log.Data, log.IdErro, log.Erro, log.HResult, log.HelpLink, log.Message, log.Source, log.StackTrace, log.Maquina, log.UsuarioMaquina, log.Linha, log.Objeto);
+ File.AppendAllText(path, contents);
+ if (abrirTela)
+ {
+ ((DispatcherObject)Application.Current).Dispatcher.BeginInvoke((DispatcherPriority)4, (Delegate)(Action)delegate
+ {
+ ((Window)new ErrorWindow((TipoErro)log.IdErro)).ShowDialog();
+ });
+ }
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/Funcoes.cs b/Decompiler/Gestor.Application.Helpers/Funcoes.cs
new file mode 100644
index 0000000..8088254
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/Funcoes.cs
@@ -0,0 +1,4086 @@
+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 Agger.Registro;
+using ClosedXML.Excel;
+using CsQuery.ExtensionMethods;
+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.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 Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Helpers;
+
+public static class Funcoes
+{
+ [CompilerGenerated]
+ private sealed class _003CDistinctBy_003Ed__55<TSource, TKey> : IEnumerable<TSource>, IEnumerable, IEnumerator<TSource>, IDisposable, IEnumerator
+ {
+ private int _003C_003E1__state;
+
+ private TSource _003C_003E2__current;
+
+ private int _003C_003El__initialThreadId;
+
+ private IEnumerable<TSource> source;
+
+ public IEnumerable<TSource> _003C_003E3__source;
+
+ private Func<TSource, TKey> keySelector;
+
+ public Func<TSource, TKey> _003C_003E3__keySelector;
+
+ private HashSet<TKey> _003CseenKeys_003E5__2;
+
+ private IEnumerator<TSource> _003C_003E7__wrap2;
+
+ TSource IEnumerator<TSource>.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ object IEnumerator.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ [DebuggerHidden]
+ public _003CDistinctBy_003Ed__55(int _003C_003E1__state)
+ {
+ this._003C_003E1__state = _003C_003E1__state;
+ _003C_003El__initialThreadId = Environment.CurrentManagedThreadId;
+ }
+
+ [DebuggerHidden]
+ void IDisposable.Dispose()
+ {
+ int num = _003C_003E1__state;
+ if (num == -3 || num == 1)
+ {
+ try
+ {
+ }
+ finally
+ {
+ _003C_003Em__Finally1();
+ }
+ }
+ _003CseenKeys_003E5__2 = null;
+ _003C_003E7__wrap2 = null;
+ _003C_003E1__state = -2;
+ }
+
+ private bool MoveNext()
+ {
+ try
+ {
+ switch (_003C_003E1__state)
+ {
+ default:
+ return false;
+ case 0:
+ _003C_003E1__state = -1;
+ _003CseenKeys_003E5__2 = new HashSet<TKey>();
+ _003C_003E7__wrap2 = source.GetEnumerator();
+ _003C_003E1__state = -3;
+ break;
+ case 1:
+ _003C_003E1__state = -3;
+ break;
+ }
+ while (_003C_003E7__wrap2.MoveNext())
+ {
+ TSource current = _003C_003E7__wrap2.Current;
+ if (_003CseenKeys_003E5__2.Add(keySelector(current)))
+ {
+ _003C_003E2__current = current;
+ _003C_003E1__state = 1;
+ return true;
+ }
+ }
+ _003C_003Em__Finally1();
+ _003C_003E7__wrap2 = null;
+ return false;
+ }
+ catch
+ {
+ //try-fault
+ ((IDisposable)this).Dispose();
+ throw;
+ }
+ }
+
+ bool IEnumerator.MoveNext()
+ {
+ //ILSpy generated this explicit interface implementation from .override directive in MoveNext
+ return this.MoveNext();
+ }
+
+ private void _003C_003Em__Finally1()
+ {
+ _003C_003E1__state = -1;
+ if (_003C_003E7__wrap2 != null)
+ {
+ _003C_003E7__wrap2.Dispose();
+ }
+ }
+
+ [DebuggerHidden]
+ void IEnumerator.Reset()
+ {
+ throw new NotSupportedException();
+ }
+
+ [DebuggerHidden]
+ IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator()
+ {
+ _003CDistinctBy_003Ed__55<TSource, TKey> _003CDistinctBy_003Ed__;
+ if (_003C_003E1__state == -2 && _003C_003El__initialThreadId == Environment.CurrentManagedThreadId)
+ {
+ _003C_003E1__state = 0;
+ _003CDistinctBy_003Ed__ = this;
+ }
+ else
+ {
+ _003CDistinctBy_003Ed__ = new _003CDistinctBy_003Ed__55<TSource, TKey>(0);
+ }
+ _003CDistinctBy_003Ed__.source = _003C_003E3__source;
+ _003CDistinctBy_003Ed__.keySelector = _003C_003E3__keySelector;
+ return _003CDistinctBy_003Ed__;
+ }
+
+ [DebuggerHidden]
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return ((IEnumerable<TSource>)this).GetEnumerator();
+ }
+ }
+
+ public static Stopwatch Stopwatch;
+
+ public static DateTime? StartTime;
+
+ public static async Task<bool[]> VerificarPagamento(long id)
+ {
+ bool[] pagamento = new bool[2];
+ if ((await new ParcelaServico().BuscarParcelas(id)).Any((Parcela x) => x.DataRecebimento.HasValue))
+ {
+ pagamento[0] = true;
+ }
+ if ((await new VendedorServico().BuscaRepasse(id)).Any((VendedorParcela x) => x.DataPagamento.HasValue))
+ {
+ pagamento[1] = true;
+ }
+ return pagamento;
+ }
+
+ public static decimal CalculaPagamento(VendedorParcela pagamento, Parcela parcela, decimal comissaoPrevista)
+ {
+ //IL_003b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0041: Invalid comparison between Unknown and I4
+ //IL_00c2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00c8: Invalid comparison between Unknown and I4
+ //IL_0109: Unknown result type (might be due to invalid IL or missing references)
+ //IL_010f: Invalid comparison between Unknown and I4
+ //IL_0129: Unknown result type (might be due to invalid IL or missing references)
+ //IL_012f: Invalid comparison between Unknown and I4
+ decimal num = pagamento.PorcentagemRepasse.GetValueOrDefault();
+ decimal valueOrDefault = pagamento.ValorRepasse.GetValueOrDefault();
+ decimal num2 = parcela.ValorComDesconto;
+ Repasse repasse = pagamento.Repasse;
+ if (repasse != null && (int)repasse.Incidencia.GetValueOrDefault() == 2)
+ {
+ decimal num3 = parcela.Documento.Comissao * parcela.Documento.PremioLiquido * 0.01m;
+ decimal num4 = ((parcela.ValorComissao != 0m) ? (parcela.ValorComissao / num3) : 0m);
+ num2 = parcela.Documento.PremioLiquido * num4;
+ }
+ Repasse repasse2 = pagamento.Repasse;
+ if (repasse2 == null || (int)repasse2.Tipo.GetValueOrDefault() != 1)
+ {
+ num = num2 * pagamento.PorcentagemRepasse.GetValueOrDefault() * 0.01m;
+ }
+ Repasse repasse3 = pagamento.Repasse;
+ if (repasse3 != null && (int)repasse3.Tipo.GetValueOrDefault() == 1)
+ {
+ Repasse repasse4 = pagamento.Repasse;
+ if (repasse4 != null && (int)repasse4.Forma.GetValueOrDefault() == 1 && Recursos.Configuracoes.Any((ConfiguracaoSistema x) => (int)x.Configuracao == 25))
+ {
+ decimal num5 = ((comissaoPrevista == 0m) ? 1m : (parcela.ValorComissao / comissaoPrevista));
+ num *= num5;
+ }
+ }
+ if (!(Math.Abs(num) > Math.Abs(valueOrDefault)))
+ {
+ return num;
+ }
+ return valueOrDefault;
+ }
+
+ public static async Task<Parcela> BaixarComissao(Parcela parcela, List<Parcela> parcelas, List<VendedorParcela> repasses, decimal tolerancia = 2m, bool comissaoAuto = false)
+ {
+ ParcelaServico servico = new ParcelaServico();
+ parcela.ValorComDesconto = ((parcela.ValorComDesconto == 0m && Math.Abs(parcela.ValorComDesconto) < Math.Abs(parcela.ValorComissao)) ? parcela.ValorComissao : parcela.ValorComDesconto);
+ var source = from x in repasses
+ group x by new
+ {
+ Id = ((DomainBase)x.Parcela).Id,
+ vendedor = ((DomainBase)x.Vendedor).Id,
+ tipovendedor = ((DomainBase)x.TipoVendedor).Id
+ };
+ BaseDialogViewModel viewmodel = new BaseDialogViewModel();
+ if (source.Any(g => g.Count() > 1))
+ {
+ Documento documento = parcela.Documento;
+ object obj;
+ if (!string.IsNullOrWhiteSpace((documento != null) ? documento.Apolice : null))
+ {
+ Documento documento2 = parcela.Documento;
+ obj = ((documento2 != null) ? documento2.Proposta : null);
+ }
+ else
+ {
+ Documento documento3 = parcela.Documento;
+ obj = ((documento3 != null) ? documento3.Apolice : null);
+ }
+ string arg = (string)obj;
+ await viewmodel.ShowMessage($"HÁ VENDEDORES DUPLICADOS PARA A PARCELA {parcela.NumeroParcela} DO DOCUMENTO {arg}, BAIXA DE COMISSÃO INTERROMPIDA.{Environment.NewLine}REALIZE A CORREÇÃO DOS VENDEDORES E TENTE NOVAMENTE.");
+ parcela.DataRecebimento = null;
+ parcela.ValorComissao = 0m;
+ parcela.ValorComDesconto = 0m;
+ parcela.Irr = 0m;
+ parcela.Iss = 0m;
+ parcela.Outros = 0m;
+ parcela.Desconto = 0m;
+ return parcela;
+ }
+ DateTime now = GetNetworkTime();
+ if ((int)parcela.SubTipo == 1 && (int)parcela.Documento.TipoRecebimento.GetValueOrDefault() == 1)
+ {
+ decimal num = (parcela.Documento.AdicionalComiss ? (parcela.Documento.PremioLiquido + parcela.Documento.PremioAdicional) : parcela.Documento.PremioLiquido);
+ decimal comissaoPrevista = num * parcela.Documento.Comissao * 0.01m;
+ decimal comissaoRecebida = parcelas.Where((Parcela x) => (int)x.SubTipo == 1 && x.DataRecebimento.HasValue).Sum((Parcela x) => x.ValorComissao);
+ decimal diferenca = Math.Abs(comissaoPrevista) - Math.Abs(comissaoRecebida);
+ bool flag = diferenca <= tolerancia || diferenca < 0.01m;
+ bool baixarProximas = (int)parcela.Documento.TipoRecebimento.GetValueOrDefault() == 1 && flag;
+ bool esgotarParcelas = true;
+ if (baixarProximas && Recursos.Configuracoes.Any((ConfiguracaoSistema c) => (int)c.Configuracao == 54))
+ {
+ Parcela obj2 = parcela;
+ object obj3;
+ if (obj2 == null)
+ {
+ obj3 = null;
+ }
+ else
+ {
+ Documento documento4 = obj2.Documento;
+ if (documento4 == null)
+ {
+ obj3 = null;
+ }
+ else
+ {
+ Controle controle = documento4.Controle;
+ if (controle == null)
+ {
+ obj3 = null;
+ }
+ else
+ {
+ Cliente cliente = controle.Cliente;
+ obj3 = ((cliente != null) ? cliente.Nome : null);
+ }
+ }
+ }
+ if (obj3 == null)
+ {
+ obj3 = string.Empty;
+ }
+ string text = (string)obj3;
+ if (string.IsNullOrEmpty(text))
+ {
+ Documento documento5 = parcela.Documento;
+ int num2;
+ if (documento5 == null)
+ {
+ num2 = 0;
+ }
+ else
+ {
+ Controle controle2 = documento5.Controle;
+ long? obj4;
+ if (controle2 == null)
+ {
+ obj4 = null;
+ }
+ else
+ {
+ Cliente cliente2 = controle2.Cliente;
+ obj4 = ((cliente2 != null) ? new long?(((DomainBase)cliente2).Id) : null);
+ }
+ num2 = ((obj4 > 0) ? 1 : 0);
+ }
+ if (num2 != 0)
+ {
+ Cliente obj5 = await new ClienteServico().BuscarClienteAsync(((DomainBase)parcela.Documento.Controle.Cliente).Id);
+ text = ((obj5 != null) ? obj5.Nome : null) ?? string.Empty;
+ }
+ }
+ if (!string.IsNullOrEmpty(text))
+ {
+ text = ", DO CLIENTE " + text;
+ }
+ Parcela obj6 = parcela;
+ object obj7;
+ if (obj6 == null)
+ {
+ obj7 = null;
+ }
+ else
+ {
+ Documento documento6 = obj6.Documento;
+ obj7 = ((documento6 != null) ? documento6.Apolice : null);
+ }
+ if (obj7 == null)
+ {
+ obj7 = string.Empty;
+ }
+ string text2 = (string)obj7;
+ if (!string.IsNullOrEmpty(text2))
+ {
+ text2 = " - APÓLICE " + text2;
+ }
+ if (parcela.Documento.NumeroParcelas != (decimal)parcela.NumeroParcela)
+ {
+ bool flag2;
+ baixarProximas = (flag2 = await viewmodel.ShowMessage($"AINDA RESTA {diferenca:c}{text}{text2} QUE NÃO SERÁ REPASSADO, CONTINUAR A BAIXA POR ESGOTAMENTO?", "SIM, BAIXAR POR ESGOMENTO", "NÃO"));
+ esgotarParcelas = flag2;
+ }
+ }
+ List<VendedorParcela> list = repasses.Where(delegate(VendedorParcela x)
+ {
+ //IL_002d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0033: Invalid comparison between Unknown and I4
+ if (((DomainBase)x.Parcela).Id == ((DomainBase)parcela).Id)
+ {
+ Repasse repasse4 = x.Repasse;
+ if (repasse4 != null && (int)repasse4.Forma.GetValueOrDefault() == 1)
+ {
+ return !x.DataPagamento.HasValue;
+ }
+ }
+ return false;
+ }).ToList();
+ List<VendedorParcela> demaisRepasses = new List<VendedorParcela>();
+ Parcela proximaParcela = ((IEnumerable<Parcela>)parcelas).FirstOrDefault((Func<Parcela, bool>)((Parcela x) => (int)x.SubTipo == 1 && x.NumeroParcela == parcela.NumeroParcela + 1));
+ Parcela parcela2 = parcela;
+ ExtensionMethods.ForEach(from g in list
+ group g by new
+ {
+ Id = ((DomainBase)g.Parcela).Id,
+ vendedor = ((DomainBase)g.Vendedor).Id,
+ tipovendedor = ((DomainBase)g.TipoVendedor).Id
+ }, x =>
+ {
+ //IL_00ba: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00bf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00d0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00dc: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ed: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ff: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0110: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0121: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0132: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0143: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0155: Expected O, but got Unknown
+ if (!x.First().CoCorretagem)
+ {
+ decimal valueOrDefault = x.First().ValorRepasse.GetValueOrDefault();
+ decimal num4 = CalculaPagamento(x.First(), parcela2, comissaoPrevista);
+ x.First().ValorRepasse = ((Math.Abs(valueOrDefault) > Math.Abs(num4)) ? num4 : valueOrDefault);
+ x.First().DataPrePagamento = parcela2.DataRecebimento;
+ if ((!esgotarParcelas || !(Math.Abs(comissaoPrevista) - Math.Abs(comissaoRecebida) <= Math.Abs(tolerancia))) && proximaParcela != null)
+ {
+ VendedorParcela item = new VendedorParcela
+ {
+ Repasse = x.First().Repasse,
+ Parcela = proximaParcela,
+ Documento = parcela2.Documento,
+ ValorRepasse = valueOrDefault - num4,
+ Vendedor = x.First().Vendedor,
+ ValorTotal = x.First().ValorTotal,
+ PorcentagemRepasse = x.First().PorcentagemRepasse,
+ TipoVendedor = x.First().TipoVendedor,
+ CoCorretagem = x.First().CoCorretagem
+ };
+ demaisRepasses.Add(item);
+ }
+ }
+ });
+ if (demaisRepasses.Count > 0)
+ {
+ list.AddRange(demaisRepasses);
+ }
+ if (!(await servico.SaveRange(list)))
+ {
+ await MostrarErro((TipoErro)24);
+ return parcela;
+ }
+ Parcela val = await servico.Save(parcela, parcelas, null, abrirTela: false);
+ parcela = val;
+ if (!servico.Sucesso)
+ {
+ await MostrarErro((TipoErro)24);
+ return parcela;
+ }
+ if (baixarProximas)
+ {
+ List<Parcela> list2 = parcelas.Where((Parcela x) => !x.DataRecebimento.HasValue && (int)x.SubTipo == 1).ToList();
+ List<VendedorParcela> baixarRepasses = new List<VendedorParcela>();
+ list2.ForEach(delegate(Parcela x)
+ {
+ x.Documento = parcela.Documento;
+ x.DataRecebimento = parcela.DataRecebimento;
+ x.DataCredito = parcela.DataRecebimento;
+ x.ValorRealizado = 0m;
+ x.ValorComissao = 0m;
+ x.ValorComDesconto = 0m;
+ x.Irr = 0m;
+ x.Iss = 0m;
+ List<VendedorParcela> list4 = repasses.Where(delegate(VendedorParcela p)
+ {
+ //IL_002d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0033: Invalid comparison between Unknown and I4
+ //IL_004b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0051: Invalid comparison between Unknown and I4
+ if (((DomainBase)p.Parcela).Id == ((DomainBase)x).Id)
+ {
+ Repasse repasse2 = p.Repasse;
+ if (repasse2 != null && (int)repasse2.Forma.GetValueOrDefault() == 1)
+ {
+ Repasse repasse3 = p.Repasse;
+ if (repasse3 == null)
+ {
+ return true;
+ }
+ return (int)repasse3.Tipo.GetValueOrDefault() != 3;
+ }
+ }
+ return false;
+ }).ToList();
+ list4.ForEach(delegate(VendedorParcela p)
+ {
+ p.Parcela = x;
+ p.Documento = parcela.Documento;
+ p.DataPrePagamento = now;
+ decimal? valorRepasse = p.ValorRepasse;
+ decimal num3 = tolerancia;
+ p.ValorRepasse = (((valorRepasse.GetValueOrDefault() > num3) & valorRepasse.HasValue) ? new decimal?(default(decimal)) : p.ValorRepasse);
+ });
+ baixarRepasses.AddRange(list4);
+ });
+ await servico.SaveRange(parcelas);
+ if (!servico.Sucesso)
+ {
+ await MostrarErro((TipoErro)24);
+ return parcela;
+ }
+ if (!(await servico.SaveRange(baixarRepasses)))
+ {
+ await MostrarErro((TipoErro)24);
+ return parcela;
+ }
+ }
+ }
+ else
+ {
+ List<VendedorParcela> list3 = repasses.Where(delegate(VendedorParcela x)
+ {
+ //IL_004a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0050: Invalid comparison between Unknown and I4
+ if (((DomainBase)x.Parcela).Id == ((DomainBase)parcela).Id && !x.DataPagamento.HasValue)
+ {
+ if (x == null)
+ {
+ return false;
+ }
+ Repasse repasse = x.Repasse;
+ return (int)((repasse != null) ? repasse.Forma : null).GetValueOrDefault() == 1;
+ }
+ return false;
+ }).ToList();
+ list3.ForEach(delegate(VendedorParcela x)
+ {
+ x.DataPrePagamento = parcela.DataRecebimento;
+ x.ValorRepasse = CalculaRepasse(x.Repasse, parcela, apolice: false);
+ });
+ parcela = await servico.Save(parcela, parcelas, list3, abrirTela: false);
+ if (!servico.Sucesso)
+ {
+ await MostrarErro((TipoErro)24);
+ return parcela;
+ }
+ }
+ if (!comissaoAuto)
+ {
+ RegistrarLogBaixa(((DomainBase)parcela.Documento).Id, now);
+ }
+ return parcela;
+ }
+
+ private static async void RegistrarLogBaixa(long id, DateTime now)
+ {
+ ApoliceServico apoliceServico = new ApoliceServico();
+ ParcelaServico parcelaServico = new ParcelaServico();
+ VendedorServico vendedoresServico = new VendedorServico();
+ Documento apolice = await apoliceServico.BuscarApoliceAsync(id);
+ Documento val = apolice;
+ val.Parcelas = await parcelaServico.BuscarParcelasAsync(((DomainBase)apolice).Id);
+ List<VendedorParcela> list = await vendedoresServico.BuscaRepasse(((DomainBase)apolice).Id);
+ foreach (Parcela parcela in apolice.Parcelas)
+ {
+ foreach (VendedorParcela item in list)
+ {
+ if (((DomainBase)item.Parcela).Id == ((DomainBase)parcela).Id)
+ {
+ if (parcela.Vendedores == null)
+ {
+ parcela.Vendedores = new ObservableCollection<VendedorParcela>();
+ }
+ parcela.Vendedores.Add(item);
+ }
+ }
+ }
+ IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
+ RegistroLog val2 = new RegistroLog
+ {
+ Acao = (TipoAcao)1,
+ Usuario = Recursos.Usuario,
+ DataHora = now,
+ Descricao = JsonConvert.SerializeObject((object)apolice, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ }),
+ EntidadeId = ((DomainBase)apolice).Id,
+ Tela = (TipoTela)2,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = hostEntry.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString()
+ };
+ UnitOfWork commited = Instancia.Commited;
+ try
+ {
+ commited.RegistroLogRepository.SaveOrUpdate(val2);
+ ((GenericUnitOfWork)commited).Commit();
+ }
+ finally
+ {
+ ((IDisposable)commited)?.Dispose();
+ }
+ }
+
+ public static async Task MostrarErro(TipoErro erro)
+ {
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000f: Unknown result type (might be due to invalid IL or missing references)
+ await ((DispatcherObject)Application.Current).Dispatcher.BeginInvoke((DispatcherPriority)4, (Delegate)(Action)delegate
+ {
+ //IL_0001: Unknown result type (might be due to invalid IL or missing references)
+ ((Window)new ErrorWindow(erro, fecharSistema: true)).ShowDialog();
+ });
+ }
+
+ public static async Task RecusarApolice(Documento documento, string motivo, bool estorno)
+ {
+ ApoliceServico servico = new ApoliceServico();
+ CriticaApoliceServico criticaServico = new CriticaApoliceServico();
+ string label = ((documento.Tipo == 0 && string.IsNullOrEmpty(documento.Apolice)) ? "PROPOSTA RECUSADA" : ((documento.Tipo == 0 && !string.IsNullOrEmpty(documento.Apolice)) ? "APÓLICE RECUSADA" : "ENDOSSO RECUSADO"));
+ if (!string.IsNullOrWhiteSpace(motivo))
+ {
+ documento.Observacao = $"{Recursos.Usuario.Nome}, ID: {((DomainBase)Recursos.Usuario).Id}, {GetNetworkTime():g}{Environment.NewLine}RECUSA: {motivo}{Environment.NewLine}{Environment.NewLine}{documento.Observacao}";
+ }
+ bool flag;
+ if (documento.Tipo == 0)
+ {
+ await servico.Save(documento, updateParcelas: false, criarParcelas: false);
+ Controle controle = await servico.BuscarControleAsync(((DomainBase)documento.Controle).Id);
+ if (((DomainBase)controle).Id == 0L)
+ {
+ return;
+ }
+ foreach (Documento documento2 in controle.Documentos)
+ {
+ if (!documento2.NegocioCorretora.HasValue)
+ {
+ documento2.NegocioCorretora = (NegocioCorretora)((documento2.Negocio.HasValue && (int)documento2.Negocio.GetValueOrDefault() == 1) ? 1 : 0);
+ }
+ documento2.Situacao = (TipoSeguro)7;
+ documento2.Apolice = "RECUSADA";
+ if (!(await servico.BaixarParcelasCancelamento(documento2, estorno)))
+ {
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ }
+ }
+ flag = await servico.UpdateRange(controle);
+ }
+ else
+ {
+ if (!documento.NegocioCorretora.HasValue)
+ {
+ documento.NegocioCorretora = (NegocioCorretora)((documento.Negocio.HasValue && (int)documento.Negocio.GetValueOrDefault() == 1) ? 1 : 0);
+ }
+ documento.Situacao = (TipoSeguro)7;
+ documento.Apolice = "RECUSADA";
+ documento.Endosso = "RECUSADA";
+ if (!(await servico.BaixarParcelasCancelamento(documento, estorno)))
+ {
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ }
+ await servico.Save(documento, updateParcelas: false, criarParcelas: false);
+ if (!servico.Sucesso)
+ {
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ }
+ if (!servico.Sucesso)
+ {
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ }
+ flag = await InativarItens(((DomainBase)documento).Id, ((DomainBase)documento.Controle.Ramo).Id, delete: false);
+ if (!flag)
+ {
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ }
+ }
+ if (!flag)
+ {
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ }
+ List<CriticaApolice> list = await criticaServico.BuscarCritica(((DomainBase)documento).Id);
+ if (list != null)
+ {
+ foreach (CriticaApolice item in list)
+ {
+ item.Critica = true;
+ await criticaServico.Save(item);
+ }
+ }
+ Gestor.Application.Actions.Actions.AcessaTela?.Invoke((TipoTela)21, "");
+ ToggleSnackBar(label + " COM SUCESSO");
+ }
+
+ public static void ToggleSnackBar(string message, bool active = true)
+ {
+ ((ContentControl)App.SnackBar.Message).Content = message;
+ App.SnackBar.IsActive = active;
+ if (active)
+ {
+ Task.Factory.StartNew(CloseSlackBar);
+ }
+ }
+
+ private static void CloseSlackBar()
+ {
+ Thread.Sleep(5000);
+ Dispatcher dispatcher = ((DispatcherObject)App.ProgressRing).Dispatcher;
+ if (dispatcher != null)
+ {
+ dispatcher.BeginInvoke((DispatcherPriority)4, (Delegate)(Action)delegate
+ {
+ ToggleSnackBar("", active: false);
+ });
+ }
+ }
+
+ public static decimal CalculaRepasse(Repasse repasse, Parcela parcela, bool apolice = true)
+ {
+ //IL_0018: Unknown result type (might be due to invalid IL or missing references)
+ //IL_001e: Invalid comparison between Unknown and I4
+ //IL_00e9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ef: Invalid comparison between Unknown and I4
+ //IL_0036: Unknown result type (might be due to invalid IL or missing references)
+ //IL_003c: Invalid comparison between Unknown and I4
+ //IL_0042: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0048: Invalid comparison between Unknown and I4
+ //IL_010b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0111: Invalid comparison between Unknown and I4
+ //IL_0170: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0176: Invalid comparison between Unknown and I4
+ //IL_018e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0194: Invalid comparison between Unknown and I4
+ //IL_01ca: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01d0: Invalid comparison between Unknown and I4
+ //IL_01e9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01ef: Invalid comparison between Unknown and I4
+ //IL_0280: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0286: Invalid comparison between Unknown and I4
+ //IL_0289: Unknown result type (might be due to invalid IL or missing references)
+ //IL_028f: Invalid comparison between Unknown and I4
+ //IL_02a0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02a6: Invalid comparison between Unknown and I4
+ if (repasse == null)
+ {
+ return 0m;
+ }
+ bool flag = (int)parcela.Documento.NegocioCorretora.GetValueOrDefault() == 1;
+ decimal num2;
+ decimal num3;
+ decimal num;
+ if (apolice && (int)parcela.Documento.TipoRecebimento.GetValueOrDefault() != 2 && (int)parcela.SubTipo == 1)
+ {
+ num = (parcela.Documento.AdicionalComiss ? (parcela.Documento.PremioLiquido + parcela.Documento.PremioAdicional) : parcela.Documento.PremioLiquido);
+ num2 = (parcela.Documento.AdicionalComiss ? (parcela.Documento.PremioLiquido + parcela.Documento.PremioAdicional) : parcela.Documento.PremioLiquido);
+ num3 = parcela.Documento.Comissao * 0.01m;
+ }
+ else
+ {
+ decimal num4 = (((int)parcela.Documento.TipoRecebimento.GetValueOrDefault() == 2) ? parcela.ValorLiquidoFatura : parcela.Valor);
+ num = (((int)repasse.Incidencia.GetValueOrDefault() == 2) ? num4 : ((parcela.ValorComDesconto == 0m) ? num4 : parcela.ValorComDesconto));
+ num2 = num;
+ num3 = ((parcela.ValorComDesconto == 0m) ? (parcela.Comissao * 0.01m) : 1m);
+ }
+ num = (((int)repasse.Incidencia.GetValueOrDefault() == 2) ? num : (num * num3));
+ num = (((int)repasse.Tipo.GetValueOrDefault() == 1) ? num : (num * (flag ? repasse.ValorRenovacao : repasse.ValorNovo) * 0.01m));
+ decimal num5 = (((int)repasse.Incidencia.GetValueOrDefault() == 2) ? num2 : (num2 * num3));
+ decimal num6;
+ if ((int)repasse.Tipo.GetValueOrDefault() == 1)
+ {
+ num6 = (flag ? repasse.ValorRenovacao : repasse.ValorNovo);
+ if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => (int)x.Configuracao == 24) && parcela.Valor < 0m)
+ {
+ num6 = -num6;
+ }
+ }
+ else
+ {
+ num6 = num5 * (flag ? repasse.ValorRenovacao : repasse.ValorNovo) * 0.01m;
+ }
+ if ((int)parcela.Documento.TipoRecebimento.GetValueOrDefault() != 2 && (int)parcela.SubTipo == 1 && (int)parcela.Documento.TipoEndosso.GetValueOrDefault() != 2)
+ {
+ if (Math.Abs(num6) > Math.Abs(num))
+ {
+ new BaseDialogViewModel().ShowMessage("OS VALORES DE REPASSE ULTRAPASSARAM O VALOR DE COMISSÃO FECHADA. REVEJA OS VALORES.");
+ }
+ if (!(Math.Abs(num6) > Math.Abs(num)))
+ {
+ return num6;
+ }
+ return num;
+ }
+ if (!(parcela.ValorComDesconto != 0m) || !(Math.Abs(num6) > Math.Abs(parcela.ValorComDesconto)) || !Recursos.Configuracoes.All((ConfiguracaoSistema x) => (int)x.Configuracao != 15))
+ {
+ return num6;
+ }
+ return parcela.ValorComDesconto;
+ }
+
+ public static async Task<Parcela> ExcluirBaixa(Parcela parcela, List<VendedorParcela> repasses, List<Parcela> parcelas = null)
+ {
+ ParcelaServico servico = new ParcelaServico();
+ if ((int)parcela.SubTipo == 1 && (int)parcela.Documento.TipoRecebimento.GetValueOrDefault() == 1)
+ {
+ List<VendedorParcela> source = repasses.Where(delegate(VendedorParcela x)
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000c: Invalid comparison between Unknown and I4
+ //IL_0023: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0029: Invalid comparison between Unknown and I4
+ if ((int)x.Parcela.SubTipo == 1)
+ {
+ Repasse repasse4 = x.Repasse;
+ if (repasse4 != null && (int)repasse4.Forma.GetValueOrDefault() == 1)
+ {
+ if (((DomainBase)x.Parcela).Id != ((DomainBase)parcela).Id)
+ {
+ return !x.DataPrePagamento.HasValue;
+ }
+ return true;
+ }
+ }
+ return false;
+ }).ToList();
+ decimal comiss = (parcela.Documento.PremioLiquido + (parcela.Documento.AdicionalComiss ? parcela.Documento.PremioAdicional : 0m)) * parcela.Documento.Comissao * 0.01m;
+ List<VendedorParcela> refazerRepasses = (from x in source
+ group x by ((DomainBase)x.Vendedor).Id).Select((Func<IGrouping<long, VendedorParcela>, VendedorParcela>)delegate(IGrouping<long, VendedorParcela> x)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0016: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0027: Unknown result type (might be due to invalid IL or missing references)
+ //IL_003d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0067: Unknown result type (might be due to invalid IL or missing references)
+ //IL_006d: Invalid comparison between Unknown and I4
+ //IL_013e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_014f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0160: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0171: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0183: Expected O, but got Unknown
+ VendedorParcela val2 = new VendedorParcela
+ {
+ Repasse = x.First().Repasse,
+ Parcela = parcela,
+ Documento = parcela.Documento
+ };
+ VendedorParcela obj = x.First();
+ decimal? valorTotal;
+ if (obj != null)
+ {
+ Repasse repasse3 = obj.Repasse;
+ if ((int)((repasse3 != null) ? repasse3.Tipo : null).GetValueOrDefault() == 3)
+ {
+ valorTotal = x.First().ValorRepasse;
+ goto IL_0139;
+ }
+ }
+ VendedorParcela obj2 = x.First();
+ if (obj2 == null || !obj2.ValorTotal.HasValue)
+ {
+ goto IL_00d5;
+ }
+ VendedorParcela obj3 = x.First();
+ decimal? valorTotal2;
+ if (obj3 != null)
+ {
+ valorTotal2 = obj3.ValorTotal;
+ if ((valorTotal2.GetValueOrDefault() == default(decimal)) & valorTotal2.HasValue)
+ {
+ goto IL_00d5;
+ }
+ }
+ VendedorParcela obj4 = x.First();
+ valorTotal = ((obj4 != null) ? obj4.ValorTotal : null);
+ goto IL_0139;
+ IL_0139:
+ val2.ValorTotal = valorTotal;
+ val2.Vendedor = x.First().Vendedor;
+ val2.PorcentagemRepasse = x.First().PorcentagemRepasse;
+ val2.TipoVendedor = x.First().TipoVendedor;
+ val2.CoCorretagem = x.First().CoCorretagem;
+ return val2;
+ IL_00d5:
+ decimal value = comiss;
+ valorTotal2 = x.First().PorcentagemRepasse;
+ valorTotal = (decimal?)value * valorTotal2 * (decimal?)0.01m;
+ goto IL_0139;
+ }).ToList();
+ List<Parcela> parcelasAnteriores = ((parcelas != null) ? parcelas.Where((Parcela x) => (int)x.SubTipo == 1 && x.NumeroParcela < parcela.NumeroParcela).ToList() : new List<Parcela>());
+ refazerRepasses.ForEach(delegate(VendedorParcela y)
+ {
+ y.ValorRepasse = y.ValorTotal - repasses.Where(delegate(VendedorParcela x)
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000c: Invalid comparison between Unknown and I4
+ //IL_0026: Unknown result type (might be due to invalid IL or missing references)
+ //IL_002c: Invalid comparison between Unknown and I4
+ if ((int)x.Parcela.SubTipo == 1)
+ {
+ Repasse repasse2 = x.Repasse;
+ if (repasse2 != null && (int)repasse2.Forma.GetValueOrDefault() == 1 && ((DomainBase)x.Vendedor).Id == ((DomainBase)y.Vendedor).Id)
+ {
+ return parcelasAnteriores.Select((Parcela z) => ((DomainBase)z).Id).ToList().Contains(((DomainBase)x.Parcela).Id);
+ }
+ }
+ return false;
+ }).Sum((VendedorParcela x) => x.ValorRepasse);
+ });
+ List<Parcela> demaisParcelas3 = ((parcelas != null) ? parcelas.Where((Parcela x) => (int)x.SubTipo == 1 && x.NumeroParcela > parcela.NumeroParcela).ToList() : new List<Parcela>());
+ demaisParcelas3.Add(parcela);
+ List<VendedorParcela> repasses2 = repasses.Where(delegate(VendedorParcela x)
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000c: Invalid comparison between Unknown and I4
+ //IL_0023: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0029: Invalid comparison between Unknown and I4
+ if ((int)x.Parcela.SubTipo == 1)
+ {
+ Repasse repasse = x.Repasse;
+ if (repasse != null && (int)repasse.Forma.GetValueOrDefault() == 1)
+ {
+ if (x.Parcela.NumeroParcela < parcela.NumeroParcela)
+ {
+ return !x.DataPrePagamento.HasValue;
+ }
+ return true;
+ }
+ }
+ return false;
+ }).ToList();
+ if (!(await servico.DeletePagamentoRange(repasses2)))
+ {
+ await MostrarErro((TipoErro)191);
+ return parcela;
+ }
+ if (!(await servico.SaveRange(refazerRepasses)))
+ {
+ await MostrarErro((TipoErro)191);
+ return parcela;
+ }
+ demaisParcelas3 = demaisParcelas3.Where((Parcela dParcela) => dParcela.ValorComissao != 0m || dParcela.ValorComissao != 0m || dParcela.DataRecebimento.HasValue || dParcela.DataCredito.HasValue || dParcela.ValorRealizado != 0m).ToList();
+ if (demaisParcelas3 != null && demaisParcelas3.Count > 0)
+ {
+ demaisParcelas3.ForEach(delegate(Parcela dParcela)
+ {
+ dParcela.Documento = parcela.Documento;
+ dParcela.ValorComissao = 0m;
+ dParcela.ValorComDesconto = 0m;
+ dParcela.DataRecebimento = null;
+ dParcela.DataCredito = null;
+ dParcela.ValorRealizado = 0m;
+ });
+ demaisParcelas3 = await servico.UpdateRange(demaisParcelas3);
+ if (!servico.Sucesso)
+ {
+ await MostrarErro((TipoErro)191);
+ return parcela;
+ }
+ parcela = ((IEnumerable<Parcela>)demaisParcelas3).FirstOrDefault((Func<Parcela, bool>)((Parcela x) => ((DomainBase)x).Id == ((DomainBase)parcela).Id));
+ }
+ }
+ else
+ {
+ List<VendedorParcela> list = repasses.Where((VendedorParcela x) => ((DomainBase)x.Parcela).Id == ((DomainBase)parcela).Id && !x.DataPagamento.HasValue).ToList();
+ list.ForEach(delegate(VendedorParcela x)
+ {
+ x.DataPrePagamento = null;
+ x.ValorRepasse = x.ValorTotal ?? CalculaPagamento(x, x.Parcela, 0m);
+ });
+ parcela.ValorComissao = 0m;
+ parcela.ValorComDesconto = 0m;
+ parcela.DataRecebimento = null;
+ parcela.DataCredito = null;
+ parcela.ValorRealizado = 0m;
+ parcela = await servico.Save(parcela, parcelas, list, abrirTela: false);
+ if (!servico.Sucesso)
+ {
+ await MostrarErro((TipoErro)191);
+ return parcela;
+ }
+ }
+ ApoliceServico apoliceServico = new ApoliceServico();
+ ParcelaServico parcelaServico = new ParcelaServico();
+ VendedorServico vendedoresServico = new VendedorServico();
+ if (parcela != null)
+ {
+ Documento apolice = await apoliceServico.BuscarApoliceAsync(((DomainBase)parcela.Documento).Id);
+ Documento val = apolice;
+ val.Parcelas = await parcelaServico.BuscarParcelasAsync(((DomainBase)apolice).Id);
+ List<VendedorParcela> list2 = await vendedoresServico.BuscaRepasse(((DomainBase)apolice).Id);
+ foreach (Parcela parcela2 in apolice.Parcelas)
+ {
+ foreach (VendedorParcela item in list2)
+ {
+ if (((DomainBase)item.Parcela).Id == ((DomainBase)parcela2).Id)
+ {
+ if (parcela2.Vendedores == null)
+ {
+ parcela2.Vendedores = new ObservableCollection<VendedorParcela>();
+ }
+ parcela2.Vendedores.Add(item);
+ }
+ }
+ }
+ IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
+ RegistroLog registroLog = new RegistroLog
+ {
+ Acao = (TipoAcao)2,
+ Usuario = Recursos.Usuario,
+ DataHora = GetNetworkTime(),
+ Descricao = JsonConvert.SerializeObject((object)apolice, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ }),
+ EntidadeId = ((DomainBase)apolice).Id,
+ Tela = (TipoTela)2,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = hostEntry.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString()
+ };
+ await Task.Run(delegate
+ {
+ UnitOfWork commited = Instancia.Commited;
+ try
+ {
+ commited.RegistroLogRepository.SaveOrUpdate(registroLog);
+ ((GenericUnitOfWork)commited).Commit();
+ }
+ finally
+ {
+ ((IDisposable)commited)?.Dispose();
+ }
+ });
+ }
+ return parcela;
+ }
+
+ public static void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
+ {
+ //IL_0001: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ DatePicker val = (DatePicker)sender;
+ val.Text = ValidationHelper.FormatDate(val.Text);
+ }
+
+ public static void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e)
+ {
+ //IL_0001: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0007: Invalid comparison between Unknown and I4
+ //IL_000b: Unknown result type (might be due to invalid IL or missing references)
+ if ((int)e.Key == 6)
+ {
+ ((DatePicker)sender).Text = GetNetworkTime().Date.ToString("dd/MM/yyyy");
+ }
+ }
+
+ public static async Task OrganizarDocumentos(long id)
+ {
+ ApoliceServico servico = new ApoliceServico();
+ Controle val = await servico.BuscarControleAsync(id);
+ int ordem = 1;
+ (from x in val.Documentos
+ where !x.Excluido
+ orderby x.Vigencia1
+ select x).ToList().ForEach(delegate(Documento x)
+ {
+ if (x.Tipo == 0)
+ {
+ x.Ordem = 0;
+ }
+ else
+ {
+ x.Ordem = ordem;
+ ordem++;
+ }
+ });
+ await servico.UpdateRange(val);
+ }
+
+ public static async Task<bool> ReativarItens(List<long> ids)
+ {
+ ItemServico servico = new ItemServico();
+ List<Item> list = await servico.BuscarItems(ids);
+ list.ForEach(delegate(Item x)
+ {
+ x.Substituido = null;
+ x.Cancelado = false;
+ x.Status = x.StatusInclusao;
+ });
+ await servico.SaveRange(list);
+ return servico.Sucesso;
+ }
+
+ public static async Task<bool> InativarItens(long id, long ramo, bool delete = true)
+ {
+ ItemServico servico = new ItemServico();
+ ObservableCollection<Item> itens = await servico.BuscarItens(id);
+ if (!(await ReativarItens((from x in itens
+ where x.Substituicao.HasValue
+ select x.Substituicao.Value).ToList())))
+ {
+ return false;
+ }
+ if (delete)
+ {
+ await servico.DeleteRange(itens.ToList(), ramo);
+ }
+ else
+ {
+ itens.ToList().ForEach(delegate(Item x)
+ {
+ x.Cancelado = true;
+ });
+ await servico.SaveRange(itens.ToList());
+ }
+ return servico.Sucesso;
+ }
+
+ public static string ExportarHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "")
+ {
+ string newValue = $"DATA DE EMISSÃO DO RELATÓRIO EM {GetNetworkTime():G}";
+ if (tipo.Inicio != DateTime.MinValue && tipo.Nome != "RELATÓRIO DE CLIENTE")
+ {
+ newValue = $"PERÍODO DE {tipo.Inicio:d} ATÉ {tipo.Fim:d}. DATA DE EMISSÃO DO RELATÓRIO EM {GetNetworkTime():G}";
+ }
+ string newValue2 = ((!search) ? "<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' crossorigin='anonymous'>" : "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>");
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append(Resources.RelatorioTemplate.Replace("{style}", newValue2).Replace("Orientation", orientation).Replace("{NomeRelatorio}", Recursos.Empresa.NomeSocial + " - " + tipo.Nome)
+ .Replace("{EmissaoRelatorio}", newValue)
+ .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 newValue = $"DATA DE EMISSÃO DO RELATÓRIO EM {GetNetworkTime():G}";
+ if (tipo.Inicio != DateTime.MinValue && tipo.Nome != "RELATÓRIO DE CLIENTE")
+ {
+ newValue = $"PERÍODO DE {tipo.Inicio:d} ATÉ {tipo.Fim:d}. DATA DE EMISSÃO DO RELATÓRIO EM {GetNetworkTime():G}";
+ }
+ string newValue2 = ((!search) ? "<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' crossorigin='anonymous'>" : "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>");
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append(Resources.RelatorioMultipleTemplate.Replace("{style}", newValue2).Replace("Orientation", orientation).Replace("{NomeRelatorio}", Recursos.Empresa.NomeSocial + " - " + tipo.Nome)
+ .Replace("{EmissaoRelatorio}", newValue)
+ .Replace("{Grafico}", grafico)
+ .Replace("{DadosRelatorio}", dados));
+ return stringBuilder.ToString();
+ }
+
+ public static string CriarRecibo(Vendedor vendedor, decimal valor, Filtros filtro, bool segundavia)
+ {
+ string text = (segundavia ? " acima listados" : $" no periodo de {filtro.Inicio:d} até {filtro.Fim:d}");
+ string text2 = "CPF";
+ if (vendedor.Documento != null && ValidationHelper.OnlyNumber(vendedor.Documento).Length > 12)
+ {
+ text2 = "CNPJ";
+ }
+ return $" <div class='card'>\r\n <h5 class='card-header'>RECIBO DE PAGAMENTO</h5>\r\n <div class='card-body'>\r\n <h5 class='card-title'>Declaração de recebimento de Comissão</h5>\r\n <p class='card-text'>Eu {vendedor.Nome}, portador(a) do {text2} {vendedor.Documento} declaro que recebi de {Recursos.Empresa.Nome} o valor de {valor:c} referente a comissão dos seguros{text}.</p>\r\n\r\n <p class='card-text'>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.</p>\r\n\r\n <p class='card-text'>_____________________________________________________________ </br> {GetNetworkTime().Date:d}</p>\r\n </div>\r\n </div>";
+ }
+
+ public static string CreateCard(string title, string body, bool pageBreak = false)
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append(pageBreak ? "<div class='card p-0' style='page-break-after:always;'>" : "<div class='card p-0'>");
+ stringBuilder.Append("<div class='card-body'>");
+ stringBuilder.Append("<h5 class='card-title'>" + title + "</h5>");
+ stringBuilder.Append(body);
+ stringBuilder.Append("</div>");
+ stringBuilder.Append("</div>");
+ return stringBuilder.ToString();
+ }
+
+ public static async Task<string> GenerateTableSintetic(List<SinteticModel> sintetic, int fontSize = 0)
+ {
+ if (sintetic == null || sintetic.Count == 0)
+ {
+ return "";
+ }
+ string classSize = ((fontSize == 0) ? "" : $"fs-{fontSize}'");
+ return await Task.Run(delegate
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder headerContent = new StringBuilder();
+ StringBuilder stringBuilder3 = new StringBuilder();
+ StringBuilder content = new StringBuilder();
+ sintetic.ForEach(delegate(SinteticModel x)
+ {
+ headerContent.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", classSize).Replace("{FontWeight}", "fw-bold")
+ .Replace("{Content}", x.Hint));
+ content.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", classSize).Replace("{FontWeight}", "")
+ .Replace("{Content}", (x.Value == null) ? "" : x.Value.ToString()));
+ });
+ stringBuilder2.Append(Resources.RowTemplate.Replace("{Content}", headerContent.ToString()).Replace("{Color}", ""));
+ stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", content.ToString()).Replace("{Color}", ""));
+ stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder2.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", ""));
+ return stringBuilder.ToString();
+ });
+ }
+
+ public static async Task<string> GenerateTableSintetic(List<SinteticModelList> sintetic, int fontSize = 0)
+ {
+ if (sintetic == null || sintetic.Count == 0)
+ {
+ return "";
+ }
+ string classSize = ((fontSize == 0) ? "" : $"fs-{fontSize}'");
+ return await Task.Run(delegate
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder headerContent = new StringBuilder();
+ StringBuilder stringBuilder3 = new StringBuilder();
+ sintetic.ForEach(delegate(SinteticModelList x)
+ {
+ headerContent.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", classSize).Replace("{FontWeight}", "fw-bold")
+ .Replace("{Content}", x.Hint));
+ });
+ stringBuilder2.Append(Resources.RowTemplate.Replace("{Content}", headerContent.ToString()).Replace("{Color}", ""));
+ for (int i = 0; i < sintetic.First().Value.Count; i++)
+ {
+ StringBuilder stringBuilder4 = new StringBuilder();
+ bool flag = false;
+ foreach (SinteticModelList item in sintetic)
+ {
+ flag = flag || (item.Value[0] != null && item.Value[i].ToString() == "TOTAL");
+ stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", classSize).Replace("{FontWeight}", flag ? "fw-bold" : "")
+ .Replace("{Content}", $"{item.Value[i]}"));
+ }
+ stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", ""));
+ }
+ stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder2.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", ""));
+ return stringBuilder.ToString();
+ });
+ }
+
+ public static async Task<string> GenerateTable<T>(List<T> analitico, List<string> colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null)
+ {
+ if (analitico == null)
+ {
+ return "";
+ }
+ if (analitico.Count == 0)
+ {
+ return "";
+ }
+ int num = 0;
+ if (config != null)
+ {
+ num = config.TamanhoFonte;
+ }
+ string classSize = ((num == 0) ? "" : $"fs-{num}'");
+ return await Task.Run(delegate
+ {
+ //IL_0112: Unknown result type (might be due to invalid IL or missing references)
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder rowContent = new StringBuilder();
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties = type.GetProperties();
+ int num2 = 0;
+ PropertyInfo[] array = properties;
+ foreach (PropertyInfo propertyInfo in array)
+ {
+ if (!(propertyInfo.Name == "ValidationEvent"))
+ {
+ object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj != null)
+ {
+ string description = ((DescriptionAttribute)obj).Description;
+ if ((!propertyName || !colunasOcultas.Contains(propertyInfo.Name)) && (propertyName || !colunasOcultas.Contains(description)))
+ {
+ object obj2 = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), inherit: true).FirstOrDefault();
+ string text = "";
+ if (obj2 != null)
+ {
+ text = ((TipoAttribute)obj2).Description;
+ }
+ string newValue = "text-start";
+ switch (text)
+ {
+ case "PERCENTUAL":
+ case "VALOR":
+ newValue = "text-center";
+ break;
+ case "QUANTIDADE":
+ case "DATA":
+ newValue = "text-end";
+ break;
+ }
+ stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", newValue).Replace("{Size}", classSize).Replace("{FontWeight}", "fw-bold")
+ .Replace("{Content}", description));
+ num2++;
+ }
+ }
+ }
+ }
+ stringBuilder.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", ""));
+ analitico.ForEach(delegate(T x)
+ {
+ //IL_00ca: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00cd: Invalid comparison between Unknown and I4
+ //IL_01d8: Unknown result type (might be due to invalid IL or missing references)
+ type = x.GetType();
+ properties = type.GetProperties();
+ PropertyInfo propertyInfo2 = properties.FirstOrDefault((PropertyInfo b) => b.Name == "Bold");
+ bool flag = propertyInfo2 != null && (bool)propertyInfo2.GetValue(x);
+ PropertyInfo propertyInfo3 = properties.FirstOrDefault((PropertyInfo b) => b.Name == "Sinal");
+ Sinal result;
+ string text2 = ((propertyInfo3 != null && propertyInfo3.GetValue(x) != null && Enum.TryParse<Sinal>(propertyInfo3.GetValue(x).ToString(), ignoreCase: true, out result) && (int)result == 1) ? "color: red;" : "color: black;");
+ if (!flag)
+ {
+ _ = "<tr style='" + text2 + "'>";
+ }
+ else
+ {
+ _ = "<tr style='font-weight: bold; " + text2 + "'>";
+ }
+ StringBuilder stringBuilder4 = new StringBuilder();
+ PropertyInfo[] array2 = properties;
+ foreach (PropertyInfo propertyInfo4 in array2)
+ {
+ if (!(propertyInfo4.Name == "ValidationEvent"))
+ {
+ object obj3 = propertyInfo4.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj3 != null)
+ {
+ string description2 = ((DescriptionAttribute)obj3).Description;
+ if ((!propertyName || !colunasOcultas.Contains(propertyInfo4.Name)) && (propertyName || !colunasOcultas.Contains(description2)))
+ {
+ object obj4 = propertyInfo4.GetCustomAttributes(typeof(TipoAttribute), inherit: true).FirstOrDefault();
+ string text3 = "";
+ if (obj4 != null)
+ {
+ text3 = ((TipoAttribute)obj4).Description;
+ }
+ string newValue2 = "text-start";
+ string newValue3;
+ switch (text3)
+ {
+ default:
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{propertyInfo4.GetValue(x)}" : "");
+ break;
+ case "PERCENTUAL":
+ newValue2 = "text-end";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{(decimal)propertyInfo4.GetValue(x) * 0.01m:p2}" : "");
+ break;
+ case "VALOR":
+ newValue2 = "text-end";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{(decimal)propertyInfo4.GetValue(x):c2}" : "");
+ break;
+ case "VALORDECIMAL2":
+ newValue2 = "text-end";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{(decimal)propertyInfo4.GetValue(x):n2}" : "");
+ break;
+ case "DATA":
+ newValue2 = "text-center";
+ newValue3 = ((propertyInfo4.GetValue(x) == null || (DateTime)propertyInfo4.GetValue(x) == DateTime.MinValue) ? "" : $"{(DateTime)propertyInfo4.GetValue(x):d}");
+ break;
+ case "QUANTIDADE":
+ newValue2 = "text-center";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{propertyInfo4.GetValue(x)}" : "");
+ break;
+ case "ENUM":
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? (ValidationHelper.GetDescription((Enum)propertyInfo4.GetValue(x)) ?? "") : "");
+ break;
+ case "DATA/TIME?":
+ case "DATA/TIME":
+ newValue2 = "text-center";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{(DateTime?)propertyInfo4.GetValue(x):G}" : "");
+ break;
+ case "DATA?":
+ newValue2 = "text-center";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{(DateTime?)propertyInfo4.GetValue(x):d}" : "");
+ break;
+ case "VALOR?":
+ newValue2 = "text-end";
+ newValue3 = ((propertyInfo4.GetValue(x) != null) ? $"{(decimal?)propertyInfo4.GetValue(x):c2}" : "");
+ break;
+ }
+ stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", newValue2).Replace("{Size}", classSize).Replace("{FontWeight}", flag ? "fw-bold" : "")
+ .Replace("{Content}", newValue3));
+ }
+ }
+ }
+ }
+ rowContent.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", "style='" + text2 + "'"));
+ });
+ StringBuilder stringBuilder3 = new StringBuilder();
+ if (grafico)
+ {
+ rowContent.Append("<td>");
+ rowContent.Append("<div id=\"donutchart\" style=\"width: 500px; height: 300px;\"></div>");
+ rowContent.Append("<h6 style='text-align:center'>*VALORES NEGATIVOS NÃO SÃO REPRESENTADOS NO GRÁFICO DE PIZZA.</h6>");
+ rowContent.Append("</td>");
+ }
+ stringBuilder3.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder.ToString()).Replace("{Body}", rowContent.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer)) ? Resources.FooterTemplate.Replace("{Content}", $"<tr><td colspan='{num2}' style='color:gray'>{footer}</td></tr>") : ""));
+ return stringBuilder3.ToString();
+ });
+ }
+
+ public static async Task<string> GenerateMultipleTable(List<List<Listagem>> analiticos, List<string> colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null)
+ {
+ if (analiticos == null)
+ {
+ return "";
+ }
+ if (analiticos.Count == 0)
+ {
+ return "";
+ }
+ int num = 0;
+ if (config != null)
+ {
+ num = config.TamanhoFonte;
+ }
+ string classSize = ((num == 0) ? "" : $"fs-{num}'");
+ return await Task.Run(delegate
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ int num2 = 0;
+ foreach (List<Listagem> analitico in analiticos)
+ {
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder stringBuilder3 = new StringBuilder();
+ StringBuilder stringBuilder4 = new StringBuilder();
+ int num3 = 0;
+ stringBuilder3.Append(Resources.HeaderTemplate.Replace("{Align}", "text-start").Replace("{Size}", "").Replace("{FontWeight}", "fw-bold")
+ .Replace("{Content}", analitico[0].NomeRelatorio));
+ stringBuilder2.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder3.ToString()).Replace("{Color}", ""));
+ analitico.ForEach(delegate(Listagem x)
+ {
+ //IL_0098: Unknown result type (might be due to invalid IL or missing references)
+ //IL_009b: Invalid comparison between Unknown and I4
+ //IL_018c: Unknown result type (might be due to invalid IL or missing references)
+ PropertyInfo[] properties = ((object)x).GetType().GetProperties();
+ PropertyInfo propertyInfo = properties.FirstOrDefault((PropertyInfo b) => b.Name == "Bold");
+ bool flag = propertyInfo != null && (bool)propertyInfo.GetValue(x);
+ PropertyInfo propertyInfo2 = properties.FirstOrDefault((PropertyInfo b) => b.Name == "Sinal");
+ Sinal result;
+ string text = ((propertyInfo2 != null && propertyInfo2.GetValue(x) != null && Enum.TryParse<Sinal>(propertyInfo2.GetValue(x).ToString(), ignoreCase: true, out result) && (int)result == 1) ? "color: red;" : "color: black;");
+ if (!flag)
+ {
+ _ = "<tr style='" + text + "'>";
+ }
+ else
+ {
+ _ = "<tr style='font-weight: bold; " + text + "'>";
+ }
+ StringBuilder stringBuilder6 = new StringBuilder();
+ PropertyInfo[] array = properties;
+ foreach (PropertyInfo propertyInfo3 in array)
+ {
+ if (!(propertyInfo3.Name == "ValidationEvent"))
+ {
+ object obj = propertyInfo3.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj != null)
+ {
+ string description = ((DescriptionAttribute)obj).Description;
+ if ((!propertyName || !colunasOcultas.Contains(propertyInfo3.Name)) && (propertyName || !colunasOcultas.Contains(description)))
+ {
+ object obj2 = propertyInfo3.GetCustomAttributes(typeof(TipoAttribute), inherit: true).FirstOrDefault();
+ string text2 = "";
+ if (obj2 != null)
+ {
+ text2 = ((TipoAttribute)obj2).Description;
+ }
+ string newValue = "text-start";
+ string newValue2;
+ switch (text2)
+ {
+ default:
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{propertyInfo3.GetValue(x)}" : "");
+ break;
+ case "PERCENTUAL":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{(decimal)propertyInfo3.GetValue(x) * 0.01m:p2}" : "");
+ break;
+ case "VALOR":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{(decimal)propertyInfo3.GetValue(x):c2}" : "");
+ break;
+ case "DATA":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(x) == null || (DateTime)propertyInfo3.GetValue(x) == DateTime.MinValue) ? "" : $"{(DateTime)propertyInfo3.GetValue(x):d}");
+ break;
+ case "QUANTIDADE":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{propertyInfo3.GetValue(x)}" : "");
+ break;
+ case "ENUM":
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? (ValidationHelper.GetDescription((Enum)propertyInfo3.GetValue(x)) ?? "") : "");
+ break;
+ case "DATA/TIME?":
+ case "DATA/TIME":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{(DateTime?)propertyInfo3.GetValue(x):G}" : "");
+ break;
+ case "DATA?":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{(DateTime?)propertyInfo3.GetValue(x):d}" : "");
+ break;
+ case "VALOR?":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(x) != null) ? $"{(decimal?)propertyInfo3.GetValue(x):c2}" : "");
+ break;
+ }
+ stringBuilder6.Append(Resources.ColumnTemplate.Replace("{Align}", newValue).Replace("{Size}", classSize).Replace("{FontWeight}", flag ? "fw-bold" : "")
+ .Replace("{Content}", newValue2));
+ }
+ }
+ }
+ }
+ });
+ StringBuilder stringBuilder5 = new StringBuilder();
+ if (grafico)
+ {
+ stringBuilder4.Append($"<div id=\"donutchart{num2}\" style=\"width: 70%; height: 125px;\"></div>");
+ }
+ num2++;
+ stringBuilder5.Append(Resources.TableMultipleTemplate.Replace("{Head}", stringBuilder2.ToString()).Replace("{Body}", stringBuilder4.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer)) ? Resources.FooterTemplate.Replace("{Content}", $"<tr><td colspan='{num3}' style='color:gray'>{footer}</td></tr>") : ""));
+ stringBuilder.Append(stringBuilder5.ToString());
+ }
+ return stringBuilder.ToString();
+ });
+ }
+
+ public static async Task<XLWorkbook> GerarXlsSintetico(XLWorkbook xlWorkbook, string nome, List<SinteticModel> sintetic)
+ {
+ return await Task.Run((Func<XLWorkbook>)delegate
+ {
+ try
+ {
+ nome = nome.ValidaNomePlanilha();
+ IXLWorksheet xlWorksheet = xlWorkbook.Worksheets.Add(nome);
+ int indexColumn = 1;
+ sintetic.ForEach(delegate(SinteticModel x)
+ {
+ xlWorksheet.Cell(1, indexColumn).Value = x.Hint;
+ xlWorksheet.Cell(2, indexColumn).Value = x.Value;
+ indexColumn++;
+ });
+ ((IXLFontBase)((IXLRangeBase)xlWorksheet.Row(1)).Style.Font).Bold = true;
+ xlWorksheet.Columns().AdjustToContents();
+ return xlWorkbook;
+ }
+ catch (Exception)
+ {
+ return (XLWorkbook)null;
+ }
+ });
+ }
+
+ public static async Task<string> GenerateTable<T>(List<T> analitico, Relatorio relatorio, bool grafico = false, bool verificarColunas = true, string footer = "", ConfiguracaoImpressao config = null)
+ {
+ //IL_0016: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0017: Unknown result type (might be due to invalid IL or missing references)
+ int fontSize = 0;
+ List<ParametrosRelatorio> parametros;
+ if (config == null)
+ {
+ List<ParametrosRelatorio> list = ((!verificarColunas) ? null : (await new ConfuguracoesServico().BuscarParametros(relatorio)));
+ parametros = list;
+ if (parametros == null || parametros.Count == 0)
+ {
+ PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ parametros = ((IEnumerable<PropertyInfo>)properties).Select((Func<PropertyInfo, ParametrosRelatorio>)((PropertyInfo x) => new ParametrosRelatorio
+ {
+ Campo = x.Name,
+ Header = x.GetDescriptionAttribute(),
+ Tipo = x.GetTypeAttribute(),
+ Relatorio = relatorio,
+ Width = 0,
+ Ordem = 0
+ })).ToList();
+ }
+ }
+ else
+ {
+ parametros = config.Campos;
+ fontSize = config.TamanhoFonte;
+ }
+ string classSize = ((fontSize == 0) ? "" : $"fs-{fontSize}'");
+ parametros = await GetRestricoesColunas(parametros);
+ if (analitico == null)
+ {
+ return "";
+ }
+ if (analitico.Count == 0)
+ {
+ return "";
+ }
+ return await Task.Run(delegate
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder headerContent = new StringBuilder();
+ StringBuilder rowContent = new StringBuilder();
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties2 = type.GetProperties();
+ int columnsCount = 0;
+ ExtensionMethods.ForEach<ParametrosRelatorio>((IEnumerable<ParametrosRelatorio>)(from x in parametros
+ orderby x.Ordem, x.Header
+ select x), (Action<ParametrosRelatorio>)delegate(ParametrosRelatorio x)
+ {
+ if (!(x.Tipo == "INVALID"))
+ {
+ PropertyInfo propertyInfo4 = properties2.FirstOrDefault((PropertyInfo p) => p.Name == x.Campo);
+ if (!(propertyInfo4 == null))
+ {
+ string descriptionAttribute = propertyInfo4.GetDescriptionAttribute();
+ string newValue3 = "text-start";
+ switch (x.Tipo)
+ {
+ case "PERCENTUAL":
+ case "VALOR":
+ newValue3 = "text-center";
+ break;
+ case "QUANTIDADE":
+ case "DATA":
+ newValue3 = "text-end";
+ break;
+ }
+ headerContent.Append(Resources.HeaderTemplate.Replace("{Align}", newValue3).Replace("{Size}", classSize).Replace("{FontWeight}", "fw-bold")
+ .Replace("{Content}", descriptionAttribute));
+ columnsCount++;
+ }
+ }
+ });
+ stringBuilder.Append(Resources.RowTemplate.Replace("{Content}", headerContent.ToString()).Replace("{Color}", ""));
+ analitico.ForEach(delegate(T a)
+ {
+ //IL_0101: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0104: Invalid comparison between Unknown and I4
+ StringBuilder content = new StringBuilder();
+ type = a.GetType();
+ properties2 = type.GetProperties();
+ PropertyInfo propertyInfo = properties2.FirstOrDefault((PropertyInfo b) => b.Name == "Bold");
+ bool bold = propertyInfo != null && (bool)propertyInfo.GetValue(a);
+ PropertyInfo propertyInfo2 = properties2.FirstOrDefault((PropertyInfo b) => b.Name == "Sinal");
+ Sinal result;
+ string text = ((propertyInfo2 != null && propertyInfo2.GetValue(a) != null && Enum.TryParse<Sinal>(propertyInfo2.GetValue(a).ToString(), ignoreCase: true, out result) && (int)result == 1) ? "color: red;" : "color: black;");
+ if (!bold)
+ {
+ _ = "<tr style='" + text + "'>";
+ }
+ else
+ {
+ _ = "<tr class='fw-bold' style='" + text + "'>";
+ }
+ ExtensionMethods.ForEach<ParametrosRelatorio>((IEnumerable<ParametrosRelatorio>)(from x in parametros
+ orderby x.Ordem, x.Header
+ select x), (Action<ParametrosRelatorio>)delegate(ParametrosRelatorio x)
+ {
+ if (!(x.Tipo == "INVALID"))
+ {
+ PropertyInfo propertyInfo3 = properties2.FirstOrDefault((PropertyInfo p) => p.Name == x.Campo);
+ if (!(propertyInfo3 == null))
+ {
+ string newValue = "text-start";
+ string newValue2;
+ switch (x.Tipo)
+ {
+ default:
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{propertyInfo3.GetValue(a)}" : "");
+ break;
+ case "PERCENTUAL":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{(decimal)propertyInfo3.GetValue(a) * 0.01m:p2}" : "");
+ break;
+ case "VALOR":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{(decimal)propertyInfo3.GetValue(a):c2}" : "");
+ break;
+ case "VALORDECIMAL2":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{(decimal)propertyInfo3.GetValue(a):n2}" : "");
+ break;
+ case "DATA":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(a) == null || (DateTime)propertyInfo3.GetValue(a) == DateTime.MinValue) ? "" : $"{(DateTime)propertyInfo3.GetValue(a):d}");
+ break;
+ case "QUANTIDADE":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{propertyInfo3.GetValue(a)}" : "");
+ break;
+ case "ENUM":
+ newValue2 = ((propertyInfo3.GetValue(a) != null && Convert.ToInt32(propertyInfo3.GetValue(a)) != 0) ? (ValidationHelper.GetDescription((Enum)propertyInfo3.GetValue(a)) ?? "") : "");
+ break;
+ case "DATA/TIME?":
+ case "DATA/TIME":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{(DateTime?)propertyInfo3.GetValue(a):G}" : "");
+ break;
+ case "DATA?":
+ newValue = "text-center";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{(DateTime?)propertyInfo3.GetValue(a):d}" : "");
+ break;
+ case "VALOR?":
+ newValue = "text-end";
+ newValue2 = ((propertyInfo3.GetValue(a) != null) ? $"{(decimal?)propertyInfo3.GetValue(a):c2}" : "");
+ break;
+ }
+ content.Append(Resources.ColumnTemplate.Replace("{Align}", newValue).Replace("{Size}", classSize).Replace("{FontWeight}", bold ? "fw-bold" : "")
+ .Replace("{Content}", newValue2));
+ }
+ }
+ });
+ rowContent.Append(Resources.RowTemplate.Replace("{Content}", content.ToString()).Replace("{Color}", "style='" + text + "'"));
+ });
+ StringBuilder stringBuilder2 = new StringBuilder();
+ stringBuilder2.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder.ToString()).Replace("{Body}", rowContent.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer)) ? Resources.FooterTemplate.Replace("{Content}", $"<tr><td colspan='{columnsCount}' style='color:gray'>{footer}</td></tr>") : ""));
+ return stringBuilder2.ToString();
+ });
+ }
+
+ public static async Task<XLWorkbook> GerarXls<T>(XLWorkbook xlWorkbook, string nome, List<T> analitico, Relatorio relatorio, bool verificarColunas = true)
+ {
+ //IL_0026: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0027: Unknown result type (might be due to invalid IL or missing references)
+ nome = nome.ValidaNomePlanilha();
+ List<ParametrosRelatorio> list = ((!verificarColunas) ? null : (await new ConfuguracoesServico().BuscarParametros(relatorio)));
+ List<ParametrosRelatorio> parametros = list;
+ if (parametros == null || parametros.Count == 0)
+ {
+ PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ parametros = ((IEnumerable<PropertyInfo>)properties).Select((Func<PropertyInfo, ParametrosRelatorio>)((PropertyInfo x) => new ParametrosRelatorio
+ {
+ Campo = x.Name,
+ Header = x.GetDescriptionAttribute(),
+ Tipo = x.GetTypeAttribute(),
+ Relatorio = relatorio,
+ Width = 0,
+ Ordem = 0
+ })).ToList();
+ }
+ parametros = await GetRestricoesColunas(parametros);
+ return await Task.Run((Func<XLWorkbook>)delegate
+ {
+ try
+ {
+ IXLWorksheet xlWorksheet = xlWorkbook.Worksheets.Add(nome);
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties2 = type.GetProperties();
+ int indexColumn = 1;
+ ExtensionMethods.ForEach<ParametrosRelatorio>((IEnumerable<ParametrosRelatorio>)(from x in parametros
+ orderby x.Ordem, x.Header
+ select x), (Action<ParametrosRelatorio>)delegate(ParametrosRelatorio x)
+ {
+ if (!(x.Tipo == "INVALID"))
+ {
+ PropertyInfo propertyInfo2 = properties2.FirstOrDefault((PropertyInfo p) => p.Name == x.Campo || (p.Name.ToUpper().Equals("NOME") && x.Campo.ToUpper().Equals("VENDEDOR") && nome.Equals("SINTÉTICO POR VENDEDOR") && (int)relatorio == 7) || (p.Name.ToUpper().Equals("NOME") && x.Campo.ToUpper().Equals("SEGURADORA") && nome.Equals("SINTÉTICO POR SEGURADORA") && (int)relatorio == 7) || (p.Name.ToUpper().Equals("NOME") && x.Campo.ToUpper().Equals("RAMO") && nome.Equals("SINTÉTICO POR RAMO") && (int)relatorio == 7));
+ if (!(propertyInfo2 == null))
+ {
+ xlWorksheet.Cell(1, indexColumn).Value = propertyInfo2.GetDescriptionAttribute();
+ indexColumn++;
+ }
+ }
+ });
+ int indexRow = 2;
+ analitico.ForEach(delegate(T a)
+ {
+ indexColumn = 1;
+ int row = indexRow;
+ ExtensionMethods.ForEach<ParametrosRelatorio>((IEnumerable<ParametrosRelatorio>)(from x in parametros
+ orderby x.Ordem, x.Header
+ select x), (Action<ParametrosRelatorio>)delegate(ParametrosRelatorio x)
+ {
+ if (!(x.Tipo == "INVALID"))
+ {
+ PropertyInfo propertyInfo = properties2.FirstOrDefault((PropertyInfo p) => p.Name == x.Campo || (p.Name.ToUpper().Equals("NOME") && x.Campo.ToUpper().Equals("VENDEDOR") && nome.Equals("SINTÉTICO POR VENDEDOR") && (int)relatorio == 7) || (p.Name.ToUpper().Equals("NOME") && x.Campo.ToUpper().Equals("SEGURADORA") && nome.Equals("SINTÉTICO POR SEGURADORA") && (int)relatorio == 7) || (p.Name.ToUpper().Equals("NOME") && x.Campo.ToUpper().Equals("RAMO") && nome.Equals("SINTÉTICO POR RAMO") && (int)relatorio == 7));
+ if (!(propertyInfo == null))
+ {
+ Regex regex = new Regex("\\<[^\\>]*\\>");
+ object obj = propertyInfo.GetValue(a);
+ if (obj != null && obj.ToString().Contains(">") && obj.ToString().Contains("<"))
+ {
+ obj = regex.Replace(obj.ToString(), "");
+ }
+ switch (x.Tipo)
+ {
+ default:
+ ((IXLNumberFormatBase)xlWorksheet.Cell(row, indexColumn).Style.NumberFormat).Format = "@";
+ xlWorksheet.Cell(row, indexColumn).Value = $"{obj}";
+ break;
+ case "DATA/TIME?":
+ case "DATA/TIME":
+ ((IXLNumberFormatBase)xlWorksheet.Cell(row, indexColumn).Style.NumberFormat).Format = "dd/MM/yyyy HH:mm:ss";
+ xlWorksheet.Cell(row, indexColumn).Value = $"{obj}";
+ break;
+ case "DATA?":
+ case "DATA":
+ ((IXLNumberFormatBase)xlWorksheet.Cell(row, indexColumn).Style.NumberFormat).Format = "dd/MM/yyyy";
+ xlWorksheet.Cell(row, indexColumn).Value = $"{obj}";
+ break;
+ case "VALOR":
+ xlWorksheet.Cell(row, indexColumn).Style.NumberFormat.SetNumberFormatId(2);
+ xlWorksheet.Cell(row, indexColumn).Value = ((decimal?)obj).GetValueOrDefault();
+ break;
+ case "QUANTIDADE":
+ xlWorksheet.Cell(row, indexColumn).Style.NumberFormat.SetNumberFormatId(1);
+ xlWorksheet.Cell(row, indexColumn).Value = obj;
+ break;
+ case "PERCENTUAL":
+ xlWorksheet.Cell(row, indexColumn).Style.NumberFormat.SetNumberFormatId(10);
+ xlWorksheet.Cell(row, indexColumn).Value = ((decimal?)obj).GetValueOrDefault() * 0.01m;
+ break;
+ }
+ int num = indexColumn;
+ indexColumn = num + 1;
+ }
+ }
+ });
+ indexRow++;
+ });
+ ((IXLFontBase)((IXLRangeBase)xlWorksheet.Row(1)).Style.Font).Bold = true;
+ xlWorksheet.Columns().AdjustToContents();
+ return xlWorkbook;
+ }
+ catch (Exception)
+ {
+ return (XLWorkbook)null;
+ }
+ });
+ }
+
+ public static async Task<XLWorkbook> GerarXls<T>(XLWorkbook xlWorkbook, string nome, List<T> analitico, List<string> colunasOcultas = null)
+ {
+ return await Task.Run((Func<XLWorkbook>)delegate
+ {
+ try
+ {
+ nome = nome.ValidaNomePlanilha();
+ IXLWorksheet xlWorksheet = xlWorkbook.Worksheets.Add(nome);
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties = type.GetProperties();
+ int indexColumn = 1;
+ PropertyInfo[] array = properties;
+ foreach (PropertyInfo propertyInfo in array)
+ {
+ if (!(propertyInfo.Name == "ValidationEvent"))
+ {
+ object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj != null)
+ {
+ string description = ((DescriptionAttribute)obj).Description;
+ if (colunasOcultas == null || !colunasOcultas.Contains(description))
+ {
+ xlWorksheet.Cell(1, indexColumn).Value = description;
+ indexColumn++;
+ }
+ }
+ }
+ }
+ int indexRow = 2;
+ analitico.ForEach(delegate(T x)
+ {
+ indexColumn = 1;
+ type = x.GetType();
+ properties = type.GetProperties();
+ PropertyInfo[] array2 = properties;
+ foreach (PropertyInfo propertyInfo2 in array2)
+ {
+ if (propertyInfo2.Name == "ValidationEvent")
+ {
+ continue;
+ }
+ object obj2 = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj2 == null)
+ {
+ continue;
+ }
+ string description2 = ((DescriptionAttribute)obj2).Description;
+ if (colunasOcultas != null && colunasOcultas.Contains(description2))
+ {
+ continue;
+ }
+ string name = propertyInfo2.Name;
+ if (!name.Contains("Fipe"))
+ {
+ switch (name)
+ {
+ case "NumeroProposta":
+ case "NumeroApolice":
+ case "NumeroPedidoEndosso":
+ break;
+ default:
+ goto IL_010f;
+ }
+ }
+ ((IXLNumberFormatBase)xlWorksheet.Cell(indexRow, indexColumn).Style.NumberFormat).Format = "@";
+ goto IL_010f;
+ IL_010f:
+ xlWorksheet.Cell(indexRow, indexColumn).Value = propertyInfo2.GetValue(x);
+ indexColumn++;
+ }
+ indexRow++;
+ });
+ ((IXLFontBase)((IXLRangeBase)xlWorksheet.Row(1)).Style.Font).Bold = true;
+ xlWorksheet.Columns().AdjustToContents();
+ return xlWorkbook;
+ }
+ catch (Exception)
+ {
+ return (XLWorkbook)null;
+ }
+ });
+ }
+
+ public static bool IsWindowOpen<T>(string title) where T : Window
+ {
+ return ((IEnumerable)Application.Current.Windows).OfType<T>().Any((T x) => ((Window)x).Title == title);
+ }
+
+ public static void Destroy<T>() where T : Window
+ {
+ object obj = ((IEnumerable)Application.Current.Windows).OfType<T>().FirstOrDefault();
+ if (obj != null)
+ {
+ ((Window)obj).Close();
+ }
+ }
+
+ public static void Destroy<T>(string title) where T : Window
+ {
+ object obj = ((IEnumerable)Application.Current.Windows).OfType<T>().FirstOrDefault((T x) => ((Window)x).Title == title);
+ if (obj != null)
+ {
+ ((Window)obj).Close();
+ }
+ }
+
+ public static T GetValueFromType<T>(this object objeto)
+ {
+ Type typeFromHandle = typeof(T);
+ PropertyInfo[] properties = objeto.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ foreach (PropertyInfo propertyInfo in properties)
+ {
+ if (!(propertyInfo.PropertyType != typeFromHandle))
+ {
+ return (T)propertyInfo.GetValue(objeto);
+ }
+ }
+ return default(T);
+ }
+
+ private static async Task<List<ParametrosRelatorio>> GetRestricoesColunas(List<ParametrosRelatorio> parametros)
+ {
+ List<RestricaoUsuarioCamposRelatorios> restricoes = await new RestricaoUsuarioServico().BuscarRestricoesCamposRelatorios(((DomainBase)Recursos.Usuario).Id);
+ restricoes = restricoes.Where((RestricaoUsuarioCamposRelatorios x) => x.Restricao).ToList();
+ return parametros.Where((ParametrosRelatorio x) => restricoes.Where((RestricaoUsuarioCamposRelatorios y) => x.Relatorio == y.Relatorio).All((RestricaoUsuarioCamposRelatorios y) => x.Header != y.Campo)).ToList();
+ }
+
+ public static async Task ContruirLista<T>(this DataGrid grid, Relatorio relatorio)
+ {
+ //IL_0016: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0017: Unknown result type (might be due to invalid IL or missing references)
+ List<ParametrosRelatorio> list = await new ConfuguracoesServico().BuscarParametros(relatorio);
+ if (list == null || list.Count == 0)
+ {
+ list = ((IEnumerable<PropertyInfo>)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)).Select((Func<PropertyInfo, ParametrosRelatorio>)((PropertyInfo x) => new ParametrosRelatorio
+ {
+ Campo = x.Name,
+ Header = x.GetDescriptionAttribute(),
+ Tipo = x.GetTypeAttribute(),
+ Relatorio = relatorio,
+ Width = 0,
+ Ordem = 0
+ })).ToList();
+ }
+ if (!Recursos.Usuario.Administrador)
+ {
+ list = await GetRestricoesColunas(list);
+ }
+ (from x in list
+ orderby x.Ordem, x.Header
+ select x).ToList().ForEach(delegate(ParametrosRelatorio x)
+ {
+ //IL_0077: Unknown result type (might be due to invalid IL or missing references)
+ //IL_007d: Expected O, but got Unknown
+ //IL_0091: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0097: Expected O, but got Unknown
+ //IL_0335: Unknown result type (might be due to invalid IL or missing references)
+ //IL_033a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_021a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0220: Expected O, but got Unknown
+ //IL_0234: Unknown result type (might be due to invalid IL or missing references)
+ //IL_023a: Expected O, but got Unknown
+ //IL_01db: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01e1: Expected O, but got Unknown
+ //IL_01f5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01fb: Expected O, but got Unknown
+ //IL_0361: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0362: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0367: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0373: Unknown result type (might be due to invalid IL or missing references)
+ //IL_037d: Expected O, but got Unknown
+ //IL_037d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0384: Unknown result type (might be due to invalid IL or missing references)
+ //IL_038b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0397: Expected O, but got Unknown
+ //IL_0397: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02d4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02da: Expected O, but got Unknown
+ //IL_02ee: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02f4: Expected O, but got Unknown
+ //IL_03b8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03a7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0298: Unknown result type (might be due to invalid IL or missing references)
+ //IL_029e: Expected O, but got Unknown
+ //IL_02b2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02b8: Expected O, but got Unknown
+ //IL_0259: Unknown result type (might be due to invalid IL or missing references)
+ //IL_025f: Expected O, but got Unknown
+ //IL_0273: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0279: Expected O, but got Unknown
+ //IL_03c2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03c9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03d5: Expected O, but got Unknown
+ //IL_030a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0310: Expected O, but got Unknown
+ //IL_0324: Unknown result type (might be due to invalid IL or missing references)
+ //IL_032a: Expected O, but got Unknown
+ if (!(x.Tipo == "INVALID") && (!(x.Campo == "DataControle") || Recursos.Usuario.Administrador || !Recursos.Configuracoes.Any((ConfiguracaoSistema c) => (int)c.Configuracao == 33)))
+ {
+ string stringFormat = "";
+ Style elementStyle = (Style)Application.Current.Resources[(object)"VerticalCenterStyle3"];
+ Style headerStyle = (Style)Application.Current.Resources[(object)"MaterialDesignDataGridColumnHeaderNew"];
+ switch (x.Tipo)
+ {
+ case "DATA/TIME?":
+ case "DATA/TIME":
+ stringFormat = "G";
+ elementStyle = (Style)Application.Current.Resources[(object)"HorizontalCenterStyle2"];
+ headerStyle = (Style)Application.Current.Resources[(object)"HorizontalCenterHeaderStyleNew"];
+ break;
+ case "DATA?":
+ case "DATA":
+ stringFormat = "d";
+ elementStyle = (Style)Application.Current.Resources[(object)"HorizontalCenterStyle2"];
+ headerStyle = (Style)Application.Current.Resources[(object)"HorizontalCenterHeaderStyleNew"];
+ break;
+ case "PERCENTUAL":
+ stringFormat = "{0:0.00}%";
+ elementStyle = (Style)Application.Current.Resources[(object)"HorizontalRightStyle"];
+ headerStyle = (Style)Application.Current.Resources[(object)"HorizontalRightHeaderStyleNew"];
+ break;
+ case "VALOR":
+ stringFormat = "c";
+ elementStyle = (Style)Application.Current.Resources[(object)"HorizontalRightStyle"];
+ headerStyle = (Style)Application.Current.Resources[(object)"HorizontalRightHeaderStyleNew"];
+ break;
+ case "VALORDECIMAL2":
+ stringFormat = "n2";
+ elementStyle = (Style)Application.Current.Resources[(object)"HorizontalRightStyle"];
+ headerStyle = (Style)Application.Current.Resources[(object)"HorizontalRightHeaderStyleNew"];
+ break;
+ case "QUANTIDADE":
+ elementStyle = (Style)Application.Current.Resources[(object)"HorizontalCenterStyle2"];
+ headerStyle = (Style)Application.Current.Resources[(object)"HorizontalCenterHeaderStyleNew"];
+ break;
+ }
+ grid.Columns.Add((DataGridColumn)new MaterialDataGridTextColumn
+ {
+ Header = (x.Header?.ToUpper() ?? x.Campo.ToUpper()),
+ Binding = (BindingBase)new Binding
+ {
+ Path = new PropertyPath(x.Campo, Array.Empty<object>()),
+ StringFormat = stringFormat,
+ Mode = (BindingMode)0,
+ UpdateSourceTrigger = (UpdateSourceTrigger)1
+ },
+ Width = (DataGridLength)((x.Width == 0) ? new DataGridLength(1.0, (DataGridLengthUnitType)0) : DataGridLength.op_Implicit((double)x.Width)),
+ ElementStyle = elementStyle,
+ HeaderStyle = headerStyle
+ });
+ }
+ });
+ }
+
+ public static List<SinteticModelList> ConstruirSintetico(this List<Sintetico> sintetico, Relatorio relatorio)
+ {
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000f: Unknown result type (might be due to invalid IL or missing references)
+ if (sintetico == null)
+ {
+ return null;
+ }
+ List<SinteticModelList> sintetics = new List<SinteticModelList>();
+ typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList().ForEach(delegate(PropertyInfo props)
+ {
+ //IL_0744: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0724: Unknown result type (might be due to invalid IL or missing references)
+ //IL_078d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0792: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0799: Unknown result type (might be due to invalid IL or missing references)
+ //IL_07a9: Expected O, but got Unknown
+ if (props.GetValue(sintetico.First()) != null)
+ {
+ string descriptionAttribute = props.GetDescriptionAttribute();
+ TipoRestricao? val = null;
+ switch (descriptionAttribute)
+ {
+ case "PRÊMIO TOTAL":
+ val = (TipoRestricao)65;
+ break;
+ case "TOTAL DE CLIENTES":
+ case "TOTAL DE CLIENTES ATIVOS":
+ case "TOTAL DE CLIENTES INATIVOS":
+ val = (TipoRestricao)66;
+ break;
+ case "PRÊMIO LÍQUIDO":
+ val = (TipoRestricao)67;
+ break;
+ case "MÉDIA DE COMISSÃO GERADA":
+ case "MÉDIA DE COMISSÃO PONDERADA":
+ case "MÉDIA DE COMISSÃO FECHADA":
+ val = (TipoRestricao)68;
+ break;
+ case "QUANTIDADE DE NOVOS NEGÓCIOS":
+ case "QUANTIDADE DE NEGÓCIOS PRÓPRIOS":
+ val = (TipoRestricao)69;
+ break;
+ case "QUANTIDADE DE RENOVAÇÕES":
+ case "QUANTIDADE DE SEGUROS NOVOS":
+ val = (TipoRestricao)70;
+ break;
+ case "QUANTIDADE DE CANCELAMENTOS":
+ val = (TipoRestricao)71;
+ break;
+ case "QUANTIDADE DE APÓLICES":
+ val = (TipoRestricao)72;
+ break;
+ case "QUANTIDADE DE ENDOSSOS":
+ val = (TipoRestricao)73;
+ break;
+ case "QUANTIDADE DE FATURAS":
+ val = (TipoRestricao)74;
+ break;
+ case "TOTAL GERAL":
+ val = (TipoRestricao)75;
+ break;
+ case "TOTAL DE LÍQUIDO":
+ val = (TipoRestricao)76;
+ break;
+ case "QUANTIDADE DE PROSPECÇÕES":
+ val = (TipoRestricao)77;
+ break;
+ case "TOTAL DE COMISSÃO GERADA":
+ val = (TipoRestricao)78;
+ break;
+ case "COMISSÃO RECEBIDA BRUTA":
+ val = (TipoRestricao)79;
+ break;
+ case "COMISSÃO RECEBIDA LÍQUIDA":
+ val = (TipoRestricao)92;
+ break;
+ case "IMPOSTOS":
+ val = (TipoRestricao)93;
+ break;
+ case "COMISSÃO PREVISTA":
+ val = (TipoRestricao)80;
+ break;
+ case "REPASSE":
+ val = (TipoRestricao)81;
+ break;
+ case "TOTAL PREVISTO":
+ val = (TipoRestricao)82;
+ break;
+ case "TOTAL DE TERCEIROS":
+ val = (TipoRestricao)83;
+ break;
+ case "QUANTIDADE LIQUIDADO":
+ val = (TipoRestricao)84;
+ break;
+ case "QUANTIDADE PENDENTE":
+ val = (TipoRestricao)85;
+ break;
+ case "VALOR LIQUIDADO":
+ val = (TipoRestricao)86;
+ break;
+ case "VALOR":
+ val = (TipoRestricao)100;
+ break;
+ case "VALOR ORÇADO":
+ val = (TipoRestricao)101;
+ break;
+ case "VALOR LIBERADO":
+ val = (TipoRestricao)103;
+ break;
+ case "VALOR PAGO":
+ val = (TipoRestricao)104;
+ break;
+ case "VALOR SALVADO":
+ val = (TipoRestricao)105;
+ break;
+ case "VALOR FRANQUIA":
+ val = (TipoRestricao)106;
+ break;
+ case "COMISSÃO PENDENTE":
+ val = (TipoRestricao)87;
+ break;
+ case "META ATINGIR":
+ val = (TipoRestricao)88;
+ break;
+ case "META CUMPRIDA":
+ val = (TipoRestricao)89;
+ break;
+ case "TOTAL PARCELAS":
+ val = (TipoRestricao)102;
+ break;
+ }
+ if (val.HasValue)
+ {
+ RestricaoUsuario val2 = new RestricaoUsuarioServico().BuscarRestricao(Recursos.Usuario, val.Value);
+ if (val2 != null && val2.Restricao)
+ {
+ return;
+ }
+ }
+ List<ParametrosTotalizacao> list = new ConfuguracoesServico().BuscarParametroTotalizacao(relatorio);
+ if (list == null || list.Count <= 0 || !list.All((ParametrosTotalizacao y) => y.Campo != props.Name) || props.Name.ToUpperInvariant().Contains("AGRUPAMENTO"))
+ {
+ SinteticModelList sintetic = new SinteticModelList
+ {
+ Hint = descriptionAttribute,
+ Value = new List<object>()
+ };
+ string tipo = props.GetTypeAttribute();
+ sintetico.ForEach(delegate(Sintetico s)
+ {
+ object item;
+ switch (tipo)
+ {
+ default:
+ item = $"{props.GetValue(s)}";
+ break;
+ case "DATA/TIME":
+ case "DATA/TIME?":
+ item = ((DateTime?)props.GetValue(s))?.ToString("G");
+ break;
+ case "DATA":
+ case "DATA?":
+ item = ((DateTime?)props.GetValue(s))?.ToString("d");
+ break;
+ case "PERCENTUAL":
+ item = $"{props.GetValue(s):n2} %";
+ break;
+ case "VALOR":
+ item = ((decimal)props.GetValue(s)).ToString("c2");
+ break;
+ }
+ sintetic.Value.Add(item);
+ });
+ sintetics.Add(sintetic);
+ }
+ }
+ });
+ return sintetics;
+ }
+
+ public static List<SinteticModel> ConstruirSintetico(this Sintetico sintetico, Relatorio relatorio)
+ {
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000f: Unknown result type (might be due to invalid IL or missing references)
+ if (sintetico == null)
+ {
+ return null;
+ }
+ List<SinteticModel> sintetics = new List<SinteticModel>();
+ typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList().ForEach(delegate(PropertyInfo x)
+ {
+ //IL_074d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_072d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_077d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0782: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0789: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0792: Expected O, but got Unknown
+ if (x.GetValue(sintetico) != null)
+ {
+ string descriptionAttribute = x.GetDescriptionAttribute();
+ TipoRestricao? val = null;
+ string descriptionField = null;
+ switch (descriptionAttribute)
+ {
+ case "PRÊMIO TOTAL":
+ val = (TipoRestricao)65;
+ break;
+ case "TOTAL DE CLIENTES":
+ case "TOTAL DE CLIENTES ATIVOS":
+ case "TOTAL DE CLIENTES INATIVOS":
+ val = (TipoRestricao)66;
+ break;
+ case "PRÊMIO LÍQUIDO":
+ val = (TipoRestricao)67;
+ break;
+ case "MÉDIA DE COMISSÃO GERADA":
+ case "MÉDIA DE COMISSÃO PONDERADA":
+ case "MÉDIA DE COMISSÃO FECHADA":
+ val = (TipoRestricao)68;
+ break;
+ case "QUANTIDADE DE NOVOS NEGÓCIOS":
+ case "QUANTIDADE DE NEGÓCIOS PRÓPRIOS":
+ val = (TipoRestricao)69;
+ break;
+ case "QUANTIDADE DE RENOVAÇÕES":
+ case "QUANTIDADE DE SEGUROS NOVOS":
+ val = (TipoRestricao)70;
+ break;
+ case "QUANTIDADE DE CANCELAMENTOS":
+ val = (TipoRestricao)71;
+ break;
+ case "QUANTIDADE DE APÓLICES":
+ val = (TipoRestricao)72;
+ break;
+ case "QUANTIDADE DE ENDOSSOS":
+ val = (TipoRestricao)73;
+ break;
+ case "QUANTIDADE DE FATURAS":
+ val = (TipoRestricao)74;
+ break;
+ case "TOTAL GERAL":
+ val = (TipoRestricao)75;
+ descriptionField = "CONTAGEM GERAL DE DOCUMENTOS";
+ break;
+ case "TOTAL DE LÍQUIDO":
+ val = (TipoRestricao)76;
+ descriptionField = "CONTAGEM GERAL DOS DOCUMENTOS ATIVOS";
+ break;
+ case "QUANTIDADE DE PROSPECÇÕES":
+ val = (TipoRestricao)77;
+ break;
+ case "TOTAL DE COMISSÃO GERADA":
+ val = (TipoRestricao)78;
+ break;
+ case "COMISSÃO RECEBIDA BRUTA":
+ val = (TipoRestricao)79;
+ break;
+ case "COMISSÃO RECEBIDA LÍQUIDA":
+ val = (TipoRestricao)92;
+ break;
+ case "IMPOSTOS":
+ val = (TipoRestricao)93;
+ break;
+ case "COMISSÃO PREVISTA":
+ val = (TipoRestricao)80;
+ break;
+ case "REPASSE":
+ val = (TipoRestricao)81;
+ break;
+ case "TOTAL PREVISTO":
+ val = (TipoRestricao)82;
+ break;
+ case "TOTAL DE TERCEIROS":
+ val = (TipoRestricao)83;
+ break;
+ case "QUANTIDADE LIQUIDADO":
+ val = (TipoRestricao)84;
+ break;
+ case "QUANTIDADE PENDENTE":
+ val = (TipoRestricao)85;
+ break;
+ case "VALOR LIQUIDADO":
+ val = (TipoRestricao)86;
+ break;
+ case "VALOR":
+ val = (TipoRestricao)100;
+ break;
+ case "VALOR ORÇADO":
+ val = (TipoRestricao)101;
+ break;
+ case "VALOR LIBERADO":
+ val = (TipoRestricao)103;
+ break;
+ case "VALOR PAGO":
+ val = (TipoRestricao)104;
+ break;
+ case "VALOR SALVADO":
+ val = (TipoRestricao)105;
+ break;
+ case "VALOR FRANQUIA":
+ val = (TipoRestricao)106;
+ break;
+ case "COMISSÃO PENDENTE":
+ val = (TipoRestricao)87;
+ break;
+ case "META ATINGIR":
+ val = (TipoRestricao)88;
+ break;
+ case "META CUMPRIDA":
+ val = (TipoRestricao)89;
+ break;
+ case "TOTAL PARCELAS":
+ val = (TipoRestricao)102;
+ break;
+ }
+ if (val.HasValue)
+ {
+ RestricaoUsuario val2 = new RestricaoUsuarioServico().BuscarRestricao(Recursos.Usuario, val.Value);
+ if (val2 != null && val2.Restricao)
+ {
+ return;
+ }
+ }
+ List<ParametrosTotalizacao> list = new ConfuguracoesServico().BuscarParametroTotalizacao(relatorio);
+ if (list == null || list.Count <= 0 || !list.All((ParametrosTotalizacao y) => y.Campo != x.Name))
+ {
+ SinteticModel val3 = new SinteticModel
+ {
+ Hint = descriptionAttribute,
+ DescriptionField = descriptionField
+ };
+ switch (x.GetTypeAttribute())
+ {
+ default:
+ val3.Value = $"{x.GetValue(sintetico)}";
+ break;
+ case "DATA/TIME?":
+ case "DATA/TIME":
+ val3.Value = ((DateTime?)x.GetValue(sintetico))?.ToString("G");
+ break;
+ case "DATA?":
+ case "DATA":
+ val3.Value = ((DateTime?)x.GetValue(sintetico))?.ToString("d");
+ break;
+ case "PERCENTUAL":
+ val3.Value = $"{x.GetValue(sintetico)} %";
+ break;
+ case "VALOR":
+ val3.Value = ((decimal)x.GetValue(sintetico)).ToString("c2");
+ break;
+ case "VALORDECIMAL2":
+ val3.Value = ((decimal)x.GetValue(sintetico)).ToString("n2");
+ break;
+ }
+ sintetics.Add(val3);
+ }
+ }
+ });
+ return sintetics;
+ }
+
+ public static string GetTypeAttribute(this PropertyInfo pi)
+ {
+ //IL_0021: Unknown result type (might be due to invalid IL or missing references)
+ object obj = pi.GetCustomAttributes(typeof(TipoAttribute), inherit: true).FirstOrDefault();
+ if (obj == null)
+ {
+ return "";
+ }
+ return ((TipoAttribute)obj).Description;
+ }
+
+ public static string GetDescriptionAttribute(this PropertyInfo pi)
+ {
+ object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj == null)
+ {
+ return pi.Name.ToUpper();
+ }
+ return ((DescriptionAttribute)obj).Description;
+ }
+
+ public static List<string> OcultarColunasDescricao(Type type, string categoria)
+ {
+ List<string> list = new List<string>();
+ PropertyInfo[] properties = type.GetProperties();
+ foreach (PropertyInfo propertyInfo in properties)
+ {
+ if (propertyInfo.Name == "ValidationEvent")
+ {
+ continue;
+ }
+ object obj = propertyInfo.GetCustomAttributes(typeof(CategoryAttribute), inherit: true).FirstOrDefault();
+ if (obj != null && !(((CategoryAttribute)obj).Category == categoria))
+ {
+ object obj2 = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault();
+ if (obj2 != null)
+ {
+ string description = ((DescriptionAttribute)obj2).Description;
+ list.Add(description);
+ }
+ }
+ }
+ return list;
+ }
+
+ public static string SubstituirVariaveis(string corpo, MalaDireta envio)
+ {
+ //IL_0025: Unknown result type (might be due to invalid IL or missing references)
+ //IL_002d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0097: Expected I4, but got Unknown
+ //IL_009d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00c6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0108: Unknown result type (might be due to invalid IL or missing references)
+ //IL_012b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_05ce: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0655: Unknown result type (might be due to invalid IL or missing references)
+ //IL_068d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06c5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_070e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_078a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_023a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0268: Unknown result type (might be due to invalid IL or missing references)
+ //IL_034c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0388: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03d9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0415: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0451: Unknown result type (might be due to invalid IL or missing references)
+ //IL_047f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_04ad: Unknown result type (might be due to invalid IL or missing references)
+ //IL_018a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01e9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_050d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_05f0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06f2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02d0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0314: Unknown result type (might be due to invalid IL or missing references)
+ //IL_063b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0753: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0759: Invalid comparison between Unknown and I4
+ //IL_058f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_07e6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_07ec: Invalid comparison between Unknown and I4
+ DateTime networkTime = GetNetworkTime();
+ VariaveisMalaDireta[] array = (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta));
+ foreach (VariaveisMalaDireta val in array)
+ {
+ switch ((int)val)
+ {
+ case 0:
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), networkTime.ToString(new CultureInfo("pt-BR")));
+ break;
+ case 1:
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), ValidationHelper.IsNotNullOrEmpty(envio.Cliente.NomeSocialRg) ? envio.Cliente.NomeSocialRg : envio.Cliente.Nome);
+ break;
+ case 2:
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Cliente.Documento);
+ break;
+ case 16:
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Cliente.VencimentoHabilitacao?.ToString("d"));
+ break;
+ case 14:
+ if (envio.Cliente.Nascimento.HasValue)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Cliente.Nascimento?.ToString("dd/MM"));
+ }
+ break;
+ case 15:
+ if (envio.Cliente.Nascimento.HasValue)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Cliente.Nascimento?.ToString("d"));
+ }
+ break;
+ case 3:
+ if (envio.Apolice != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Apolice.Proposta);
+ }
+ break;
+ case 4:
+ if (envio.Apolice != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Apolice.Apolice + ((envio.Apolice.Tipo != 0) ? (", endosso de número: " + envio.Apolice.Endosso) : ""));
+ }
+ break;
+ case 5:
+ {
+ Documento apolice9 = envio.Apolice;
+ if (((apolice9 != null) ? apolice9.Controle : null) != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Apolice.Controle.Ramo.Nome);
+ }
+ break;
+ }
+ case 6:
+ {
+ Documento apolice3 = envio.Apolice;
+ if (((apolice3 != null) ? apolice3.Controle : null) != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Apolice.Controle.Seguradora.Nome);
+ }
+ break;
+ }
+ case 7:
+ if (envio.Apolice != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Apolice.Vigencia1.ToString("d"));
+ }
+ break;
+ case 8:
+ if (envio.Apolice != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Apolice.Vigencia2?.ToString("d"));
+ }
+ break;
+ case 9:
+ if (envio.Parcela != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Parcela.Vencimento.ToString("d"));
+ }
+ break;
+ case 10:
+ if (envio.Parcela != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Parcela.Valor.ToString("c2"));
+ }
+ break;
+ case 11:
+ if (envio.Item != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Item.Descricao);
+ }
+ break;
+ case 12:
+ if (envio.Sinistro != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Sinistro.Numero);
+ }
+ break;
+ case 13:
+ if (envio.Parcela != null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), envio.Parcela.NumeroParcela.ToString());
+ }
+ break;
+ case 17:
+ {
+ if (envio.ArquivoDigital == null || envio.ArquivoDigital.All((IndiceArquivoDigital x) => string.IsNullOrWhiteSpace(x.UrlAssinatura)))
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), string.Empty);
+ break;
+ }
+ string links = "<table><thead><tr><th>ABAIXO OS DOCUMENTOS PARA ASSINATURA</th></thead><tbody>";
+ envio.ArquivoDigital.Where((IndiceArquivoDigital x) => !string.IsNullOrWhiteSpace(x.UrlAssinatura)).ToList().ForEach(delegate(IndiceArquivoDigital x)
+ {
+ links = links + "<tr><td><a href='" + x.UrlAssinatura + "'>" + x.Descricao + "</a></td></tr>";
+ });
+ links += "</tbody></table>";
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), links);
+ break;
+ }
+ case 18:
+ {
+ string newValue3 = $"<strong>ABAIXO O LINK PARA MEU CARTÃO DE VISITA.</strong><br><a target='_blank' href='{Address.Card}{((DomainBase)Recursos.Usuario).Id.GeraCartaoVisita()}'>CARTÃO DE VISITA ELETRÔNICO</a>";
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), newValue3);
+ break;
+ }
+ case 19:
+ {
+ if (envio.Apolice == null)
+ {
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), string.Empty);
+ break;
+ }
+ Uri assistance = Address.Assistance;
+ object arg;
+ if (envio == null)
+ {
+ arg = null;
+ }
+ else
+ {
+ Documento apolice7 = envio.Apolice;
+ arg = ((apolice7 != null) ? ((DomainBase)apolice7).Id.GeraAssistencia() : null);
+ }
+ string newValue2 = $"<strong>ABAIXO O LINK PARA O SEU CARTÃO ASSISTÊNCIA.</strong><br><a target='_blank' href='{assistance}{arg}'>CARTÃO ASSISTÊNCIA</a>";
+ corpo = corpo.Replace(ValidationHelper.GetEntity((Enum)(object)val), newValue2);
+ break;
+ }
+ case 20:
+ {
+ string text3 = corpo;
+ string entity3 = ValidationHelper.GetEntity((Enum)(object)val);
+ Documento apolice4 = envio.Apolice;
+ corpo = text3.Replace(entity3, (apolice4 != null) ? apolice4.PremioLiquido.ToString("c") : null);
+ break;
+ }
+ case 21:
+ {
+ string text2 = corpo;
+ string entity2 = ValidationHelper.GetEntity((Enum)(object)val);
+ Documento apolice2 = envio.Apolice;
+ corpo = text2.Replace(entity2, (apolice2 != null) ? apolice2.PremioTotal.ToString("c") : null);
+ break;
+ }
+ case 22:
+ {
+ string text5 = corpo;
+ string entity5 = ValidationHelper.GetEntity((Enum)(object)val);
+ Documento apolice8 = envio.Apolice;
+ object newValue4;
+ if (apolice8 == null)
+ {
+ newValue4 = null;
+ }
+ else
+ {
+ FormaPagamento? formaPagamento = apolice8.FormaPagamento;
+ newValue4 = (formaPagamento.HasValue ? ValidationHelper.GetDescription((Enum)(object)formaPagamento.GetValueOrDefault()) : null);
+ }
+ corpo = text5.Replace(entity5, (string?)newValue4);
+ break;
+ }
+ case 23:
+ {
+ string text4 = corpo;
+ string entity4 = ValidationHelper.GetEntity((Enum)(object)val);
+ Documento apolice5 = envio.Apolice;
+ object newValue;
+ if (((apolice5 != null) ? new decimal?(apolice5.NumeroParcelas) : null).HasValue && (int)envio.Apolice.TipoRecebimento.GetValueOrDefault() != 2)
+ {
+ Documento apolice6 = envio.Apolice;
+ newValue = ((apolice6 != null) ? apolice6.NumeroParcelas.ToString() : null);
+ }
+ else
+ {
+ newValue = "Indefinido";
+ }
+ corpo = text4.Replace(entity4, (string?)newValue);
+ break;
+ }
+ case 24:
+ {
+ string text = corpo;
+ string entity = ValidationHelper.GetEntity((Enum)(object)val);
+ Documento apolice = envio.Apolice;
+ corpo = text.Replace(entity, (!((apolice != null) ? new decimal?(apolice.NumeroParcelas) : null).HasValue || envio.Apolice.NumeroParcelas == 0m || (int)envio.Apolice.TipoRecebimento.GetValueOrDefault() == 2) ? "Verificar documento anexado" : (envio.Apolice.PremioTotal / envio.Apolice.NumeroParcelas).ToString());
+ break;
+ }
+ }
+ }
+ return corpo;
+ }
+
+ public static string GetText(string html)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ HtmlDocument val = new HtmlDocument();
+ val.LoadHtml(html);
+ return NodeText(val.DocumentNode);
+ }
+
+ private static string NodeText(HtmlNode node)
+ {
+ //IL_0056: Unknown result type (might be due to invalid IL or missing references)
+ //IL_005c: Invalid comparison between Unknown and I4
+ //IL_0025: Unknown result type (might be due to invalid IL or missing references)
+ //IL_002b: Invalid comparison between Unknown and I4
+ string text = "";
+ if (node.HasChildNodes)
+ {
+ foreach (HtmlNode item in (IEnumerable<HtmlNode>)node.ChildNodes)
+ {
+ text += (((int)item.NodeType == 3) ? item.InnerText : NodeText(item));
+ }
+ }
+ else if ((int)node.NodeType == 3)
+ {
+ text = node.InnerText;
+ }
+ return text;
+ }
+
+ public static string AdicionarLog(string html)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ HtmlDocument val = new HtmlDocument();
+ val.LoadHtml(html);
+ DateTime networkTime = GetNetworkTime();
+ foreach (HtmlNode item in (IEnumerable<HtmlNode>)val.DocumentNode.ChildNodes)
+ {
+ if (!(item.Name != "body"))
+ {
+ item.InnerHtml = $"<p>{Recursos.Usuario.Nome} ID-{((DomainBase)Recursos.Usuario).Id} {networkTime:g} </p>{item.InnerHtml}<hr>";
+ return item.InnerHtml;
+ }
+ }
+ return "";
+ }
+
+ public static List<FiltroPersonalizado> PopularFiltroPersonalizado<T>()
+ {
+ //IL_0062: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0067: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0073: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0080: Expected O, but got Unknown
+ List<FiltroPersonalizado> list = new List<FiltroPersonalizado>();
+ foreach (PropertyInfo item in from x in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
+ orderby ValidationHelper.DescriptionAttribute(x)
+ select x)
+ {
+ if (item.Name == "ValidationEvent")
+ {
+ continue;
+ }
+ FiltroPersonalizado val = new FiltroPersonalizado
+ {
+ Propriedade = item.Name,
+ Nome = item.GetDescriptionAttribute()
+ };
+ if (!(item.GetTypeAttribute() == "INVALID"))
+ {
+ Type type = item.PropertyType;
+ if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
+ {
+ type = type.GetGenericArguments()[0];
+ }
+ val.Tipo = ((type.BaseType == typeof(Enum)) ? type.BaseType : type);
+ list.Add(val);
+ }
+ }
+ return list;
+ }
+
+ public static List<FiltroPersonalizado> PopularFiltroFinanceiro()
+ {
+ //IL_0006: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0016: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0021: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0036: Expected O, but got Unknown
+ //IL_0037: Unknown result type (might be due to invalid IL or missing references)
+ //IL_003c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0047: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0052: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0067: Expected O, but got Unknown
+ //IL_0068: Unknown result type (might be due to invalid IL or missing references)
+ //IL_006d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0078: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0083: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0098: Expected O, but got Unknown
+ //IL_0099: Unknown result type (might be due to invalid IL or missing references)
+ //IL_009e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00a9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00b4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00c9: Expected O, but got Unknown
+ //IL_00ca: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00cf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00da: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00e5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00fa: Expected O, but got Unknown
+ //IL_00fb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0100: Unknown result type (might be due to invalid IL or missing references)
+ //IL_010b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0116: Unknown result type (might be due to invalid IL or missing references)
+ //IL_012b: Expected O, but got Unknown
+ //IL_012c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0131: Unknown result type (might be due to invalid IL or missing references)
+ //IL_013c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0147: Unknown result type (might be due to invalid IL or missing references)
+ //IL_015c: Expected O, but got Unknown
+ //IL_015d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0162: Unknown result type (might be due to invalid IL or missing references)
+ //IL_016d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0178: Unknown result type (might be due to invalid IL or missing references)
+ //IL_018d: Expected O, but got Unknown
+ //IL_018e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0193: Unknown result type (might be due to invalid IL or missing references)
+ //IL_019e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01a9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01be: Expected O, but got Unknown
+ //IL_01bf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01c4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01cf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01da: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01ef: Expected O, but got Unknown
+ //IL_01f0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_01f5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0200: Unknown result type (might be due to invalid IL or missing references)
+ //IL_020b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0220: Expected O, but got Unknown
+ //IL_0221: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0226: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0231: Unknown result type (might be due to invalid IL or missing references)
+ //IL_023c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0251: Expected O, but got Unknown
+ //IL_0252: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0257: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0262: Unknown result type (might be due to invalid IL or missing references)
+ //IL_026d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0282: Expected O, but got Unknown
+ //IL_0283: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0288: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0293: Unknown result type (might be due to invalid IL or missing references)
+ //IL_029e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02b3: Expected O, but got Unknown
+ //IL_02b4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02b9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02c4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02cf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02e4: Expected O, but got Unknown
+ //IL_02e5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02ea: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02f5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0300: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0315: Expected O, but got Unknown
+ //IL_0316: Unknown result type (might be due to invalid IL or missing references)
+ //IL_031b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0326: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0331: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0346: Expected O, but got Unknown
+ //IL_0347: Unknown result type (might be due to invalid IL or missing references)
+ //IL_034c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0357: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0362: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0377: Expected O, but got Unknown
+ //IL_0378: Unknown result type (might be due to invalid IL or missing references)
+ //IL_037d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0388: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0393: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03a8: Expected O, but got Unknown
+ //IL_03a9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03ae: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03b9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03c4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03d9: Expected O, but got Unknown
+ return new List<FiltroPersonalizado>
+ {
+ new FiltroPersonalizado
+ {
+ Propriedade = "Id",
+ Nome = "ID",
+ Tipo = typeof(long)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Controle.Fornecedor.NomeSocial",
+ Nome = "FORNECEDOR",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Controle.Fornecedor.Ativo",
+ Nome = "FORNECEDOR ATIVO",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Historico",
+ Nome = "HISTÓRICO",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Parcela",
+ Nome = "PARCELA",
+ Tipo = typeof(int)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Documento",
+ Nome = "DOCUMENTO",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Competencia",
+ Nome = "COMPETÊNCIA",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Complemento",
+ Nome = "COMPLEMENTO",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Vencimento",
+ Nome = "VENCIMENTO",
+ Tipo = typeof(DateTime)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Valor",
+ Nome = "VALOR",
+ Tipo = typeof(decimal)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Baixa",
+ Nome = "DATA BAIXA",
+ Tipo = typeof(DateTime)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "ValorPago",
+ Nome = "VALOR PAGO",
+ Tipo = typeof(decimal)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Pagamento",
+ Nome = "PAGAMENTO",
+ Tipo = typeof(DateTime)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Conta.Descricao",
+ Nome = "CONTA",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Controle.Plano.Descricao",
+ Nome = "PLANO DE CONTAS",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Controle.Centro.Descricao",
+ Nome = "CENTRO DE CUSTO",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Sinal",
+ Nome = "SINAL",
+ Tipo = typeof(Enum)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "TipoPagamento",
+ Nome = "FORMA PAGAMENTO",
+ Tipo = typeof(Enum)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Observacao",
+ Nome = "OBSERVAÇÃO",
+ Tipo = typeof(string)
+ },
+ new FiltroPersonalizado
+ {
+ Propriedade = "Controle.Plano.Nome",
+ Nome = "PLANO",
+ Tipo = typeof(string)
+ }
+ };
+ }
+
+ public static List<ParametrosRelatorio> ColunasRelatorio<T>(Relatorio relatorio, List<ParametrosRelatorio> parametrosAdicionados)
+ {
+ //IL_00a3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00a8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00cd: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00de: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ef: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00ff: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0100: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0106: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0117: Unknown result type (might be due to invalid IL or missing references)
+ //IL_011e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0143: Expected O, but got Unknown
+ List<ParametrosRelatorio> list = new List<ParametrosRelatorio>();
+ foreach (PropertyInfo pi in from x in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
+ orderby x.GetDescriptionAttribute()
+ select x)
+ {
+ if (!(pi.Name == "ValidationEvent") && !(pi.GetTypeAttribute() == "INVALID") && !parametrosAdicionados.Any((ParametrosRelatorio x) => x.Campo == pi.Name))
+ {
+ ParametrosRelatorio val = new ParametrosRelatorio();
+ ParametrosRelatorio? obj = ((IEnumerable<ParametrosRelatorio>)parametrosAdicionados).FirstOrDefault((Func<ParametrosRelatorio, bool>)((ParametrosRelatorio x) => x.IdUsuario != 0L && x.Campo == pi.Name));
+ val.Id = ((obj != null) ? obj.Id : 0);
+ val.Campo = pi.Name;
+ val.Header = pi.GetDescriptionAttribute();
+ val.IdUsuario = ((DomainBase)Recursos.Usuario).Id;
+ val.Relatorio = relatorio;
+ val.Tipo = pi.GetTypeAttribute();
+ val.Width = 0;
+ ParametrosRelatorio? obj2 = ((IEnumerable<ParametrosRelatorio>)parametrosAdicionados).FirstOrDefault((Func<ParametrosRelatorio, bool>)((ParametrosRelatorio x) => x.Campo == pi.Name));
+ val.Ordem = ((obj2 != null) ? obj2.Ordem : 0);
+ ParametrosRelatorio item = val;
+ list.Add(item);
+ }
+ }
+ return list;
+ }
+
+ public static List<ParametrosTotalizacao> TotalizacoesRelatorio<T>(Relatorio relatorio, List<ParametrosTotalizacao> parametrosAdicionados)
+ {
+ //IL_000c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0050: Expected I4, but got Unknown
+ //IL_0395: Unknown result type (might be due to invalid IL or missing references)
+ //IL_039a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03bf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03d0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03e1: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03f1: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03f2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03fa: Expected O, but got Unknown
+ List<ParametrosTotalizacao> list = new List<ParametrosTotalizacao>();
+ List<string> list2 = new List<string>();
+ switch (relatorio - 2)
+ {
+ case 0:
+ case 1:
+ list2.Add("PremioTotal");
+ list2.Add("PremioLiquido");
+ list2.Add("MediaComissao");
+ list2.Add("ComissaoGerada");
+ list2.Add("Cancelamentos");
+ list2.Add("Novos");
+ list2.Add("NegociosProprios");
+ list2.Add("Renovacoes");
+ list2.Add("SegurosNovos");
+ list2.Add("Apolices");
+ list2.Add("Endossos");
+ list2.Add("Faturas");
+ list2.Add("TotalGeral");
+ list2.Add("MediaPonderada");
+ break;
+ case 2:
+ list2.Add("Cancelamentos");
+ list2.Add("Novos");
+ list2.Add("Renovacoes");
+ list2.Add("Apolices");
+ list2.Add("Endossos");
+ list2.Add("Faturas");
+ list2.Add("TotalProspeccao");
+ list2.Add("TotalGeral");
+ list2.Add("PremioTotal");
+ list2.Add("PremioLiquido");
+ list2.Add("ComissaoGerada");
+ break;
+ case 3:
+ list2.Add("ComissaoRecebidaBruta");
+ list2.Add("ComissaoRecebidaLiquida");
+ list2.Add("ComissaoPrevista");
+ list2.Add("Repasse");
+ list2.Add("Impostos");
+ list2.Add("PremioTotal");
+ list2.Add("PremioLiquido");
+ break;
+ case 4:
+ case 14:
+ list2.Add("ComissaoPrevista");
+ list2.Add("TotalPrevista");
+ list2.Add("TotalGeral");
+ list2.Add("TotalParcela");
+ break;
+ case 7:
+ case 8:
+ list2.Add("Liquidado");
+ list2.Add("ValorLiquidado");
+ list2.Add("Pendente");
+ list2.Add("TotalGeral");
+ list2.Add("TotalClientes");
+ list2.Add("TotalTerceiros");
+ break;
+ case 6:
+ list2.Add("PremioTotal");
+ list2.Add("PremioLiquido");
+ list2.Add("ComissaoRecebidaBruta");
+ list2.Add("MediaComissao");
+ list2.Add("TotalPrevista");
+ list2.Add("ComissaoGerada");
+ list2.Add("Cancelamentos");
+ list2.Add("Novos");
+ list2.Add("Renovacoes");
+ list2.Add("Apolices");
+ list2.Add("Endossos");
+ list2.Add("Faturas");
+ list2.Add("TotalGeral");
+ break;
+ }
+ foreach (PropertyInfo pi in from x in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
+ orderby x.GetDescriptionAttribute()
+ select x)
+ {
+ if (!(pi.Name == "ValidationEvent") && !(pi.GetTypeAttribute() == "INVALID") && list2.Contains(pi.Name) && !(pi.Name == "Agrupamento") && !parametrosAdicionados.Any((ParametrosTotalizacao x) => x.Campo == pi.Name))
+ {
+ ParametrosTotalizacao val = new ParametrosTotalizacao();
+ ParametrosTotalizacao? obj = ((IEnumerable<ParametrosTotalizacao>)parametrosAdicionados).FirstOrDefault((Func<ParametrosTotalizacao, bool>)((ParametrosTotalizacao x) => x.IdUsuario != 0L && x.Campo == pi.Name));
+ val.Id = ((obj != null) ? obj.Id : 0);
+ val.Campo = pi.Name;
+ val.Header = pi.GetDescriptionAttribute();
+ val.IdUsuario = ((DomainBase)Recursos.Usuario).Id;
+ val.Relatorio = relatorio;
+ ParametrosTotalizacao item = val;
+ list.Add(item);
+ }
+ }
+ return list;
+ }
+
+ public static async Task<List<string>> OcultarColunas<T>(Relatorio relatorio)
+ {
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000f: Unknown result type (might be due to invalid IL or missing references)
+ List<string> filtros = new List<string>();
+ List<ParametrosRelatorio> list = await new ConfuguracoesServico().BuscarParametros(relatorio);
+ if (list == null || list.Count == 0)
+ {
+ return filtros;
+ }
+ list = await GetRestricoesColunas(list);
+ PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ foreach (PropertyInfo pi in properties)
+ {
+ object obj = pi.GetCustomAttributes(typeof(TipoAttribute), inherit: true).FirstOrDefault();
+ string text = "";
+ if (obj != null)
+ {
+ text = ((TipoAttribute)obj).Description;
+ }
+ string descriptionAttribute = pi.GetDescriptionAttribute();
+ if (text == "INVALID")
+ {
+ filtros.Add(descriptionAttribute);
+ }
+ if (!list.Any((ParametrosRelatorio x) => x.Campo == pi.Name) && !(pi.Name == "ValidationEvent"))
+ {
+ filtros.Add(descriptionAttribute);
+ }
+ }
+ return filtros;
+ }
+
+ public static async Task<bool> ExcluirPagamento(VendedorParcela pagamento)
+ {
+ pagamento.DataPagamento = null;
+ ParcelaServico servico = new ParcelaServico
+ {
+ Sucesso = true
+ };
+ await servico.Save(pagamento);
+ return servico.Sucesso;
+ }
+
+ public static TipoTela? ConvertTela(string name)
+ {
+ //IL_0032: Unknown result type (might be due to invalid IL or missing references)
+ return ((IEnumerable<TipoTela>)((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList()).FirstOrDefault((Func<TipoTela, bool>)((TipoTela x) => ValidationHelper.GetEntity((Enum)(object)x) == name));
+ }
+
+ public static string PlacaVencimento(string placa, Categoria? categoria)
+ {
+ //IL_007b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0081: Invalid comparison between Unknown and I4
+ //IL_009a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00a0: Invalid comparison between Unknown and I4
+ //IL_00b9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00bf: Invalid comparison between Unknown and I4
+ //IL_00d8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00de: Invalid comparison between Unknown and I4
+ //IL_00f7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00fd: Invalid comparison between Unknown and I4
+ //IL_0116: Unknown result type (might be due to invalid IL or missing references)
+ //IL_011c: Invalid comparison between Unknown and I4
+ //IL_0135: Unknown result type (might be due to invalid IL or missing references)
+ //IL_013b: Invalid comparison between Unknown and I4
+ //IL_0154: Unknown result type (might be due to invalid IL or missing references)
+ //IL_015a: Invalid comparison between Unknown and I4
+ //IL_0173: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0179: Invalid comparison between Unknown and I4
+ if (string.IsNullOrEmpty(placa))
+ {
+ return "";
+ }
+ switch (placa.Substring(placa.Length - 1, 1))
+ {
+ case "1":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "ABRIL";
+ }
+ return "SETEMBRO";
+ case "2":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "MAIO";
+ }
+ return "SETEMBRO";
+ case "3":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "JUNHO";
+ }
+ return "OUTUBRO";
+ case "4":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "JULHO";
+ }
+ return "OUTUBRO";
+ case "5":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "AGOSTO";
+ }
+ return "OUTUBRO";
+ case "6":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "AGOSTO";
+ }
+ return "NOVEMBRO";
+ case "7":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "SETEMBRO";
+ }
+ return "NOVEMBRO";
+ case "8":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "OUTUBRO";
+ }
+ return "NOVEMBRO";
+ case "9":
+ if (!categoria.HasValue || (int)categoria.GetValueOrDefault() != 4)
+ {
+ return "NOVEMBRO";
+ }
+ return "DEZEMBRO";
+ case "0":
+ return "DEZEMBRO";
+ default:
+ return "";
+ }
+ }
+
+ public static ParentescoVinculo? ParentescoInverso(ParentescoVinculo? parentesco)
+ {
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0013: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0014: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0076: Expected I4, but got Unknown
+ return parentesco switch
+ {
+ 0L => (ParentescoVinculo)1,
+ 1L => (ParentescoVinculo)0,
+ 3L => (ParentescoVinculo)4,
+ 4L => (ParentescoVinculo)3,
+ 5L => (ParentescoVinculo)6,
+ 6L => (ParentescoVinculo)5,
+ 7L => (ParentescoVinculo)8,
+ 8L => (ParentescoVinculo)7,
+ 10L => (ParentescoVinculo)11,
+ 11L => (ParentescoVinculo)10,
+ 13L => (ParentescoVinculo)14,
+ 14L => (ParentescoVinculo)13,
+ 19L => (ParentescoVinculo)20,
+ 20L => (ParentescoVinculo)19,
+ 22L => (ParentescoVinculo)21,
+ 21L => (ParentescoVinculo)22,
+ _ => parentesco,
+ };
+ }
+
+ public static string DiaDaSemana(this int? dia)
+ {
+ if (!dia.HasValue)
+ {
+ return "";
+ }
+ return (DayOfWeek)dia.Value switch
+ {
+ DayOfWeek.Sunday => "DOMINGO",
+ DayOfWeek.Monday => "SEGUNDA-FEIRA",
+ DayOfWeek.Tuesday => "TERÇA-FEIRA",
+ DayOfWeek.Wednesday => "QUARTA-FEIRA",
+ DayOfWeek.Thursday => "QUINTA-FEIRA",
+ DayOfWeek.Friday => "SEXTA-FEIRA",
+ DayOfWeek.Saturday => "SABADO",
+ _ => "",
+ };
+ }
+
+ public static string GetBody(this string html)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ HtmlDocument val = new HtmlDocument();
+ val.LoadHtml(html);
+ HtmlNode obj = val.DocumentNode.SelectSingleNode("//body");
+ if (obj == null)
+ {
+ return null;
+ }
+ return obj.InnerHtml;
+ }
+
+ public static string GerarGrafico(List<ValorSintetico> sinteticoLista)
+ {
+ string rows = "['NOME', 'VALOR'], ";
+ sinteticoLista.ForEach(delegate(ValorSintetico x)
+ {
+ if (x.Indice != "TOTAL" && x.Valor > 0m)
+ {
+ rows = rows + "[`" + x.Indice + " " + x.Porcentagem + "`, " + x.Valor.ToString("F2", CultureInfo.InvariantCulture) + "], ";
+ }
+ });
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append("<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>");
+ stringBuilder.Append("<script type=\"text/javascript\">");
+ stringBuilder.Append("google.charts.load(\"current\", {packages:[\"corechart\"]});");
+ stringBuilder.Append("google.charts.setOnLoadCallback(drawChart);");
+ stringBuilder.Append("function drawChart() {");
+ stringBuilder.Append("var data = google.visualization.arrayToDataTable([" + rows + "]);");
+ stringBuilder.Append("var options = { pieHole:0.4, chartArea:{top:100,width:'100%',height:'100%'}, pieSliceText:'none', enableInteractivity:false, legend:{alignment:'center', position:'top', maxLines:6}, pieStartAngle: 50 };");
+ stringBuilder.Append("var chart = new google.visualization.PieChart(document.getElementById('donutchart'));");
+ stringBuilder.Append("chart.draw(data, options); }");
+ stringBuilder.Append("</script>");
+ return stringBuilder.ToString();
+ }
+
+ public static string GerarGraficoUnico(List<List<ValorSintetico>> sinteticosListas)
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append("<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>");
+ stringBuilder.Append("<script type=\"text/javascript\">");
+ stringBuilder.Append("google.charts.load(\"current\", {packages:[\"corechart\"]});");
+ stringBuilder.Append("google.charts.setOnLoadCallback(drawAllCharts);");
+ stringBuilder.Append("function drawAllCharts() {");
+ stringBuilder.Append("var data;");
+ stringBuilder.Append("var chart;");
+ stringBuilder.Append("var options = { pieHole:0.4, chartArea:{left: 0,width:'100%',height:'100%'}, pieSliceText:'none', enableInteractivity:false, legend:{alignment:'center'}, pieStartAngle: 50 };");
+ int num = 0;
+ foreach (List<ValorSintetico> sinteticosLista in sinteticosListas)
+ {
+ string rows = "['NOME', 'VALOR'], ";
+ sinteticosLista.ForEach(delegate(ValorSintetico x)
+ {
+ if (x.Indice != "TOTAL")
+ {
+ string text = $"{x.Valor}";
+ if (x.Unidate != null && x.Unidate.Equals("R$"))
+ {
+ text = $"{x.Valor:c2}";
+ }
+ rows = rows + "[`" + x.Indice + " \n" + text + "\n" + x.Porcentagem + "`, " + x.Valor.ToString("F2", CultureInfo.InvariantCulture) + "], ";
+ }
+ });
+ stringBuilder.Append("data = google.visualization.arrayToDataTable([" + rows + "]);");
+ stringBuilder.Append($"chart = new google.visualization.PieChart(document.getElementById('donutchart{num}'));");
+ stringBuilder.Append("chart.draw(data, options);");
+ num++;
+ }
+ stringBuilder.Append("}");
+ stringBuilder.Append("</script>");
+ return stringBuilder.ToString();
+ }
+
+ [IteratorStateMachine(typeof(_003CDistinctBy_003Ed__55<, >))]
+ public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
+ {
+ //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
+ return new _003CDistinctBy_003Ed__55<TSource, TKey>(-2)
+ {
+ _003C_003E3__source = source,
+ _003C_003E3__keySelector = keySelector
+ };
+ }
+
+ public static string Clear(this string stringToClean)
+ {
+ if (stringToClean != null)
+ {
+ return Regex.Replace(stringToClean, "[^\\d]", string.Empty);
+ }
+ return null;
+ }
+
+ public static string RemoverAcentos(string text)
+ {
+ string source = text.Normalize(NormalizationForm.FormD);
+ StringBuilder stringBuilder = new StringBuilder();
+ foreach (char item in from c in source
+ let unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c)
+ where unicodeCategory != UnicodeCategory.NonSpacingMark
+ select c)
+ {
+ stringBuilder.Append(item);
+ }
+ return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
+ }
+
+ public static Cor? GetCor(string text)
+ {
+ //IL_0031: Unknown result type (might be due to invalid IL or missing references)
+ if (text.Contains("outro"))
+ {
+ return (Cor)16;
+ }
+ if (Enum.TryParse<Cor>(text, ignoreCase: true, out Cor _))
+ {
+ return (Cor)Enum.Parse(typeof(Cor), text, ignoreCase: true);
+ }
+ return null;
+ }
+
+ public static Correcao? GetCorrecao(string text)
+ {
+ if (text.Contains("mercado"))
+ {
+ return (Correcao)0;
+ }
+ if (text.Contains("determinado"))
+ {
+ return (Correcao)1;
+ }
+ return null;
+ }
+
+ public static TabelaReferencia? GetTabelaReferencia(string text)
+ {
+ //IL_001c: Unknown result type (might be due to invalid IL or missing references)
+ if (Enum.TryParse<TabelaReferencia>(text, ignoreCase: true, out TabelaReferencia _))
+ {
+ return (TabelaReferencia)Enum.Parse(typeof(TabelaReferencia), text, ignoreCase: true);
+ }
+ return null;
+ }
+
+ public static Categoria? GetCategoria(string text)
+ {
+ //IL_0094: Unknown result type (might be due to invalid IL or missing references)
+ if (text.Contains("caminhao") || text.Contains("caminhão"))
+ {
+ return (Categoria)4;
+ }
+ if (text.Contains("onibus") || text.Contains("ônibus"))
+ {
+ return (Categoria)6;
+ }
+ if (text.Contains("utilitario") || text.Contains("utilitário"))
+ {
+ return (Categoria)6;
+ }
+ if (text.Contains("moto"))
+ {
+ return (Categoria)9;
+ }
+ if (Enum.TryParse<Categoria>(text, ignoreCase: true, out Categoria _))
+ {
+ return (Categoria)Enum.Parse(typeof(Categoria), text, ignoreCase: true);
+ }
+ return null;
+ }
+
+ public static TipoCobertura? GetTipoCobertura(string text)
+ {
+ //IL_0086: Unknown result type (might be due to invalid IL or missing references)
+ if (text.Contains("incendio") || text.Contains("incêndio"))
+ {
+ return (TipoCobertura)2;
+ }
+ if (text.Contains("roubo") && text.Contains("furto"))
+ {
+ return (TipoCobertura)5;
+ }
+ if (text.Contains("terceiros"))
+ {
+ return (TipoCobertura)3;
+ }
+ if (text.Contains("compreensiva"))
+ {
+ return (TipoCobertura)1;
+ }
+ if (Enum.TryParse<TipoCobertura>(text, ignoreCase: true, out TipoCobertura _))
+ {
+ return (TipoCobertura)Enum.Parse(typeof(TipoCobertura), text, ignoreCase: true);
+ }
+ return null;
+ }
+
+ public static Isencao? GetIsencao(string text)
+ {
+ if (text.Contains("sem"))
+ {
+ return (Isencao)0;
+ }
+ if (text.Contains("ipi") && text.Contains("icms"))
+ {
+ return (Isencao)3;
+ }
+ if (text.Contains("ipi"))
+ {
+ return (Isencao)2;
+ }
+ if (text.Contains("icms"))
+ {
+ return (Isencao)1;
+ }
+ return null;
+ }
+
+ public static Combustivel? GetCombustivel(string text)
+ {
+ //IL_015d: Unknown result type (might be due to invalid IL or missing references)
+ if (text.Contains("flex"))
+ {
+ return (Combustivel)4;
+ }
+ if (text.Contains("gasolina") && (text.Contains("alcool") || text.Contains("álcool")))
+ {
+ if (text.Contains("gnv"))
+ {
+ return (Combustivel)8;
+ }
+ if (text.Contains("eletrico") || text.Contains("elétrico"))
+ {
+ return (Combustivel)12;
+ }
+ return (Combustivel)4;
+ }
+ if (text.Contains("gasolina") && text.Contains("gnv"))
+ {
+ return (Combustivel)7;
+ }
+ if (text.Contains("gasolina") && (text.Contains("eletrico") || text.Contains("elétrico")))
+ {
+ return (Combustivel)9;
+ }
+ if (text.Contains("eletrico") || text.Contains("elétrico"))
+ {
+ return (Combustivel)11;
+ }
+ if (text.Contains("alcool") || text.Contains("álcool"))
+ {
+ return (Combustivel)1;
+ }
+ if (text.Contains("hibrido") || text.Contains("híbrido"))
+ {
+ return (Combustivel)10;
+ }
+ if (text.Contains("outro"))
+ {
+ return (Combustivel)6;
+ }
+ if (Enum.TryParse<Combustivel>(text, ignoreCase: true, out Combustivel _))
+ {
+ return (Combustivel)Enum.Parse(typeof(Combustivel), text, ignoreCase: true);
+ }
+ return null;
+ }
+
+ public static async Task<Fabricante> GetFabricante(string text)
+ {
+ List<Fabricante> list = await new BaseServico().BuscarFabricante(text);
+ return (list.Count < 1) ? null : list.First();
+ }
+
+ 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 = $"{index} {nome}";
+ }
+ if (nome.Length > 30)
+ {
+ nome = nome.Substring(0, 30);
+ }
+ return nome;
+ }
+
+ public static bool IsEmpty(this string html)
+ {
+ int count = Regex.Matches(html, "<body>").Count;
+ bool flag = true;
+ int startIndex = 0;
+ for (int i = 0; i < count; i++)
+ {
+ int num = html.IndexOf("<body>", startIndex, StringComparison.Ordinal) + 6;
+ if (num == 5)
+ {
+ break;
+ }
+ int num2 = html.IndexOf("</body>", startIndex, StringComparison.Ordinal);
+ startIndex = num2 + 7;
+ flag = string.IsNullOrWhiteSpace(html.Substring(num, num2 - num));
+ if (!flag)
+ {
+ break;
+ }
+ }
+ return flag;
+ }
+
+ public static Window IsHosterOpen(string name)
+ {
+ return (Window)(object)((IEnumerable)Application.Current.Windows).OfType<HosterWindow>().ToList().FirstOrDefault(delegate(HosterWindow x)
+ {
+ ContentControl? obj = Extentions.FindVisualChildren<ContentControl>((DependencyObject)(object)x).FirstOrDefault();
+ return ((obj != null) ? ((FrameworkElement)obj).Tag.ToString() : null) == name;
+ });
+ }
+
+ public static DateTime GetNetworkTime()
+ {
+ try
+ {
+ if (StartTime.HasValue)
+ {
+ return StartTime.Value.AddMilliseconds(Stopwatch.ElapsedMilliseconds);
+ }
+ byte[] array = new byte[48];
+ array[0] = 27;
+ IPEndPoint remoteEP = new IPEndPoint(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(remoteEP);
+ socket.ReceiveTimeout = 3000;
+ socket.Send(array);
+ socket.Receive(array);
+ socket.Close();
+ }
+ ulong num = ((ulong)array[40] << 24) | ((ulong)array[41] << 16) | ((ulong)array[42] << 8) | array[43];
+ ulong num2 = ((ulong)array[44] << 24) | ((ulong)array[45] << 16) | ((ulong)array[46] << 8) | array[47];
+ ulong num3 = num * 1000 + num2 * 1000 / 4294967296L;
+ DateTime value = new DateTime(1900, 1, 1).AddMilliseconds((long)num3).ToLocalTime();
+ StartTime = value;
+ Stopwatch = Stopwatch.StartNew();
+ return StartTime.Value;
+ }
+ catch (Exception)
+ {
+ StartTime = DateTime.Now;
+ Stopwatch = Stopwatch.StartNew();
+ return StartTime.Value;
+ }
+ }
+
+ public static TipoPagamento ParseTransactionType(this OfxTransactionType type)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0042: Expected I4, but got Unknown
+ switch ((int)type)
+ {
+ default:
+ return (TipoPagamento)12;
+ case 0:
+ return (TipoPagamento)5;
+ case 1:
+ case 4:
+ return (TipoPagamento)7;
+ case 11:
+ return (TipoPagamento)15;
+ case 6:
+ case 13:
+ return (TipoPagamento)8;
+ case 7:
+ case 12:
+ return (TipoPagamento)10;
+ case 14:
+ return (TipoPagamento)6;
+ case 10:
+ return (TipoPagamento)4;
+ }
+ }
+
+ public static string GeraCartaoVisita(this long id)
+ {
+ try
+ {
+ return HttpUtility.UrlEncode($"{DateTime.Now.Ticks}:{ApplicationHelper.IdFornecedor}:V:{id}".Base64Encode());
+ }
+ catch
+ {
+ }
+ return "";
+ }
+
+ public static string GeraAssistencia(this long id)
+ {
+ try
+ {
+ return HttpUtility.UrlEncode($"{DateTime.Now.Ticks}:{ApplicationHelper.IdFornecedor}:A:{id}".Base64Encode());
+ }
+ catch
+ {
+ }
+ return "";
+ }
+
+ public static long UnixTimeStamp()
+ {
+ return (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
+ }
+
+ public static async Task<string> CriarCartao(this Card card)
+ {
+ return await Connection.Post<string>("Card", card);
+ }
+
+ public static async Task<string> AtualizarCartao(this Card card, string id)
+ {
+ return (await Connection.Put<string>("Card/" + id, card) == null) ? id : null;
+ }
+
+ public static async Task<string> CriarAssistencia(this Assistance assistance)
+ {
+ return await Connection.Post<string>("Assistance", assistance);
+ }
+
+ public static async Task<string> Criarlogo(this Logo logo)
+ {
+ return await Connection.Post<string>("Card/Logo", logo);
+ }
+
+ public static async Task<string> Atualizarlogo(this Logo logo, string id)
+ {
+ return await Connection.Put<string>("Card/Logo/" + id, logo);
+ }
+
+ public static async Task<string> CriarSeguradora(this AssistenciaCia cia)
+ {
+ return await Connection.Post<string>("Assistance/Seguradora", cia);
+ }
+
+ public static async Task<string> AtualizarSeguradora(this AssistenciaCia cia, string id)
+ {
+ return await Connection.Put<string>("Assistance/Seguradora/" + id, cia);
+ }
+
+ public static async Task<string> AtualizarAssistencia(this Assistance assistance, string id)
+ {
+ return (await Connection.Put<string>("Assistance/" + id, assistance) == null) ? id : null;
+ }
+
+ public static bool EnviarWhatsapp(this string numero, string anotacoes = null)
+ {
+ Uri uri = (string.IsNullOrEmpty(anotacoes) ? Recursos.WhatsAppLink.SetQuery("phone", numero) : Recursos.WhatsAppLink.AddQuery("phone", numero).SetQuery("text", anotacoes));
+ try
+ {
+ Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
+ return true;
+ }
+ catch (Exception)
+ {
+ uri.AbsoluteUri.CopyToClipboard();
+ return false;
+ }
+ }
+
+ public static bool ProgramaEmExecucao(this string programName)
+ {
+ return Process.GetProcessesByName(programName).Length != 0;
+ }
+
+ [DllImport("user32.dll")]
+ private static extern bool SetForegroundWindow(IntPtr hWnd);
+
+ [DllImport("user32.dll")]
+ private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
+
+ public static void BringToFront(this string programName)
+ {
+ try
+ {
+ Process[] processesByName = Process.GetProcessesByName(programName);
+ if (processesByName.Length != 0)
+ {
+ IntPtr mainWindowHandle = processesByName[0].MainWindowHandle;
+ ShowWindow(mainWindowHandle, 5);
+ ShowWindow(mainWindowHandle, 9);
+ SetForegroundWindow(mainWindowHandle);
+ }
+ }
+ catch (Exception)
+ {
+ }
+ }
+
+ public static List<TupleList> LogList(this List<ValorOriginal> valores, bool restricaoComissao = false)
+ {
+ //IL_0030: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0035: Unknown result type (might be due to invalid IL or missing references)
+ //IL_004b: Expected O, but got Unknown
+ List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>();
+ valores.ForEach(delegate(ValorOriginal x)
+ {
+ if (!restricaoComissao || !x.Campo.ToUpper().Contains("COMISSÃO"))
+ {
+ tuples.Add(new Tuple<string, string, string>(x.Descricao, string.IsNullOrEmpty(x.ValorAtual) ? "NÃO PREENCHIDO" : ((x.ValorAtual == "True") ? "SIM" : ((x.ValorAtual == "False") ? "NÃO" : x.ValorAtual)), ""));
+ }
+ });
+ return new List<TupleList>
+ {
+ new TupleList
+ {
+ Tuples = new ObservableCollection<Tuple<string, string, string>>(tuples)
+ }
+ };
+ }
+
+ public static List<TupleList> LogList(this List<Diferenca> valores, bool restricaoComissao = false)
+ {
+ //IL_0030: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0035: Unknown result type (might be due to invalid IL or missing references)
+ //IL_004b: Expected O, but got Unknown
+ List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>();
+ valores.ForEach(delegate(Diferenca x)
+ {
+ if (!restricaoComissao || !x.Campo.ToUpper().Contains("COMISSÃO"))
+ {
+ tuples.Add(new Tuple<string, string, string>(x.Descricao, string.IsNullOrEmpty(x.ValorAtual) ? "NÃO PREENCHIDO" : ((x.ValorAtual == "True") ? "SIM" : ((x.ValorAtual == "False") ? "NÃO" : x.ValorAtual)), string.IsNullOrEmpty(x.ValorAnterior) ? "NÃO PREENCHIDO" : ((x.ValorAnterior == "True") ? "SIM" : ((x.ValorAnterior == "False") ? "NÃO" : x.ValorAnterior))));
+ }
+ });
+ return new List<TupleList>
+ {
+ new TupleList
+ {
+ Tuples = new ObservableCollection<Tuple<string, string, string>>(tuples)
+ }
+ };
+ }
+
+ public static void CopyToClipboard(this string text)
+ {
+ try
+ {
+ Clipboard.SetText(text);
+ }
+ catch (Exception)
+ {
+ }
+ }
+
+ public static async Task<string> GerarCsv<T>(List<T> Conteudo, IEnumerable<string> colunasExportacao)
+ {
+ PropertyInfo[] source = (from p in typeof(T).GetProperties()
+ where colunasExportacao.Contains(p.Name)
+ select p).ToArray();
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.AppendLine(string.Join(";", source.Select((PropertyInfo p) => p.Name)));
+ foreach (T item in Conteudo)
+ {
+ IEnumerable<string> values = source.Select((PropertyInfo p) => p.GetValue(item, null)?.ToString() ?? string.Empty);
+ stringBuilder.AppendLine(string.Join(";", values));
+ }
+ return stringBuilder.ToString();
+ }
+
+ public static UsoVeiculo? GetUsoveiculo(string text)
+ {
+ //IL_000e: Unknown result type (might be due to invalid IL or missing references)
+ UsoVeiculo result;
+ return (UsoVeiculo)(Enum.TryParse<UsoVeiculo>(text, ignoreCase: true, out result) ? ((int)result) : 0);
+ }
+
+ public static string BoolToString(this bool boolean)
+ {
+ if (!boolean)
+ {
+ return "0";
+ }
+ return "1";
+ }
+
+ public static string ConvertGaragemTrabalhoEstudoCalculo(this GaragemTrabalhoEstudo garagemTrabalhoEstudo)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_001e: Expected I4, but got Unknown
+ switch ((int)garagemTrabalhoEstudo)
+ {
+ case 0:
+ return "0";
+ case 1:
+ return "1";
+ case 2:
+ return "2";
+ case 4:
+ case 5:
+ return "3";
+ default:
+ return string.Empty;
+ }
+ }
+
+ public static string ConvertTipoSeguroCalculo(this TipoSeguro tipoSeguro)
+ {
+ //IL_0000: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0002: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0004: Invalid comparison between Unknown and I4
+ if (tipoSeguro - 1 <= 1)
+ {
+ return "1";
+ }
+ return "0";
+ }
+
+ public static string ConvertTempoHabilitacaoCalculo(this DateTime tempoHabilitacao)
+ {
+ if (tempoHabilitacao == DateTime.MinValue)
+ {
+ return "0";
+ }
+ int num = DateTime.Now.Year - tempoHabilitacao.Year;
+ if (num >= 11)
+ {
+ return "11";
+ }
+ return num.ToString();
+ }
+
+ public static TempoHabilitacao ConvertTempoHabilitacao(int tempoHabilitacao = 0)
+ {
+ if (tempoHabilitacao != 1)
+ {
+ if (tempoHabilitacao != 2)
+ {
+ if (tempoHabilitacao != 3)
+ {
+ if (tempoHabilitacao != 4)
+ {
+ if (tempoHabilitacao != 5)
+ {
+ if (tempoHabilitacao != 6)
+ {
+ if (tempoHabilitacao != 7)
+ {
+ if (tempoHabilitacao != 8)
+ {
+ if (tempoHabilitacao != 9)
+ {
+ if (tempoHabilitacao != 10)
+ {
+ if (tempoHabilitacao < 11)
+ {
+ return (TempoHabilitacao)0;
+ }
+ return (TempoHabilitacao)10;
+ }
+ return (TempoHabilitacao)9;
+ }
+ return (TempoHabilitacao)8;
+ }
+ return (TempoHabilitacao)7;
+ }
+ return (TempoHabilitacao)6;
+ }
+ return (TempoHabilitacao)5;
+ }
+ return (TempoHabilitacao)4;
+ }
+ return (TempoHabilitacao)3;
+ }
+ return (TempoHabilitacao)2;
+ }
+ return (TempoHabilitacao)1;
+ }
+ return (TempoHabilitacao)0;
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/HttpHelper.cs b/Decompiler/Gestor.Application.Helpers/HttpHelper.cs
new file mode 100644
index 0000000..d552c84
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/HttpHelper.cs
@@ -0,0 +1,83 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Linq;
+using System.Net.Http;
+using System.Text;
+using System.Web;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+
+namespace Gestor.Application.Helpers;
+
+public static class HttpHelper
+{
+ public static Uri AddQuery<T>(this Uri uri, string name, T value)
+ {
+ UriBuilder uriBuilder = new UriBuilder(uri);
+ NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(uri.Query);
+ nameValueCollection.Add(name, value?.ToString());
+ uriBuilder.Query = nameValueCollection.ToString();
+ return uriBuilder.Uri;
+ }
+
+ public static Uri SetQuery(this Uri uri, string name, string value, bool escapeValue = true)
+ {
+ UriBuilder uriBuilder = new UriBuilder(uri);
+ Dictionary<string, string> dictionary = uri.ParseQueryString();
+ string value2 = (escapeValue ? Uri.EscapeDataString(value) : value);
+ if (dictionary.ContainsKey(name))
+ {
+ dictionary.Remove(name);
+ }
+ dictionary.Add(name, value2);
+ List<string> values = dictionary.Select((KeyValuePair<string, string> x) => x.Key + "=" + x.Value).ToList();
+ string query = string.Join("&", values);
+ uriBuilder.Query = query;
+ return uriBuilder.Uri;
+ }
+
+ public static Dictionary<string, string> ParseQueryString(this Uri uri)
+ {
+ int startIndex = uri.Query.IndexOf('?') + 1;
+ return (from o in uri.Query.Substring(startIndex).Split(new char[1] { '&' })
+ select o.Split(new char[1] { '=' }) into items
+ where items.Length == 2
+ select items).ToDictionary((string[] pair) => pair[0], (string[] pair) => pair[1]);
+ }
+
+ public static Uri ToUri(this string uri)
+ {
+ Uri.TryCreate(uri, UriKind.Absolute, out Uri result);
+ return result;
+ }
+
+ public static StringContent ToHttpContent<T>(this T content, Encoding encoding = null, string mediaType = "application/json")
+ {
+ //IL_0011: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0017: Expected O, but got Unknown
+ return new StringContent(JsonConvert.SerializeObject((object)content), Encoding.UTF8, mediaType);
+ }
+
+ public static JObject ToJObject(this string jsonString)
+ {
+ try
+ {
+ return JObject.Parse(jsonString);
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ public static JObject ToJObject(this HttpContent content)
+ {
+ return content.ReadAsStringAsync().Result.ToJObject();
+ }
+
+ public static string ToBase64BasicEncode(this string value)
+ {
+ return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/Instancia.cs b/Decompiler/Gestor.Application.Helpers/Instancia.cs
new file mode 100644
index 0000000..b67323b
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/Instancia.cs
@@ -0,0 +1,53 @@
+using System;
+using System.IO;
+using Gestor.Common.Helpers;
+using Gestor.Infrastructure.UnitOfWork.Generic;
+using Gestor.Infrastructure.UnitOfWork.Logic;
+
+namespace Gestor.Application.Helpers;
+
+public class Instancia
+{
+ public static string Conexao;
+
+ public static App App { get; set; }
+
+ public static UnitOfWork Commited => UnitOfWork();
+
+ public static UnitOfWork Read => UnitOfWork(withTransaction: false);
+
+ private static UnitOfWork UnitOfWork(bool withTransaction = true)
+ {
+ //IL_0037: Unknown result type (might be due to invalid IL or missing references)
+ //IL_003d: Expected O, but got Unknown
+ DataBaseParameters.NovoGestor = true;
+ Conexao = Conexao ?? Connection.GetConnection();
+ if (Conexao == null)
+ {
+ return App.ConnectionRetry().Result;
+ }
+ UnitOfWork val = new UnitOfWork(Conexao, withTransaction);
+ if (!((GenericUnitOfWork)val).HasSession)
+ {
+ return App.ConnectionRetry().Result;
+ }
+ return val;
+ }
+
+ public static void ExcluirCfg()
+ {
+ File.Delete("Data_" + Connection.Catalog + ".cfg");
+ File.Delete("File_" + Connection.Catalog + ".cfg");
+ File.Delete("Sign_" + Connection.Catalog + ".cfg");
+ }
+
+ public static void DeleteCfg()
+ {
+ string text = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
+ string text2 = Connection.Catalog + ".cfg";
+ if (File.Exists(text + text2))
+ {
+ File.Delete(text + text2);
+ }
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/InstanciaAssinador.cs b/Decompiler/Gestor.Application.Helpers/InstanciaAssinador.cs
new file mode 100644
index 0000000..4a48b08
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/InstanciaAssinador.cs
@@ -0,0 +1,22 @@
+using Assinador.Infrastructure.UnitOfWork.Logic;
+
+namespace Gestor.Application.Helpers;
+
+public class InstanciaAssinador
+{
+ public static string EnderecoConexao;
+
+ public static App App { get; set; }
+
+ public static UnitOfWork Commited => UnitOfWork();
+
+ public static UnitOfWork Read => UnitOfWork(withTransaction: false);
+
+ private static UnitOfWork UnitOfWork(bool withTransaction = true)
+ {
+ //IL_001a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0020: Expected O, but got Unknown
+ EnderecoConexao = EnderecoConexao ?? Connection.GetConnection();
+ return new UnitOfWork(EnderecoConexao, withTransaction);
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/LicenseHelper.cs b/Decompiler/Gestor.Application.Helpers/LicenseHelper.cs
new file mode 100644
index 0000000..65b9dee
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/LicenseHelper.cs
@@ -0,0 +1,455 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Threading.Tasks;
+using Agger.Registro;
+using Gestor.Common.Helpers;
+using Gestor.Common.Validation;
+using Gestor.Model.API;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.License;
+using Microsoft.Win32;
+using Newtonsoft.Json;
+
+namespace Gestor.Application.Helpers;
+
+public class LicenseHelper
+{
+ public static int? DiasRestantes { get; set; }
+
+ public static StatusLicenca Status { get; set; } = (StatusLicenca)1;
+
+
+ public static List<Licenca> Produtos { get; set; }
+
+ public static Instalacao Instalacao { get; set; }
+
+ public static DateTime DataAtual { get; private set; }
+
+ private string _guid { get; set; }
+
+ public async Task<bool> VerificarRegistro()
+ {
+ return await Task.Run(delegate
+ {
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000b: Expected O, but got Unknown
+ RegistryHelper val = new RegistryHelper(ApplicationHelper.Subkey);
+ if (string.IsNullOrEmpty(val.Read("NS", true)))
+ {
+ return false;
+ }
+ string s = EncryptionHelper.Decrypt(val.Read("CUSTOMER", true));
+ if (!long.TryParse(s, out var _))
+ {
+ ApplicationHelper.IdFornecedor = long.Parse(Connection.Get<string>("Configuration/Customer").Result);
+ val.Write<string>("CUSTOMER", EncryptionHelper.Encrypt(ApplicationHelper.IdFornecedor.ToString()), true);
+ }
+ else
+ {
+ ApplicationHelper.IdFornecedor = long.Parse(s);
+ }
+ string text = Connection.Get<string>("Installation/Time", autorizar: false).Result ?? Funcoes.GetNetworkTime().ToString("d");
+ DataAtual = DateTime.Parse(text);
+ val.Write<string>("CURRENTDATE", EncryptionHelper.Encrypt(text), true);
+ val.Write<string>("DATE", text, true);
+ ApplicationHelper.Beta = Connection.Get<List<object>>($"Configuration/Customer/{ApplicationHelper.IdFornecedor}").Result?.Any((object x) => x.ToString().Contains("\"Tipo\": 45")) ?? false;
+ Address.Beta = ApplicationHelper.Beta;
+ return true;
+ });
+ }
+
+ public async Task<Tuple<bool, string>> VerificarAcesso()
+ {
+ return await Task.Run(delegate
+ {
+ //IL_000b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0011: Expected O, but got Unknown
+ //IL_053f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0545: Invalid comparison between Unknown and I4
+ //IL_0547: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0555: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02d4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_035e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0363: Unknown result type (might be due to invalid IL or missing references)
+ //IL_036f: Expected O, but got Unknown
+ //IL_03b1: Unknown result type (might be due to invalid IL or missing references)
+ //IL_040b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03d7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03dc: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03e3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03ef: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03f7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03fe: Unknown result type (might be due to invalid IL or missing references)
+ //IL_040a: Expected O, but got Unknown
+ RegistryHelper val = new RegistryHelper(ApplicationHelper.Subkey);
+ DateTime now = Funcoes.GetNetworkTime();
+ DateTime today = now.Date;
+ if (ApplicationHelper.Conectado)
+ {
+ List<Access> result = Connection.Get<List<Access>>($"Access/Customer/{ApplicationHelper.IdFornecedor}").Result;
+ List<long> liberados = new List<long> { 2L, 3L, 4L, 5L, 24L, 10024L };
+ Produtos = (from x in result
+ group x by new { x.ProductId, x.Status }).Select(x =>
+ {
+ //IL_0014: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0019: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0038: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00b0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00cd: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0102: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0127: Expected O, but got Unknown
+ Licenca val2 = new Licenca
+ {
+ Produto = (Produto)x.Key.ProductId.GetValueOrDefault()
+ };
+ AccessControl? obj2 = (from l in x.SelectMany((Access c) => c.Control)
+ orderby l.Expiration descending
+ select l).FirstOrDefault();
+ val2.Liberacao = ((obj2 != null) ? obj2.Expiration : now.AddDays(-1.0));
+ val2.AcessoLiberado = x.All(delegate(Access l)
+ {
+ if (!l.AgreementId.HasValue || !liberados.Contains(l.AgreementId.Value))
+ {
+ AccessControl? obj3 = (from d in x.SelectMany((Access c) => c.Control)
+ orderby d.Expiration descending
+ select d).FirstOrDefault();
+ if (obj3 == null)
+ {
+ return false;
+ }
+ return obj3.Expiration >= today;
+ }
+ return true;
+ });
+ val2.Quantidade = (int)x.Sum((Access l) => l.Ammount.GetValueOrDefault());
+ val2.Status = int.Parse(x.Key.Status ?? "1");
+ return val2;
+ }).ToList();
+ if (Produtos == null || Produtos.Count == 0 || Produtos.All((Licenca x) => x.Status == 3))
+ {
+ val.Write<string>("EXPIRATION", EncryptionHelper.Encrypt(now.AddDays(-1.0).ToString("d")), true);
+ val.Write<string>("BLOCK", EncryptionHelper.Encrypt("TRUE"), true);
+ Status = (StatusLicenca)3;
+ return new Tuple<bool, string>(item1: false, "");
+ }
+ Licenca? obj = ((IEnumerable<Licenca>)Produtos.OrderBy((Licenca x) => x.Liberacao)).FirstOrDefault((Func<Licenca, bool>)((Licenca x) => !x.AcessoLiberado && x.Status == 1));
+ DateTime dateTime = ((obj != null) ? obj.Liberacao : now);
+ DiasRestantes = (int)(dateTime - today).TotalDays;
+ val.Write<string>("EXPIRATION", EncryptionHelper.Encrypt(dateTime.ToString("d")), true);
+ val.Write<string>("BLOCK", (dateTime >= today) ? EncryptionHelper.Encrypt("FALSE") : EncryptionHelper.Encrypt("TRUE"), true);
+ bool flag = Produtos.Any((Licenca x) => (int)x.Produto == 1 && x.Status == 4);
+ val.Write<string>("CONSULTA", EncryptionHelper.Encrypt(flag.ToString().ToUpper()), true);
+ if (flag)
+ {
+ Status = (StatusLicenca)2;
+ }
+ Status = (StatusLicenca)((dateTime < today) ? 1 : 0);
+ if (Produtos.Any((Licenca x) => (int)x.Produto == 1) && (int)Status == 0)
+ {
+ val.Write<string>("P1", EncryptionHelper.Encrypt("1$P1#" + ApplicationHelper.NumeroSerial), true);
+ val.Write<string>("P5", EncryptionHelper.Encrypt("1$P1#" + ApplicationHelper.NumeroSerial), true);
+ val.Write<string>("M1", EncryptionHelper.Encrypt("TRUE"), true);
+ }
+ string text = JsonConvert.SerializeObject((object)Produtos.Where((Licenca x) => x.Status == 1), (Formatting)1, new JsonSerializerSettings
+ {
+ ReferenceLoopHandling = (ReferenceLoopHandling)1
+ });
+ val.Write<string>("PRODUTOS", EncryptionHelper.Encrypt(text), true);
+ if (Produtos.Find((Licenca p) => (int)p.Produto == 86) != null)
+ {
+ return new Tuple<bool, string>(item1: true, EnumHelper.GetDescription<StatusLicenca>(Status));
+ }
+ if (ValidationHelper.IsNotNullOrEmpty(AssinadorHelper.Key().Result))
+ {
+ Produtos.Add(new Licenca
+ {
+ AcessoLiberado = true,
+ Liberacao = today,
+ Produto = (Produto)86,
+ Quantidade = 0,
+ Status = 1
+ });
+ }
+ return new Tuple<bool, string>(item1: true, EnumHelper.GetDescription<StatusLicenca>(Status));
+ }
+ if ((today - DataAtual).TotalDays > 2.0)
+ {
+ return new Tuple<bool, string>(item1: true, "DATA INVÁLIDA");
+ }
+ DiasRestantes = (int)(DateTime.Parse(EncryptionHelper.Decrypt(val.Read("EXPIRATION", true))).AddDays(5.0) - DataAtual).TotalDays;
+ if (DiasRestantes < 1)
+ {
+ return new Tuple<bool, string>(item1: true, "SISTEMA BLOQUEADO");
+ }
+ if (EncryptionHelper.Decrypt(val.Read("BLOCK", true)) == "TRUE")
+ {
+ return new Tuple<bool, string>(item1: true, "SISTEMA BLOQUEADO");
+ }
+ if (EncryptionHelper.Decrypt(val.Read("CONSULTA", true)) == "TRUE")
+ {
+ Status = (StatusLicenca)2;
+ }
+ string text2 = EncryptionHelper.Decrypt(val.Read("PRODUTOS", true));
+ if (string.IsNullOrEmpty(text2))
+ {
+ Status = (StatusLicenca)3;
+ return new Tuple<bool, string>(item1: false, "SISTEMA CANCELADO");
+ }
+ Produtos = JsonConvert.DeserializeObject<List<Licenca>>(text2);
+ Status = (StatusLicenca)(((int)Status == 2) ? ((int)Status) : 0);
+ return new Tuple<bool, string>(item1: true, EnumHelper.GetDescription<StatusLicenca>(Status));
+ });
+ }
+
+ public async Task<bool> VerificarMaquina()
+ {
+ return await Task.Run(delegate
+ {
+ //IL_0005: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000b: Expected O, but got Unknown
+ //IL_029d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02a2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02ad: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02b8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02c0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02cb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02d6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02e6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02f6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0301: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0346: Expected O, but got Unknown
+ RegistryHelper val = new RegistryHelper(ApplicationHelper.Subkey);
+ string macAddress = GetMacAddress();
+ string value = val.Read("MACHINEID", false);
+ if (string.IsNullOrEmpty(value))
+ {
+ value = GetMachineSerial();
+ val.Write<string>("MACHINEID", EncryptionHelper.Encrypt(macAddress + " " + value), false);
+ }
+ string[] array = EncryptionHelper.Decrypt(val.Read("MACHINEID", false)).Split(new char[1] { ' ' });
+ string text = ((array.Length > 1) ? array[1] : array[0]);
+ if (ApplicationHelper.Conectado)
+ {
+ List<Instalacao> result = Connection.Get<List<Instalacao>>("Installation/Machine/" + text + "/GerenciadorList").Result;
+ if (!Guid.TryParse(text, out var _))
+ {
+ text = GetMachineSerial();
+ }
+ _guid = text;
+ Instalacao = result?.FirstOrDefault((Func<Instalacao, bool>)((Instalacao x) => x.IdFornecedor == ApplicationHelper.IdFornecedor));
+ if (Instalacao != null && Instalacao.IdFornecedor != ApplicationHelper.IdFornecedor)
+ {
+ Instalacao = null;
+ }
+ if (Instalacao != null)
+ {
+ Instalacao.Gerenciador = text;
+ Instalacao.UsuarioId = ((DomainBase)Recursos.Usuario).Id;
+ Instalacao.UsuarioSistema = Recursos.Usuario.Nome;
+ Instalacao.Ip = Recursos.Host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString();
+ Instalacao.UltimoAcesso = DateTime.Now;
+ Instalacao.OSInfo = string.Format("P={0};V={1};x64={2};N={3}", (Environment.OSVersion.Platform == PlatformID.Win32NT) ? "W" : "O", Environment.OSVersion.Version, Environment.Is64BitOperatingSystem ? "1" : "0", GetFrameworkVersion());
+ Instalacao = Connection.Put<Instalacao>("Installation/Machine", Instalacao).Result;
+ val.Write<string>("MACHINEID", EncryptionHelper.Encrypt(macAddress + " " + Instalacao.Gerenciador), false);
+ }
+ val.Write<string>("ACCESS", (Instalacao != null || RegistrarMaquina().Result) ? EncryptionHelper.Encrypt("TRUE") : EncryptionHelper.Encrypt("FALSE"), false);
+ }
+ else if (EncryptionHelper.Decrypt(val.Read("ACCESS", false)) == "TRUE")
+ {
+ Instalacao = new Instalacao
+ {
+ IdFornecedor = ApplicationHelper.IdFornecedor,
+ Data = DataAtual,
+ Gerenciador = text,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ UsuarioId = ((DomainBase)Recursos.Usuario).Id,
+ UsuarioSistema = Recursos.Usuario.Nome,
+ UltimoAcesso = DateTime.Now,
+ Ip = Recursos.Host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString()
+ };
+ }
+ return Produtos.Any((Licenca x) => (int)x.Produto == 1) && (Instalacao != null || RegistrarMaquina().Result);
+ });
+ }
+
+ public async Task<string> Registrar(string chave)
+ {
+ return await Task.Run(delegate
+ {
+ //IL_001f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0029: Expected O, but got Unknown
+ if (string.IsNullOrEmpty(chave))
+ {
+ return "false";
+ }
+ RegistryHelper helper = new RegistryHelper("");
+ string[] array = EncryptionHelper.Decrypt(chave).Split(new char[1] { ' ' });
+ if (array.Length < 2)
+ {
+ return "false";
+ }
+ string text = helper.Verificar(array[0], EncryptionHelper.Encrypt(array[0]));
+ if (text != "false")
+ {
+ if (text == "root")
+ {
+ return "root";
+ }
+ ApplicationHelper.NumeroSerial = array[0];
+ ApplicationHelper.IdFornecedor = long.Parse(Connection.Get<string>("Maintenance/Customer").Result);
+ Instancia.Conexao = null;
+ ApplicationHelper.Subkey = array[0];
+ return "true";
+ }
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ string text2 = Connection.Get<string>("Installation/Time", autorizar: false, verificarConexao: true).Result ?? networkTime.ToString("d");
+ if (!ApplicationHelper.Conectado)
+ {
+ return "false";
+ }
+ DataAtual = DateTime.Parse($"{text2} {networkTime.Hour}:{networkTime.Minute}:{networkTime.Second}");
+ DateTime dateTime = DateTime.Parse(array[1]);
+ if (Math.Abs((DataAtual - dateTime).TotalDays) > 1.0)
+ {
+ return "false";
+ }
+ string text3 = EncryptionHelper.Decrypt(helper.Read("NS", true));
+ string text4 = helper.Read("SERIALS", false);
+ if (string.IsNullOrWhiteSpace(text4) && !string.IsNullOrWhiteSpace(text3))
+ {
+ helper.Write<string>("SERIALS", EncryptionHelper.Encrypt(text3), false);
+ text4 = helper.Read("SERIALS", false);
+ }
+ List<string> source = ((text4 != null) ? EncryptionHelper.Decrypt(text4).Split(new char[1] { ':' }).ToList() : new List<string>());
+ List<string> seriais = new List<string>();
+ source.Distinct().ToList().ForEach(delegate(string x)
+ {
+ if (!(helper.Verificar(x, EncryptionHelper.Encrypt(x)) == "false"))
+ {
+ seriais.Add(x);
+ }
+ });
+ seriais.Add(array[0]);
+ helper.Write<string>("SERIALS", EncryptionHelper.Encrypt(string.Join(":", seriais.Distinct())), false);
+ helper.Serial = ((seriais.Count > 1) ? ("\\" + array[0]) : "");
+ ApplicationHelper.Subkey = ((seriais.Count > 1) ? array[0] : "");
+ ApplicationHelper.NumeroSerial = array[0];
+ string result = Connection.Get<string>("Customer/Name/" + array[0]).Result;
+ helper.Write<string>("PERFIL", result, true);
+ helper.Write<string>("CURRENTDATE", EncryptionHelper.Encrypt(text2), true);
+ helper.Write<string>("DATE", text2, true);
+ helper.Write<string>("NS", EncryptionHelper.Encrypt(array[0]), true);
+ helper.Write<string>("INSTALL", EncryptionHelper.Encrypt(array[0]), true);
+ ApplicationHelper.IdFornecedor = long.Parse(Connection.Get<string>("Maintenance/Customer").Result);
+ helper.Write<string>("CUSTOMER", EncryptionHelper.Encrypt(ApplicationHelper.IdFornecedor.ToString()), true);
+ Instancia.Conexao = null;
+ return "true";
+ });
+ }
+
+ public async Task<List<Instalacao>> GetInstalacoes()
+ {
+ return await Connection.Get<List<Instalacao>>($"Installation/Machine/{ApplicationHelper.IdFornecedor}");
+ }
+
+ private string GetMachineSerial()
+ {
+ if (string.IsNullOrEmpty(_guid))
+ {
+ _guid = Guid.NewGuid().ToString();
+ }
+ return _guid;
+ }
+
+ public async Task<bool> RegistrarMaquina()
+ {
+ return await Task.Run(delegate
+ {
+ //IL_007e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0084: Expected O, but got Unknown
+ //IL_00ac: Unknown result type (might be due to invalid IL or missing references)
+ //IL_00b3: Expected O, but got Unknown
+ if (!ApplicationHelper.Conectado)
+ {
+ return false;
+ }
+ List<Instalacao> result = GetInstalacoes().Result;
+ Licenca? obj = ((IEnumerable<Licenca>)Produtos).FirstOrDefault((Func<Licenca, bool>)((Licenca x) => (int)x.Produto == 1));
+ if (((obj != null) ? obj.Quantidade : 0) <= result.Count((Instalacao x) => x.Gerenciador != null))
+ {
+ return false;
+ }
+ string text = "";
+ RegistryHelper val = new RegistryHelper("");
+ if (Instalacao == null)
+ {
+ string machineSerial = GetMachineSerial();
+ text = EncryptionHelper.Encrypt(GetMacAddress() + " " + machineSerial);
+ Instalacao val2 = new Instalacao();
+ val2.IdFornecedor = ApplicationHelper.IdFornecedor;
+ val2.Data = DataAtual;
+ val2.Gerenciador = machineSerial;
+ val2.NomeMaquina = Environment.MachineName;
+ val2.UsuarioMaquina = Environment.UserName;
+ val2.UsuarioId = ((DomainBase)Recursos.Usuario).Id;
+ val2.UsuarioSistema = Recursos.Usuario.Nome;
+ val2.UltimoAcesso = DateTime.Now;
+ val2.Ip = Recursos.Host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString();
+ val2.OSInfo = string.Format("P={0};V={1};x64={2};N={3}", (Environment.OSVersion.Platform == PlatformID.Win32NT) ? "W" : "O", Environment.OSVersion.Version, Environment.Is64BitOperatingSystem ? "1" : "0", GetFrameworkVersion());
+ Instalacao = val2;
+ }
+ val.Write<string>("MACHINEID", text, false);
+ Instalacao = Connection.Put<Instalacao>("Installation/Machine", Instalacao).Result;
+ return true;
+ });
+ }
+
+ public string GetMacAddress()
+ {
+ IEnumerable<string> values = from ni in NetworkInterface.GetAllNetworkInterfaces()
+ where ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
+ orderby ni.Id descending
+ select ni into x
+ select x.GetPhysicalAddress().ToString();
+ return string.Join("", values);
+ }
+
+ public NetworkInterface FindMacAddress(string macToSearch)
+ {
+ string[] macList = macToSearch.Split(new char[1] { '|' });
+ return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault((NetworkInterface ni) => macList.Contains(ni.GetPhysicalAddress().ToString()));
+ }
+
+ public async Task<Tuple<bool, string>> VerificarVersao()
+ {
+ return new Tuple<bool, string>(bool.Parse(await Connection.Get<string>($"Installation/Version/{ApplicationHelper.IdFornecedor}")), "VERSÃO INDISPONÍVEL");
+ }
+
+ public async Task<string> FindKey()
+ {
+ string text = EncryptionHelper.Decrypt(new RegistryHelper(ApplicationHelper.Subkey).ForceRead("MACHINEID", false));
+ string text2 = (string.IsNullOrEmpty(text) ? (GetMacAddress() + GetMachineSerial()) : text);
+ return await Connection.Get<string>("Installation/Serial/" + text2, autorizar: false);
+ }
+
+ 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";
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/MailHelper.cs b/Decompiler/Gestor.Application.Helpers/MailHelper.cs
new file mode 100644
index 0000000..8a56cdc
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/MailHelper.cs
@@ -0,0 +1,746 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+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.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using CsQuery.ExtensionMethods.Internal;
+using Gestor.Application.ViewModels;
+using Gestor.Common.Helpers;
+using Gestor.Common.Validation;
+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.Http;
+using Google.Apis.Requests;
+using Google.Apis.Services;
+using Google.Apis.Util.Store;
+using Microsoft.Identity.Client;
+using MimeKit;
+
+namespace Gestor.Application.Helpers;
+
+public class MailHelper
+{
+ public async Task<LogEnvio> SendAsync(Credencial credencial, Destinatario destinatario, FiltroArquivoDigital filtro = null, List<MalaDireta> maladireta = null, TipoTela tela = 0, bool confirmarLeitura = false)
+ {
+ //IL_002f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0031: Unknown result type (might be due to invalid IL or missing references)
+ IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
+ TipoTela telaEmail;
+ return await Task.Run((Func<LogEnvio>)delegate
+ {
+ //IL_0007: Unknown result type (might be due to invalid IL or missing references)
+ //IL_000c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0018: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0029: Expected O, but got Unknown
+ //IL_03ba: Unknown result type (might be due to invalid IL or missing references)
+ //IL_03c1: Expected O, but got Unknown
+ //IL_053e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0545: Invalid comparison between Unknown and I4
+ //IL_0607: Unknown result type (might be due to invalid IL or missing references)
+ //IL_060c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_060e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0611: Unknown result type (might be due to invalid IL or missing references)
+ //IL_064b: Expected I4, but got Unknown
+ //IL_0658: Unknown result type (might be due to invalid IL or missing references)
+ //IL_064f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0661: Unknown result type (might be due to invalid IL or missing references)
+ //IL_066a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0673: Unknown result type (might be due to invalid IL or missing references)
+ //IL_067d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0687: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0691: Unknown result type (might be due to invalid IL or missing references)
+ //IL_069b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06a5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06af: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06b9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06c3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e32: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e37: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e43: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e4e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e56: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e58: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e62: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e74: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e86: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0e97: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ea8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0eba: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ec5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ed0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0edb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06cc: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0204: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0209: Unknown result type (might be due to invalid IL or missing references)
+ //IL_020b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_020e: Invalid comparison between Unknown and I4
+ //IL_021d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0222: Unknown result type (might be due to invalid IL or missing references)
+ //IL_022d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_025d: Expected O, but got Unknown
+ //IL_0263: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0268: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0285: Expected O, but got Unknown
+ //IL_0285: Unknown result type (might be due to invalid IL or missing references)
+ //IL_028a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0291: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02a1: Expected O, but got Unknown
+ //IL_029c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0210: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0213: Invalid comparison between Unknown and I4
+ //IL_0828: Unknown result type (might be due to invalid IL or missing references)
+ //IL_082e: Invalid comparison between Unknown and I4
+ //IL_06e8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06ed: Unknown result type (might be due to invalid IL or missing references)
+ //IL_06f9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_070a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0715: Unknown result type (might be due to invalid IL or missing references)
+ //IL_071d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_071f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0729: Unknown result type (might be due to invalid IL or missing references)
+ //IL_073b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_074d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_075e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_076f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0781: Unknown result type (might be due to invalid IL or missing references)
+ //IL_078c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0797: Unknown result type (might be due to invalid IL or missing references)
+ //IL_07a2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02f8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_02ff: Expected O, but got Unknown
+ //IL_030e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0313: Unknown result type (might be due to invalid IL or missing references)
+ //IL_031f: Expected O, but got Unknown
+ //IL_0f1e: Expected O, but got Unknown
+ //IL_0955: Unknown result type (might be due to invalid IL or missing references)
+ //IL_095b: Invalid comparison between Unknown and I4
+ //IL_0833: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0838: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0844: Unknown result type (might be due to invalid IL or missing references)
+ //IL_084f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0861: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0869: Unknown result type (might be due to invalid IL or missing references)
+ //IL_086c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0876: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0888: Unknown result type (might be due to invalid IL or missing references)
+ //IL_089a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_08ab: Unknown result type (might be due to invalid IL or missing references)
+ //IL_08bc: Unknown result type (might be due to invalid IL or missing references)
+ //IL_08ce: Unknown result type (might be due to invalid IL or missing references)
+ //IL_08d9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_08e4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_08ef: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a82: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a88: Invalid comparison between Unknown and I4
+ //IL_0960: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0965: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0971: Unknown result type (might be due to invalid IL or missing references)
+ //IL_097c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_098e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0996: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0999: Unknown result type (might be due to invalid IL or missing references)
+ //IL_09a3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_09b5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_09c7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_09d8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_09e9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_09fb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a06: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a11: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a1c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0baf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bb5: Invalid comparison between Unknown and I4
+ //IL_0a8d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a92: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a9e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0aa9: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0abb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ac3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ac6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ad0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ae2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0af4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b05: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b16: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b28: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b33: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b3e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b49: Unknown result type (might be due to invalid IL or missing references)
+ //IL_07e5: Expected O, but got Unknown
+ //IL_0cdc: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bba: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bbf: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bcb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bd6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0be8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bf0: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bf3: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0bfd: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c0f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c21: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c32: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c43: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c55: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c60: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c6b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0c76: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0930: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0933: Unknown result type (might be due to invalid IL or missing references)
+ //IL_093f: Expected O, but got Unknown
+ //IL_0ce6: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0ceb: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0cf7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d02: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a5d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a60: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0a6c: Expected O, but got Unknown
+ //IL_0b8a: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b8d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0b99: Expected O, but got Unknown
+ //IL_0d1c: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d24: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d2b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d3d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d4f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d60: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d71: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d83: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d8e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0d99: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0da4: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0cb7: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0cba: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0cc6: Expected O, but got Unknown
+ //IL_0de5: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0de8: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0df4: Expected O, but got Unknown
+ LogEnvio log = new LogEnvio
+ {
+ Credencial = credencial,
+ Destinatario = destinatario
+ };
+ AlternateView item = CreateAlternateView(destinatario.Corpo);
+ try
+ {
+ MailMessage message = new MailMessage
+ {
+ From = new MailAddress(credencial.Email, string.IsNullOrWhiteSpace(credencial.Header) ? Recursos.Empresa.Nome : credencial.Header),
+ BodyEncoding = Encoding.UTF8,
+ Subject = destinatario.Assunto,
+ AlternateViews = { item },
+ ReplyToList =
+ {
+ new MailAddress(string.IsNullOrWhiteSpace(credencial.Replyto) ? credencial.Email : credencial.Replyto)
+ },
+ DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure,
+ IsBodyHtml = true
+ };
+ if (confirmarLeitura)
+ {
+ message.Headers.Add("Disposition-Notification-To", credencial.Email);
+ }
+ destinatario.Email.Split(new char[1] { ';' }).ToList().ForEach(delegate(string s)
+ {
+ if (ValidationHelper.ValidacaoEmail(s))
+ {
+ message.To.Add(new MailAddress(s));
+ }
+ });
+ List<string> listaCopia = new List<string>();
+ destinatario.EncaminharOculto?.ForEach(delegate(string x)
+ {
+ if (!string.IsNullOrEmpty(x))
+ {
+ if (!x.Contains(";"))
+ {
+ if (ValidationHelper.ValidacaoEmail(x))
+ {
+ listaCopia.Add(x);
+ }
+ }
+ else
+ {
+ x.Split(new char[1] { ';' }).ToList().ForEach(delegate(string s)
+ {
+ if (ValidationHelper.ValidacaoEmail(s))
+ {
+ listaCopia.Add(s);
+ }
+ });
+ }
+ }
+ });
+ destinatario.Encaminhar?.ForEach(delegate(string x)
+ {
+ if (!string.IsNullOrEmpty(x))
+ {
+ if (!x.Contains(";"))
+ {
+ if (ValidationHelper.ValidacaoEmail(x))
+ {
+ listaCopia.Add(x);
+ }
+ }
+ else
+ {
+ x.Split(new char[1] { ';' }).ToList().ForEach(delegate(string s)
+ {
+ if (ValidationHelper.ValidacaoEmail(s))
+ {
+ listaCopia.Add(s);
+ }
+ });
+ }
+ }
+ });
+ listaCopia.ForEach(delegate(string x)
+ {
+ message.Bcc.Add(new MailAddress(x));
+ });
+ destinatario.Anexos?.ForEach(delegate(ArquivoDigital x)
+ {
+ Attachment item2 = new Attachment(new MemoryStream(x.Arquivo), x.Descricao + ValidationHelper.GetDefaultExtension(x.Extensao));
+ message.Attachments.Add(item2);
+ });
+ if (credencial.Email.Contains("@gmail.com"))
+ {
+ credencial.Tipo = (TipoEmail)1;
+ }
+ TipoEmail tipo = credencial.Tipo;
+ if ((int)tipo != 1)
+ {
+ if ((int)tipo == 2)
+ {
+ StringContent val = new StringContent("");
+ IPublicClientApplication val2 = ((AbstractApplicationBuilder<PublicClientApplicationBuilder>)(object)PublicClientApplicationBuilder.Create("8d1c32fe-4c17-4d5b-a21b-55b5529c3e12").WithDefaultRedirectUri()).WithCacheOptions(new CacheOptions
+ {
+ UseSharedCache = true
+ }).Build();
+ string[] array = new string[2] { "user.read", "https://graph.microsoft.com/Mail.Send" };
+ AuthenticationResult val3;
+ try
+ {
+ val = ConverteMailMessageParaStringContent(message);
+ IEnumerable<IAccount> result = ((IClientApplicationBase)val2).GetAccountsAsync().Result;
+ val3 = ((result != null && result.Count() != 0) ? ((AbstractAcquireTokenParameterBuilder<AcquireTokenSilentParameterBuilder>)(object)((IClientApplicationBase)val2).AcquireTokenSilent((IEnumerable<string>)array, result?.FirstOrDefault())).ExecuteAsync().Result : ((AbstractAcquireTokenParameterBuilder<AcquireTokenInteractiveParameterBuilder>)(object)val2.AcquireTokenInteractive((IEnumerable<string>)array)).ExecuteAsync().Result);
+ }
+ catch
+ {
+ val3 = ((AbstractAcquireTokenParameterBuilder<AcquireTokenInteractiveParameterBuilder>)(object)val2.AcquireTokenInteractive((IEnumerable<string>)array)).ExecuteAsync().Result;
+ }
+ HttpClient val4 = new HttpClient();
+ try
+ {
+ ((HttpHeaders)val4.DefaultRequestHeaders).Clear();
+ ((HttpHeaders)val4.DefaultRequestHeaders).Add("Authorization", "Bearer " + ((val3 != null) ? val3.AccessToken : null));
+ HttpResponseMessage result2 = val4.PostAsync("https://graph.microsoft.com/v1.0/me/sendMail", (HttpContent)(object)val).Result;
+ log.Enviado = result2.IsSuccessStatusCode;
+ }
+ finally
+ {
+ ((IDisposable)val4)?.Dispose();
+ }
+ }
+ else
+ {
+ string password = EncryptionHelper.Decrypt(credencial.Senha);
+ NetworkCredential credentials = new NetworkCredential
+ {
+ Password = password,
+ UserName = (credencial.Usuario ?? credencial.Email)
+ };
+ SmtpClient smtpClient = new SmtpClient();
+ smtpClient.EnableSsl = credencial.Seguro;
+ smtpClient.Host = credencial.Dominio;
+ smtpClient.Port = credencial.Porta.GetValueOrDefault(587);
+ smtpClient.UseDefaultCredentials = false;
+ smtpClient.Credentials = credentials;
+ smtpClient.SendCompleted += delegate(object sender, AsyncCompletedEventArgs args)
+ {
+ log.Enviado = !args.Cancelled || args.Error != null;
+ if (args.Error != null)
+ {
+ log.Erro = args.Error.ToString();
+ }
+ };
+ smtpClient.Send(message);
+ log.Enviado = true;
+ }
+ }
+ else
+ {
+ UserCredential result3 = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
+ {
+ ClientId = "378618252089-fm92uqgnk2jivf25mk2tv9s735n4nf6u.apps.googleusercontent.com",
+ ClientSecret = "kUiTfSuwZLLfteqwX7x6glsu"
+ }, (IEnumerable<string>)new string[1] { Scope.GmailSend }, credencial.Email, CancellationToken.None, (IDataStore)null, (ICodeReceiver)null).Result;
+ Message val5 = new Message
+ {
+ Raw = Encode(((object)MimeMessage.CreateFromMailMessage(message)).ToString())
+ };
+ SendRequest obj2 = new GmailService(new Initializer
+ {
+ HttpClientInitializer = (IConfigurableHttpClientInitializer)(object)result3,
+ ApplicationName = "AGGER GESTOR"
+ }).Users.Messages.Send(val5, credencial.Email);
+ log.Enviado = false;
+ if (((ClientServiceRequest<Message>)(object)obj2).Execute().LabelIds.Contains("SENT"))
+ {
+ log.Enviado = true;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ log.Enviado = false;
+ string erro = ((ex.InnerException == null) ? ex.Message : (ex.Message + " | " + ex.InnerException.Message));
+ log.Erro = erro;
+ }
+ if ((int)tela == 40)
+ {
+ return log;
+ }
+ UnitOfWork commited = Instancia.Commited;
+ try
+ {
+ List<string> list = new List<string> { destinatario.Email };
+ if (destinatario.Encaminhar != null)
+ {
+ list.AddRange(destinatario.Encaminhar);
+ }
+ List<string> list2 = new List<string>();
+ if (destinatario.EncaminharOculto != null)
+ {
+ list2.AddRange(destinatario.EncaminharOculto);
+ }
+ List<string> list3 = destinatario.Anexos?.Select((ArquivoDigital x) => x.Descricao + ValidationHelper.GetDefaultExtension(x.Extensao)).ToList();
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ if (filtro != null)
+ {
+ TipoArquivoDigital tipo2 = filtro.Tipo;
+ switch (tipo2 - 1)
+ {
+ case 1:
+ telaEmail = (TipoTela)2;
+ break;
+ case 0:
+ telaEmail = (TipoTela)1;
+ break;
+ case 2:
+ telaEmail = (TipoTela)5;
+ break;
+ case 3:
+ telaEmail = (TipoTela)3;
+ break;
+ case 4:
+ telaEmail = (TipoTela)7;
+ break;
+ case 5:
+ telaEmail = (TipoTela)15;
+ break;
+ case 6:
+ telaEmail = (TipoTela)23;
+ break;
+ case 7:
+ telaEmail = (TipoTela)13;
+ break;
+ case 8:
+ telaEmail = (TipoTela)25;
+ break;
+ case 9:
+ telaEmail = (TipoTela)24;
+ break;
+ case 10:
+ telaEmail = (TipoTela)33;
+ break;
+ case 11:
+ telaEmail = (TipoTela)16;
+ break;
+ case 12:
+ telaEmail = (TipoTela)18;
+ break;
+ default:
+ telaEmail = (TipoTela)0;
+ break;
+ }
+ if (list3 != null && log.Enviado)
+ {
+ LogEmail val6 = new LogEmail
+ {
+ Credencial = credencial,
+ EntityId = filtro.Id,
+ Usuario = Recursos.Usuario,
+ Data = networkTime,
+ Tela = telaEmail,
+ Destinatarios = string.Join(";", list),
+ Cco = string.Join(";", list2),
+ Assunto = destinatario.Assunto,
+ Corpo = destinatario.Corpo,
+ Anexos = string.Join(";", list3),
+ Versao = LoginViewModel.VersaoAtual,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString()
+ };
+ commited.RegistroLogRepository.SaveOrUpdate(val6);
+ }
+ ((GenericUnitOfWork)commited).Commit();
+ }
+ else if (maladireta != null)
+ {
+ foreach (MalaDireta maladiretum in maladireta)
+ {
+ if ((int)maladiretum.Tela == 1)
+ {
+ LogEmail val7 = new LogEmail
+ {
+ Credencial = credencial,
+ Usuario = Recursos.Usuario,
+ EntityId = ((DomainBase)maladiretum.Cliente).Id,
+ Data = networkTime,
+ Tela = maladiretum.Tela,
+ Destinatarios = string.Join(";", list),
+ Cco = string.Join(";", list2),
+ Assunto = destinatario.Assunto,
+ Corpo = destinatario.Corpo,
+ Anexos = string.Join(";", list3),
+ Versao = LoginViewModel.VersaoAtual,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString(),
+ Relatorio = maladiretum.Relatorio
+ };
+ commited.RegistroLogRepository.SaveOrUpdate(val7);
+ }
+ else if ((int)maladiretum.Tela == 2)
+ {
+ LogEmail val8 = new LogEmail
+ {
+ Credencial = credencial,
+ Usuario = Recursos.Usuario,
+ EntityId = ((DomainBase)maladiretum.Apolice).Id,
+ Data = networkTime,
+ Tela = maladiretum.Tela,
+ Destinatarios = string.Join(";", list),
+ Cco = string.Join(";", list2),
+ Assunto = destinatario.Assunto,
+ Corpo = destinatario.Corpo,
+ Anexos = string.Join(";", list3),
+ Versao = LoginViewModel.VersaoAtual,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString(),
+ Relatorio = maladiretum.Relatorio
+ };
+ commited.RegistroLogRepository.SaveOrUpdate(val8);
+ }
+ else if ((int)maladiretum.Tela == 5)
+ {
+ LogEmail val9 = new LogEmail
+ {
+ Credencial = credencial,
+ Usuario = Recursos.Usuario,
+ EntityId = ((DomainBase)maladiretum.Parcela).Id,
+ Data = networkTime,
+ Tela = maladiretum.Tela,
+ Destinatarios = string.Join(";", list),
+ Cco = string.Join(";", list2),
+ Assunto = destinatario.Assunto,
+ Corpo = destinatario.Corpo,
+ Anexos = string.Join(";", list3),
+ Versao = LoginViewModel.VersaoAtual,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString(),
+ Relatorio = maladiretum.Relatorio
+ };
+ commited.RegistroLogRepository.SaveOrUpdate(val9);
+ }
+ else if ((int)maladiretum.Tela == 7)
+ {
+ LogEmail val10 = new LogEmail
+ {
+ Credencial = credencial,
+ Usuario = Recursos.Usuario,
+ EntityId = ((DomainBase)maladiretum.Sinistro).Id,
+ Data = networkTime,
+ Tela = maladiretum.Tela,
+ Destinatarios = string.Join(";", list),
+ Cco = string.Join(";", list2),
+ Assunto = destinatario.Assunto,
+ Corpo = destinatario.Corpo,
+ Anexos = string.Join(";", list3),
+ Versao = LoginViewModel.VersaoAtual,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString(),
+ Relatorio = maladiretum.Relatorio
+ };
+ commited.RegistroLogRepository.SaveOrUpdate(val10);
+ }
+ else if ((int)maladiretum.Tela == 0)
+ {
+ LogEmail val11 = new LogEmail
+ {
+ Credencial = credencial,
+ Usuario = Recursos.Usuario
+ };
+ Documento apolice = maladiretum.Apolice;
+ val11.EntityId = ((apolice != null) ? ((DomainBase)apolice).Id : 0);
+ val11.Data = networkTime;
+ val11.Tela = (TipoTela)2;
+ val11.Destinatarios = string.Join(";", list);
+ val11.Cco = string.Join(";", list2);
+ val11.Assunto = destinatario.Assunto;
+ val11.Corpo = destinatario.Corpo;
+ val11.Anexos = string.Join(";", list3);
+ val11.Versao = LoginViewModel.VersaoAtual;
+ val11.NomeMaquina = Environment.MachineName;
+ val11.UsuarioMaquina = Environment.UserName;
+ val11.Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString();
+ val11.Relatorio = maladiretum.Relatorio;
+ LogEmail val12 = val11;
+ commited.RegistroLogRepository.SaveOrUpdate(val12);
+ }
+ }
+ ((GenericUnitOfWork)commited).Commit();
+ }
+ else
+ {
+ if (list3 != null)
+ {
+ LogEmail val13 = new LogEmail
+ {
+ Credencial = credencial,
+ Usuario = Recursos.Usuario,
+ Data = networkTime,
+ Tela = tela,
+ Destinatarios = string.Join(";", list),
+ Cco = string.Join(";", list2),
+ Assunto = destinatario.Assunto,
+ Corpo = destinatario.Corpo,
+ Anexos = string.Join(";", list3),
+ Versao = LoginViewModel.VersaoAtual,
+ NomeMaquina = Environment.MachineName,
+ UsuarioMaquina = Environment.UserName,
+ Ip = host.AddressList.FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString()
+ };
+ commited.RegistroLogRepository.SaveOrUpdate(val13);
+ }
+ ((GenericUnitOfWork)commited).Commit();
+ }
+ }
+ finally
+ {
+ ((IDisposable)commited)?.Dispose();
+ }
+ return log;
+ });
+ }
+
+ private static StringContent ConverteMailMessageParaStringContent(MailMessage message)
+ {
+ //IL_004f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0056: Expected O, but got Unknown
+ MimeMessage val = (MimeMessage)message;
+ using MemoryStream memoryStream = new MemoryStream();
+ val.WriteTo((Stream)memoryStream, default(CancellationToken));
+ memoryStream.Position = 0L;
+ using StreamReader streamReader = new StreamReader(memoryStream);
+ string s = streamReader.ReadToEnd();
+ return new StringContent(Convert.ToBase64String(Encoding.ASCII.GetBytes(s)), Encoding.UTF8, "text/plain");
+ }
+
+ public static string Encode(string text)
+ {
+ return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).Replace('+', '-').Replace('/', '_')
+ .Replace("=", "");
+ }
+
+ public static AlternateView CreateAlternateView(string mailBody)
+ {
+ List<LinkedResource> list = new List<LinkedResource>();
+ string[] array = (from Match m in Regex.Matches(mailBody, "<img(.*?)src=\"file:(///).*?>", RegexOptions.IgnoreCase)
+ select m.Groups[0].Value).ToArray();
+ for (int i = 0; i < array.Length; i++)
+ {
+ string value = Regex.Match(array[i], "(?<=src=\")(.*?)(?=\")", RegexOptions.IgnoreCase).Value;
+ string text = Regex.Match(value, "file:(///).*\\.(.*)", RegexOptions.IgnoreCase).Groups[2].Value;
+ if (text == "jpg")
+ {
+ text = "jpeg";
+ }
+ if (Uri.IsWellFormedUriString(value, UriKind.Absolute))
+ {
+ Uri uri = new Uri(value);
+ if (File.Exists(uri.LocalPath))
+ {
+ mailBody = mailBody.Replace(value, "data:image/" + text + ";base64," + Convert.ToBase64String(File.ReadAllBytes(uri.LocalPath)));
+ }
+ }
+ }
+ array = (from Match m in Regex.Matches(mailBody, "<img.*?>", RegexOptions.IgnoreCase)
+ select m.Groups[0].Value).ToArray();
+ foreach (string text2 in array)
+ {
+ string value2 = Regex.Match(text2, "(?<=src=\").*(?=\")", RegexOptions.IgnoreCase).Value;
+ string value3 = Regex.Match(value2, "(?<=data:).*(?=;)", RegexOptions.IgnoreCase).Value;
+ if (ValidationHelper.IsNullOrEmpty(value3) || ValidationHelper.IsNullOrEmpty(value2))
+ {
+ mailBody = mailBody.Replace(text2, string.Empty);
+ continue;
+ }
+ byte[] buffer = Convert.FromBase64String(Regex.Match(value2, "(?<=base64,)[^\"]*", RegexOptions.IgnoreCase).Value);
+ string text3 = Guid.NewGuid().ToString();
+ LinkedResource item = new LinkedResource(new MemoryStream(buffer), value3)
+ {
+ ContentId = text3,
+ TransferEncoding = TransferEncoding.Base64
+ };
+ list.Add(item);
+ string newValue = "cid:" + text3;
+ mailBody = mailBody.Replace(value2, newValue);
+ }
+ AlternateView alternateView = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
+ ExtensionMethods.AddRange<LinkedResource>((ICollection<LinkedResource>)alternateView.LinkedResources, (IEnumerable<LinkedResource>)list);
+ return alternateView;
+ }
+
+ public List<LogEnvio> Send(Credencial credencial, List<Destinatario> destinatarios, TipoTela tela, long id)
+ {
+ List<LogEnvio> logs = new List<LogEnvio>();
+ int count = 100;
+ destinatarios.ForEach(async delegate(Destinatario i)
+ {
+ if (count == 0)
+ {
+ count = 100;
+ await Task.Delay(1000);
+ }
+ List<LogEnvio> list = logs;
+ list.Add(await SendAsync(credencial, i, null, null, (TipoTela)0));
+ count--;
+ });
+ return logs;
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/NotifyPropertyChangedExtension.cs b/Decompiler/Gestor.Application.Helpers/NotifyPropertyChangedExtension.cs
new file mode 100644
index 0000000..2eb1bf4
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/NotifyPropertyChangedExtension.cs
@@ -0,0 +1,18 @@
+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<TField>(this INotifyPropertyChanged instance, ref TField field, TField newValue, Action<PropertyChangedEventArgs> raise, [CallerMemberName] string propertyName = null)
+ {
+ if (!EqualityComparer<TField>.Default.Equals(field, newValue))
+ {
+ field = newValue;
+ raise?.Invoke(new PropertyChangedEventArgs(propertyName));
+ }
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/ObrigatorioValidationRule.cs b/Decompiler/Gestor.Application.Helpers/ObrigatorioValidationRule.cs
new file mode 100644
index 0000000..45cc3b6
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/ObrigatorioValidationRule.cs
@@ -0,0 +1,26 @@
+using System.Globalization;
+using System.Windows.Controls;
+
+namespace Gestor.Application.Helpers;
+
+public class ObrigatorioValidationRule : ValidationRule
+{
+ public bool IsRequired { get; set; }
+
+ public override ValidationResult Validate(object value, CultureInfo cultureInfo)
+ {
+ //IL_0010: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0016: Expected O, but got Unknown
+ //IL_002f: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0035: Expected O, but got Unknown
+ if (!(value is string text))
+ {
+ return new ValidationResult(false, (object)"OBRIGATÓRIO");
+ }
+ if (text != null && IsRequired && string.IsNullOrWhiteSpace(text))
+ {
+ return new ValidationResult(false, (object)"OBRIGATÓRIO");
+ }
+ return ValidationResult.ValidResult;
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/PasswordBoxAssistant.cs b/Decompiler/Gestor.Application.Helpers/PasswordBoxAssistant.cs
new file mode 100644
index 0000000..46104bd
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/PasswordBoxAssistant.cs
@@ -0,0 +1,92 @@
+using System.Windows;
+using System.Windows.Controls;
+
+namespace Gestor.Application.Helpers;
+
+public static class PasswordBoxAssistant
+{
+ public static readonly DependencyProperty BoundPassword = DependencyProperty.RegisterAttached("BoundPassword", typeof(string), typeof(PasswordBoxAssistant), new PropertyMetadata((object)string.Empty, new PropertyChangedCallback(OnBoundPasswordChanged)));
+
+ public static readonly DependencyProperty BindPassword = DependencyProperty.RegisterAttached("BindPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata((object)false, new PropertyChangedCallback(OnBindPasswordChanged)));
+
+ private static readonly DependencyProperty UpdatingPassword = DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata((object)false));
+
+ private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ //IL_001b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0025: Expected O, but got Unknown
+ //IL_0049: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0053: Expected O, but got Unknown
+ PasswordBox val = (PasswordBox)(object)((d is PasswordBox) ? d : null);
+ if (d != null && GetBindPassword(d))
+ {
+ val.PasswordChanged -= new RoutedEventHandler(HandlePasswordChanged);
+ string password = (string)((DependencyPropertyChangedEventArgs)(ref e)).NewValue;
+ if (!GetUpdatingPassword((DependencyObject)(object)val))
+ {
+ val.Password = password;
+ }
+ val.PasswordChanged += new RoutedEventHandler(HandlePasswordChanged);
+ }
+ }
+
+ private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+ {
+ //IL_002e: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0038: Expected O, but got Unknown
+ //IL_0043: Unknown result type (might be due to invalid IL or missing references)
+ //IL_004d: Expected O, but got Unknown
+ PasswordBox val = (PasswordBox)(object)((dp is PasswordBox) ? dp : null);
+ if (val != null)
+ {
+ bool num = (bool)((DependencyPropertyChangedEventArgs)(ref e)).OldValue;
+ bool flag = (bool)((DependencyPropertyChangedEventArgs)(ref e)).NewValue;
+ if (num)
+ {
+ val.PasswordChanged -= new RoutedEventHandler(HandlePasswordChanged);
+ }
+ if (flag)
+ {
+ val.PasswordChanged += new RoutedEventHandler(HandlePasswordChanged);
+ }
+ }
+ }
+
+ private static void HandlePasswordChanged(object sender, RoutedEventArgs e)
+ {
+ PasswordBox val = (PasswordBox)((sender is PasswordBox) ? sender : null);
+ SetUpdatingPassword((DependencyObject)(object)val, value: true);
+ SetBoundPassword((DependencyObject)(object)val, val.Password);
+ SetUpdatingPassword((DependencyObject)(object)val, value: false);
+ }
+
+ public static void SetBindPassword(DependencyObject dp, bool value)
+ {
+ dp.SetValue(BindPassword, (object)value);
+ }
+
+ public static bool GetBindPassword(DependencyObject dp)
+ {
+ return (bool)dp.GetValue(BindPassword);
+ }
+
+ public static string GetBoundPassword(DependencyObject dp)
+ {
+ return (string)dp.GetValue(BoundPassword);
+ }
+
+ public static void SetBoundPassword(DependencyObject dp, string value)
+ {
+ dp.SetValue(BoundPassword, (object)value);
+ }
+
+ private static bool GetUpdatingPassword(DependencyObject dp)
+ {
+ return (bool)dp.GetValue(UpdatingPassword);
+ }
+
+ private static void SetUpdatingPassword(DependencyObject dp, bool value)
+ {
+ dp.SetValue(UpdatingPassword, (object)value);
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/PipeClient.cs b/Decompiler/Gestor.Application.Helpers/PipeClient.cs
new file mode 100644
index 0000000..a0d49eb
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/PipeClient.cs
@@ -0,0 +1,41 @@
+using System;
+using System.IO;
+using System.IO.Pipes;
+using Newtonsoft.Json;
+
+namespace Gestor.Application.Helpers;
+
+public class PipeClient
+{
+ private string _pipeName;
+
+ private NamedPipeClientStream Pipe { get; set; }
+
+ public PipeClient(string pipeName)
+ {
+ _pipeName = pipeName;
+ }
+
+ public bool Send(dynamic message)
+ {
+ try
+ {
+ Pipe = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out, PipeOptions.Asynchronous);
+ Pipe.Connect(1000);
+ if (!Pipe.IsConnected)
+ {
+ return false;
+ }
+ using StreamWriter streamWriter = new StreamWriter(Pipe);
+ streamWriter.AutoFlush = true;
+ dynamic val = JsonConvert.SerializeObject(message);
+ streamWriter.WriteLine(val);
+ Pipe.WaitForPipeDrain();
+ }
+ catch (TimeoutException)
+ {
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/PipeServer.cs b/Decompiler/Gestor.Application.Helpers/PipeServer.cs
new file mode 100644
index 0000000..36c40c3
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/PipeServer.cs
@@ -0,0 +1,96 @@
+using System;
+using System.IO;
+using System.IO.Pipes;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using Assinador.Model.Common;
+using Gestor.Application.Actions;
+using Newtonsoft.Json;
+
+namespace Gestor.Application.Helpers;
+
+public class PipeServer : IDisposable
+{
+ private string _pipeName;
+
+ private NamedPipeServerStream Pipe { get; set; }
+
+ public bool CreateServer(string name)
+ {
+ _pipeName = name;
+ return Create();
+ }
+
+ private bool Create()
+ {
+ bool flag = true;
+ try
+ {
+ new NamedPipeClientStream(".", _pipeName, PipeDirection.Out, PipeOptions.Asynchronous).Connect(1000);
+ }
+ catch (TimeoutException)
+ {
+ flag = false;
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ if (flag)
+ {
+ 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));
+ Pipe = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, pipeSecurity);
+ Pipe.BeginWaitForConnection(WaitForConnectionCallBack, Pipe);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ return true;
+ }
+
+ private void WaitForConnectionCallBack(IAsyncResult iar)
+ {
+ try
+ {
+ NamedPipeServerStream namedPipeServerStream = (NamedPipeServerStream)iar.AsyncState;
+ namedPipeServerStream.EndWaitForConnection(iar);
+ using (StreamReader streamReader = new StreamReader(Pipe))
+ {
+ string text = streamReader.ReadLine();
+ if (text != null && text.IndexOf("exit", StringComparison.InvariantCultureIgnoreCase) > -1)
+ {
+ Dispose();
+ }
+ Handle(text);
+ }
+ namedPipeServerStream.Close();
+ namedPipeServerStream = null;
+ Create();
+ }
+ catch
+ {
+ }
+ }
+
+ public void Dispose()
+ {
+ Pipe.Dispose();
+ }
+
+ private void Handle(string message)
+ {
+ if (message != null)
+ {
+ PipeMessageResult obj = JsonConvert.DeserializeObject<PipeMessageResult>(message);
+ Gestor.Application.Actions.Actions.AcessarHoster?.Invoke(obj);
+ }
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/QueryableHelper.cs b/Decompiler/Gestor.Application.Helpers/QueryableHelper.cs
new file mode 100644
index 0000000..a93ebd5
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/QueryableHelper.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Linq;
+using System.Linq.Expressions;
+
+namespace Gestor.Application.Helpers;
+
+public static class QueryableHelper
+{
+ public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
+ {
+ return source.OrderBy(ToLambda<T>(propertyName));
+ }
+
+ public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
+ {
+ return source.OrderByDescending(ToLambda<T>(propertyName));
+ }
+
+ private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
+ {
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(T));
+ return Expression.Lambda<Func<T, object>>(Expression.Convert(Expression.Property(parameterExpression, propertyName), typeof(object)), new ParameterExpression[1] { parameterExpression });
+ }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/Recursos.cs b/Decompiler/Gestor.Application.Helpers/Recursos.cs
new file mode 100644
index 0000000..2c62785
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/Recursos.cs
@@ -0,0 +1,70 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+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;
+
+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 List<string> Parametros { get; set; }
+
+ public static Usuario Usuario { get; set; }
+
+ public static Empresa Empresa { get; set; }
+
+ public static List<Empresa> Empresas { get; set; }
+
+ public static List<Seguradora> Seguradoras { get; set; }
+
+ public static List<Parceiro> Parceiros { get; set; }
+
+ public static List<ConfigExtratoImport> Descricao { get; set; }
+
+ public static List<Estipulante> Estipulantes { get; set; }
+
+ public static List<Ramo> Ramos { get; set; }
+
+ public static List<Produto> Produtos { get; set; }
+
+ public static List<Status> Status { get; set; }
+
+ public static List<CoberturaPadrao> Coberturas { get; set; }
+
+ public static List<TipoVendedor> TipoVendedor { get; set; }
+
+ public static List<Vendedor> Vendedores { get; set; }
+
+ public static List<BancosContas> BancosContas { get; set; }
+
+ public static List<Usuario> Usuarios { get; set; }
+
+ public static List<TipoDeTarefa> TiposTarefa { get; set; }
+
+ public static List<StatusDeProspeccao> StatusProspeccao { get; set; }
+
+ public static Uri WhatsAppLink { get; } = new Uri("https://api.whatsapp.com/send?");
+
+
+ public static Uri ApiArquivo { get; } = Address.ApiArquivo;
+
+
+ public static List<Fabricante> Fabricantes { get; set; }
+
+ public static List<ConfiguracaoSistema> Configuracoes { get; set; }
+
+ public static IPHostEntry Host { get; set; }
+
+ public static string Registrar { get; set; }
+}
diff --git a/Decompiler/Gestor.Application.Helpers/TipoToggle.cs b/Decompiler/Gestor.Application.Helpers/TipoToggle.cs
new file mode 100644
index 0000000..a0be782
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/TipoToggle.cs
@@ -0,0 +1,13 @@
+using System;
+
+namespace Gestor.Application.Helpers;
+
+[Flags]
+public enum TipoToggle
+{
+ None = 0,
+ Consultar = 1,
+ Incluir = 2,
+ Alterar = 4,
+ Excluir = 8
+}
diff --git a/Decompiler/Gestor.Application.Helpers/ViewHelper.cs b/Decompiler/Gestor.Application.Helpers/ViewHelper.cs
new file mode 100644
index 0000000..f4c38e6
--- /dev/null
+++ b/Decompiler/Gestor.Application.Helpers/ViewHelper.cs
@@ -0,0 +1,878 @@
+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 CurrencyTextBoxControl;
+using Gestor.Application.Componentes;
+using Gestor.Model.Helper;
+using Xceed.Wpf.Toolkit;
+using Xceed.Wpf.Toolkit.Primitives;
+
+namespace Gestor.Application.Helpers;
+
+public static class ViewHelper
+{
+ [CompilerGenerated]
+ private sealed class _003CFindAncestor_003Ed__11<T> : IEnumerable<T>, IEnumerable, IEnumerator<T>, IDisposable, IEnumerator where T : DependencyObject
+ {
+ private int _003C_003E1__state;
+
+ private T _003C_003E2__current;
+
+ private int _003C_003El__initialThreadId;
+
+ private DependencyObject dependencyObject;
+
+ public DependencyObject _003C_003E3__dependencyObject;
+
+ private DependencyObject _003CparentReference_003E5__2;
+
+ T IEnumerator<T>.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ object IEnumerator.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ [DebuggerHidden]
+ public _003CFindAncestor_003Ed__11(int _003C_003E1__state)
+ {
+ this._003C_003E1__state = _003C_003E1__state;
+ _003C_003El__initialThreadId = Environment.CurrentManagedThreadId;
+ }
+
+ [DebuggerHidden]
+ void IDisposable.Dispose()
+ {
+ _003CparentReference_003E5__2 = null;
+ _003C_003E1__state = -2;
+ }
+
+ private bool MoveNext()
+ {
+ int num = _003C_003E1__state;
+ if (num != 0)
+ {
+ if (num != 1)
+ {
+ return false;
+ }
+ _003C_003E1__state = -1;
+ goto IL_005a;
+ }
+ _003C_003E1__state = -1;
+ _003CparentReference_003E5__2 = VisualTreeHelper.GetParent(dependencyObject);
+ goto IL_006b;
+ IL_005a:
+ _003CparentReference_003E5__2 = VisualTreeHelper.GetParent(_003CparentReference_003E5__2);
+ goto IL_006b;
+ IL_006b:
+ if (_003CparentReference_003E5__2 == null)
+ {
+ return false;
+ }
+ DependencyObject obj = _003CparentReference_003E5__2;
+ T val = (T)(object)((obj is T) ? obj : null);
+ if (val != null)
+ {
+ _003C_003E2__current = val;
+ _003C_003E1__state = 1;
+ return true;
+ }
+ goto IL_005a;
+ }
+
+ bool IEnumerator.MoveNext()
+ {
+ //ILSpy generated this explicit interface implementation from .override directive in MoveNext
+ return this.MoveNext();
+ }
+
+ [DebuggerHidden]
+ void IEnumerator.Reset()
+ {
+ throw new NotSupportedException();
+ }
+
+ [DebuggerHidden]
+ IEnumerator<T> IEnumerable<T>.GetEnumerator()
+ {
+ _003CFindAncestor_003Ed__11<T> _003CFindAncestor_003Ed__;
+ if (_003C_003E1__state == -2 && _003C_003El__initialThreadId == Environment.CurrentManagedThreadId)
+ {
+ _003C_003E1__state = 0;
+ _003CFindAncestor_003Ed__ = this;
+ }
+ else
+ {
+ _003CFindAncestor_003Ed__ = new _003CFindAncestor_003Ed__11<T>(0);
+ }
+ _003CFindAncestor_003Ed__.dependencyObject = _003C_003E3__dependencyObject;
+ return _003CFindAncestor_003Ed__;
+ }
+
+ [DebuggerHidden]
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return ((IEnumerable<T>)this).GetEnumerator();
+ }
+ }
+
+ [CompilerGenerated]
+ private sealed class _003CFindChildren_003Ed__2<T> : IEnumerable<T>, IEnumerable, IEnumerator<T>, IDisposable, IEnumerator where T : DependencyObject
+ {
+ private int _003C_003E1__state;
+
+ private T _003C_003E2__current;
+
+ private int _003C_003El__initialThreadId;
+
+ private DependencyObject depObj;
+
+ public DependencyObject _003C_003E3__depObj;
+
+ private IEnumerator _003C_003E7__wrap1;
+
+ private object _003Cchild_003E5__3;
+
+ private IEnumerator<T> _003C_003E7__wrap3;
+
+ T IEnumerator<T>.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ object IEnumerator.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ [DebuggerHidden]
+ public _003CFindChildren_003Ed__2(int _003C_003E1__state)
+ {
+ this._003C_003E1__state = _003C_003E1__state;
+ _003C_003El__initialThreadId = Environment.CurrentManagedThreadId;
+ }
+
+ [DebuggerHidden]
+ void IDisposable.Dispose()
+ {
+ int num = _003C_003E1__state;
+ if ((uint)(num - -4) <= 1u || (uint)(num - 1) <= 1u)
+ {
+ try
+ {
+ if (num == -4 || num == 2)
+ {
+ try
+ {
+ }
+ finally
+ {
+ _003C_003Em__Finally2();
+ }
+ }
+ }
+ finally
+ {
+ _003C_003Em__Finally1();
+ }
+ }
+ _003C_003E7__wrap1 = null;
+ _003Cchild_003E5__3 = null;
+ _003C_003E7__wrap3 = null;
+ _003C_003E1__state = -2;
+ }
+
+ private bool MoveNext()
+ {
+ try
+ {
+ object obj;
+ DependencyObject val;
+ switch (_003C_003E1__state)
+ {
+ default:
+ return false;
+ case 0:
+ _003C_003E1__state = -1;
+ if (depObj == null)
+ {
+ return false;
+ }
+ _003C_003E7__wrap1 = LogicalTreeHelper.GetChildren(depObj).GetEnumerator();
+ _003C_003E1__state = -3;
+ goto IL_012e;
+ case 1:
+ _003C_003E1__state = -3;
+ goto IL_00be;
+ case 2:
+ {
+ _003C_003E1__state = -4;
+ goto IL_010d;
+ }
+ IL_010d:
+ if (_003C_003E7__wrap3.MoveNext())
+ {
+ T current = _003C_003E7__wrap3.Current;
+ _003C_003E2__current = current;
+ _003C_003E1__state = 2;
+ return true;
+ }
+ _003C_003Em__Finally2();
+ _003C_003E7__wrap3 = null;
+ _003Cchild_003E5__3 = null;
+ goto IL_012e;
+ IL_00be:
+ obj = _003Cchild_003E5__3;
+ val = (DependencyObject)((obj is DependencyObject) ? obj : null);
+ _003C_003E7__wrap3 = val.FindChildren<T>().GetEnumerator();
+ _003C_003E1__state = -4;
+ goto IL_010d;
+ IL_012e:
+ if (_003C_003E7__wrap1.MoveNext())
+ {
+ _003Cchild_003E5__3 = _003C_003E7__wrap1.Current;
+ object obj2 = _003Cchild_003E5__3;
+ T val2 = (T)((obj2 is T) ? obj2 : null);
+ if (val2 != null)
+ {
+ object obj3 = val2;
+ object obj4 = ((obj3 is ContentControl) ? obj3 : null);
+ object obj5 = val2;
+ UserControl val3 = (UserControl)((obj5 is UserControl) ? obj5 : null);
+ if (obj4 == null || val3 != null)
+ {
+ _003C_003E2__current = val2;
+ _003C_003E1__state = 1;
+ return true;
+ }
+ }
+ goto IL_00be;
+ }
+ _003C_003Em__Finally1();
+ _003C_003E7__wrap1 = null;
+ return false;
+ }
+ }
+ catch
+ {
+ //try-fault
+ ((IDisposable)this).Dispose();
+ throw;
+ }
+ }
+
+ bool IEnumerator.MoveNext()
+ {
+ //ILSpy generated this explicit interface implementation from .override directive in MoveNext
+ return this.MoveNext();
+ }
+
+ private void _003C_003Em__Finally1()
+ {
+ _003C_003E1__state = -1;
+ if (_003C_003E7__wrap1 is IDisposable disposable)
+ {
+ disposable.Dispose();
+ }
+ }
+
+ private void _003C_003Em__Finally2()
+ {
+ _003C_003E1__state = -3;
+ if (_003C_003E7__wrap3 != null)
+ {
+ _003C_003E7__wrap3.Dispose();
+ }
+ }
+
+ [DebuggerHidden]
+ void IEnumerator.Reset()
+ {
+ throw new NotSupportedException();
+ }
+
+ [DebuggerHidden]
+ IEnumerator<T> IEnumerable<T>.GetEnumerator()
+ {
+ _003CFindChildren_003Ed__2<T> _003CFindChildren_003Ed__;
+ if (_003C_003E1__state == -2 && _003C_003El__initialThreadId == Environment.CurrentManagedThreadId)
+ {
+ _003C_003E1__state = 0;
+ _003CFindChildren_003Ed__ = this;
+ }
+ else
+ {
+ _003CFindChildren_003Ed__ = new _003CFindChildren_003Ed__2<T>(0);
+ }
+ _003CFindChildren_003Ed__.depObj = _003C_003E3__depObj;
+ return _003CFindChildren_003Ed__;
+ }
+
+ [DebuggerHidden]
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return ((IEnumerable<T>)this).GetEnumerator();
+ }
+ }
+
+ [CompilerGenerated]
+ private sealed class _003CFindParent_003Ed__3<T> : IEnumerable<T>, IEnumerable, IEnumerator<T>, IDisposable, IEnumerator where T : DependencyObject
+ {
+ private int _003C_003E1__state;
+
+ private T _003C_003E2__current;
+
+ private int _003C_003El__initialThreadId;
+
+ private DependencyObject depObj;
+
+ public DependencyObject _003C_003E3__depObj;
+
+ private DependencyObject _003CfirstParent_003E5__2;
+
+ private IEnumerator<T> _003C_003E7__wrap2;
+
+ T IEnumerator<T>.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ object IEnumerator.Current
+ {
+ [DebuggerHidden]
+ get
+ {
+ return _003C_003E2__current;
+ }
+ }
+
+ [DebuggerHidden]
+ public _003CFindParent_003Ed__3(int _003C_003E1__state)
+ {
+ this._003C_003E1__state = _003C_003E1__state;
+ _003C_003El__initialThreadId = Environment.CurrentManagedThreadId;
+ }
+
+ [DebuggerHidden]
+ void IDisposable.Dispose()
+ {
+ int num = _003C_003E1__state;
+ if (num == -3 || num == 2)
+ {
+ try
+ {
+ }
+ finally
+ {
+ _003C_003Em__Finally1();
+ }
+ }
+ _003CfirstParent_003E5__2 = null;
+ _003C_003E7__wrap2 = null;
+ _003C_003E1__state = -2;
+ }
+
+ private bool MoveNext()
+ {
+ try
+ {
+ DependencyObject val2;
+ switch (_003C_003E1__state)
+ {
+ default:
+ return false;
+ case 0:
+ {
+ _003C_003E1__state = -1;
+ if (depObj == null)
+ {
+ return false;
+ }
+ _003CfirstParent_003E5__2 = LogicalTreeHelper.GetParent(depObj);
+ DependencyObject obj = _003CfirstParent_003E5__2;
+ T val = (T)(object)((obj is T) ? obj : null);
+ if (val != null)
+ {
+ _003C_003E2__current = val;
+ _003C_003E1__state = 1;
+ return true;
+ }
+ goto IL_0079;
+ }
+ case 1:
+ _003C_003E1__state = -1;
+ goto IL_0079;
+ case 2:
+ {
+ _003C_003E1__state = -3;
+ break;
+ }
+ IL_0079:
+ val2 = _003CfirstParent_003E5__2;
+ _003C_003E7__wrap2 = val2.FindParent<T>().GetEnumerator();
+ _003C_003E1__state = -3;
+ break;
+ }
+ if (_003C_003E7__wrap2.MoveNext())
+ {
+ T current = _003C_003E7__wrap2.Current;
+ _003C_003E2__current = current;
+ _003C_003E1__state = 2;
+ return true;
+ }
+ _003C_003Em__Finally1();
+ _003C_003E7__wrap2 = null;
+ return false;
+ }
+ catch
+ {
+ //try-fault
+ ((IDisposable)this).Dispose();
+ throw;
+ }
+ }
+
+ bool IEnumerator.MoveNext()
+ {
+ //ILSpy generated this explicit interface implementation from .override directive in MoveNext
+ return this.MoveNext();
+ }
+
+ private void _003C_003Em__Finally1()
+ {
+ _003C_003E1__state = -1;
+ if (_003C_003E7__wrap2 != null)
+ {
+ _003C_003E7__wrap2.Dispose();
+ }
+ }
+
+ [DebuggerHidden]
+ void IEnumerator.Reset()
+ {
+ throw new NotSupportedException();
+ }
+
+ [DebuggerHidden]
+ IEnumerator<T> IEnumerable<T>.GetEnumerator()
+ {
+ _003CFindParent_003Ed__3<T> _003CFindParent_003Ed__;
+ if (_003C_003E1__state == -2 && _003C_003El__initialThreadId == Environment.CurrentManagedThreadId)
+ {
+ _003C_003E1__state = 0;
+ _003CFindParent_003Ed__ = this;
+ }
+ else
+ {
+ _003CFindParent_003Ed__ = new _003CFindParent_003Ed__3<T>(0);
+ }
+ _003CFindParent_003Ed__.depObj = _003C_003E3__depObj;
+ return _003CFindParent_003Ed__;
+ }
+
+ [DebuggerHidden]
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return ((IEnumerable<T>)this).GetEnumerator();
+ }
+ }
+
+ public static void ControlLostFocus(object sender, RoutedEventArgs e)
+ {
+ //IL_00a2: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0675: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0680: Expected O, but got Unknown
+ //IL_067b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0680: Unknown result type (might be due to invalid IL or missing references)
+ //IL_068a: Expected O, but got Unknown
+ Control val = null;
+ if (sender is CustomItemValidation)
+ {
+ val = ((DependencyObject)(object)(sender as CustomItemValidation)).FindChildren<Control>().FirstOrDefault((Func<Control, bool>)((Control currentControl) => currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox || currentControl is Button || currentControl is CustomPasswordBox));
+ }
+ if (sender is CustomIsReadOnlyControl)
+ {
+ CustomIsReadOnlyControl customIsReadOnlyControl = sender as CustomIsReadOnlyControl;
+ val = ((!customIsReadOnlyControl.HasValidation) ? null : ((DependencyObject)(object)customIsReadOnlyControl).FindChildren<Control>().LastOrDefault((Func<Control, bool>)((Control currentControl) => currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox || currentControl is Button)));
+ }
+ if (val == null)
+ {
+ return;
+ }
+ ComboBox val2 = (ComboBox)(object)((val is ComboBox) ? val : null);
+ if ((val2 != null && val2.IsDropDownOpen) || (val is TextBox && ((TextBoxBase)(TextBox)val).IsReadOnly))
+ {
+ return;
+ }
+ DependencyProperty dependencyProperty = GetDependencyProperty(val);
+ if (dependencyProperty == null)
+ {
+ return;
+ }
+ BindingExpression bindingExpression = ((FrameworkElement)val).GetBindingExpression(dependencyProperty);
+ if (bindingExpression == null)
+ {
+ return;
+ }
+ Validation.ClearInvalid((BindingExpressionBase)(object)bindingExpression);
+ List<string> list = bindingExpression.ParentBinding.Path.Path.Split(new char[1] { '.' }).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<KeyValuePair<string, string>> list2 = new List<KeyValuePair<string, string>>();
+ if ((!ViewHelper.HasMethod(value, "ValidationEvent")))
+ {
+ dynamic resolvedSource = bindingExpression.ResolvedSource;
+ if (resolvedSource is Control || ((!ViewHelper.HasMethod(resolvedSource, "ValidationEvent"))) || ((resolvedSource?.ValidationEvent == null) ? true : false))
+ {
+ return;
+ }
+ if (resolvedSource.ValidationEvent is Func<List<KeyValuePair<string, string>>> func)
+ {
+ list2 = func();
+ }
+ if (list2.Count == 0)
+ {
+ return;
+ }
+ }
+ if (list2.Count == 0)
+ {
+ if (value?.ValidationEvent == null)
+ {
+ return;
+ }
+ if (value.ValidationEvent is Func<List<KeyValuePair<string, string>>> func2)
+ {
+ list2 = func2();
+ }
+ }
+ if (list2 == null || !list2.Any())
+ {
+ return;
+ }
+ string text = ((list.Last() == "Id") ? list[list.Count - 2] : list.Last());
+ string valueExact = ValidationHelper.GetValueExact(list2, text);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ valueExact = ValidationHelper.GetValueExact(list2, text);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ return;
+ }
+ }
+ ValidationError val3 = new ValidationError((ValidationRule)new ExceptionValidationRule(), (object)bindingExpression)
+ {
+ ErrorContent = valueExact
+ };
+ Validation.MarkInvalid((BindingExpressionBase)(object)bindingExpression, val3);
+ }
+
+ public static bool IsPropertyExist(dynamic settings, string name)
+ {
+ if (settings is ExpandoObject)
+ {
+ return ((IDictionary<string, object>)settings).ContainsKey(name);
+ }
+ return settings.GetType().GetProperty(name) != null;
+ }
+
+ [IteratorStateMachine(typeof(_003CFindChildren_003Ed__2<>))]
+ public static IEnumerable<T> FindChildren<T>(this DependencyObject depObj) where T : DependencyObject
+ {
+ //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
+ return new _003CFindChildren_003Ed__2<T>(-2)
+ {
+ _003C_003E3__depObj = depObj
+ };
+ }
+
+ [IteratorStateMachine(typeof(_003CFindParent_003Ed__3<>))]
+ public static IEnumerable<T> FindParent<T>(this DependencyObject depObj) where T : DependencyObject
+ {
+ //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
+ return new _003CFindParent_003Ed__3<T>(-2)
+ {
+ _003C_003E3__depObj = depObj
+ };
+ }
+
+ public static T Window<T>() where T : Window
+ {
+ return ((IEnumerable)Application.Current.Windows).OfType<T>().FirstOrDefault();
+ }
+
+ public static void ValidateFields(this DependencyObject dependencyObject, List<KeyValuePair<string, string>> errorMessages, bool focusField = true)
+ {
+ if (errorMessages == null || !errorMessages.Any())
+ {
+ dependencyObject.ClearInvalid();
+ return;
+ }
+ Control val = null;
+ foreach (Control item in dependencyObject.FindChildren<Control>())
+ {
+ Control val2 = item.SetInvalid(errorMessages);
+ if (val == null && val2 != null)
+ {
+ val = val2;
+ }
+ }
+ if (focusField && val != null)
+ {
+ ((UIElement)val).Focus();
+ }
+ }
+
+ public static Control SetInvalid(this Control currentControl, List<KeyValuePair<string, string>> errorMessages = null, string specificKey = null)
+ {
+ //IL_0320: Unknown result type (might be due to invalid IL or missing references)
+ //IL_032b: Expected O, but got Unknown
+ //IL_0326: Unknown result type (might be due to invalid IL or missing references)
+ //IL_032b: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0335: Expected O, but got Unknown
+ DependencyProperty dependencyProperty = GetDependencyProperty(currentControl);
+ if (dependencyProperty == null)
+ {
+ return null;
+ }
+ BindingExpression bindingExpression = ((FrameworkElement)currentControl).GetBindingExpression(dependencyProperty);
+ if (errorMessages == null)
+ {
+ dynamic val = ((bindingExpression != null) ? bindingExpression.ResolvedSource : null);
+ if (val is Control)
+ {
+ return null;
+ }
+ if ((!ViewHelper.HasMethod(val, "ValidationEvent")))
+ {
+ return null;
+ }
+ if (val?.ValidationEvent == null)
+ {
+ return null;
+ }
+ if (val.ValidationEvent is Func<List<KeyValuePair<string, string>>> func)
+ {
+ errorMessages = func();
+ }
+ }
+ if (bindingExpression == null)
+ {
+ return null;
+ }
+ BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase((DependencyObject)(object)currentControl, dependencyProperty);
+ if (bindingExpressionBase == null)
+ {
+ return null;
+ }
+ Validation.ClearInvalid(bindingExpressionBase);
+ if (errorMessages == null || !errorMessages.Any())
+ {
+ return null;
+ }
+ string[] array = bindingExpression.ParentBinding.Path.Path.Split(new char[1] { '.' });
+ string text = specificKey ?? ((array.Last() == "Id") ? array[^2] : array.Last());
+ string valueExact = ValidationHelper.GetValueExact(errorMessages, text);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ valueExact = ValidationHelper.GetValueExact(errorMessages, text);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ return null;
+ }
+ }
+ ValidationError val2 = new ValidationError((ValidationRule)new ExceptionValidationRule(), (object)bindingExpression)
+ {
+ ErrorContent = valueExact
+ };
+ Validation.MarkInvalid(bindingExpressionBase, val2);
+ return currentControl;
+ }
+
+ private static DependencyProperty GetDependencyProperty(Control currentControl)
+ {
+ DependencyProperty result = null;
+ if (currentControl is CheckComboBox)
+ {
+ result = Selector.SelectedValueProperty;
+ }
+ if (currentControl is DatePicker)
+ {
+ result = DatePicker.SelectedDateProperty;
+ }
+ if (currentControl is AutoCompleteBox)
+ {
+ result = AutoCompleteBox.SelectedItemProperty;
+ }
+ if (currentControl is TextBox)
+ {
+ result = TextBox.TextProperty;
+ }
+ if (currentControl is MaskedTextBox)
+ {
+ result = TextBox.TextProperty;
+ }
+ if (currentControl is ComboBox)
+ {
+ result = Selector.SelectedValueProperty;
+ }
+ if (currentControl is CurrencyTextBox)
+ {
+ result = CurrencyTextBox.NumberProperty;
+ }
+ if (currentControl is ToggleButton)
+ {
+ result = ToggleButton.IsCheckedProperty;
+ }
+ if (currentControl is CustomPasswordBox)
+ {
+ result = CustomPasswordBox.TextProperty;
+ }
+ return result;
+ }
+
+ public static bool HasMethod(object objectToCheck, string methodName)
+ {
+ if (objectToCheck == null)
+ {
+ return false;
+ }
+ return objectToCheck.GetType().GetProperty(methodName) != null;
+ }
+
+ public static bool IsValid(this DependencyObject obj)
+ {
+ if (!Validation.GetHasError(obj))
+ {
+ return LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All(IsValid);
+ }
+ return false;
+ }
+
+ public static void ClearInvalid(this DependencyObject dependencyObject)
+ {
+ foreach (Control item in dependencyObject.FindChildren<Control>())
+ {
+ item.SetInvalid();
+ }
+ }
+
+ [IteratorStateMachine(typeof(_003CFindAncestor_003Ed__11<>))]
+ public static IEnumerable<T> FindAncestor<T>(this DependencyObject dependencyObject) where T : DependencyObject
+ {
+ //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
+ return new _003CFindAncestor_003Ed__11<T>(-2)
+ {
+ _003C_003E3__dependencyObject = dependencyObject
+ };
+ }
+
+ private static bool Compare(Control currentControl)
+ {
+ DependencyProperty dependencyProperty = GetDependencyProperty(currentControl);
+ if (dependencyProperty == null)
+ {
+ return false;
+ }
+ BindingExpression bindingExpression = ((FrameworkElement)currentControl).GetBindingExpression(dependencyProperty);
+ dynamic val = ((bindingExpression != null) ? bindingExpression.ResolvedSource : null);
+ return val != null && (bool)val.HasChange();
+ }
+
+ public static bool IsWindowOpen<T>(string name = "") where T : Window
+ {
+ if (!string.IsNullOrEmpty(name))
+ {
+ return ((IEnumerable)Application.Current.Windows).OfType<T>().Any((T w) => ((FrameworkElement)(object)w).Name.Equals(name));
+ }
+ return ((IEnumerable)Application.Current.Windows).OfType<T>().Any();
+ }
+
+ public static void SetInvalid(Control control, string error, bool valid)
+ {
+ //IL_0017: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0022: Expected O, but got Unknown
+ //IL_001d: Unknown result type (might be due to invalid IL or missing references)
+ //IL_0022: Unknown result type (might be due to invalid IL or missing references)
+ //IL_002a: Expected O, but got Unknown
+ DependencyProperty dependencyProperty = GetDependencyProperty(control);
+ if (dependencyProperty == null)
+ {
+ return;
+ }
+ BindingExpression bindingExpression = ((FrameworkElement)control).GetBindingExpression(dependencyProperty);
+ if (bindingExpression == null)
+ {
+ return;
+ }
+ ValidationError val = new ValidationError((ValidationRule)new ExceptionValidationRule(), (object)bindingExpression)
+ {
+ ErrorContent = error
+ };
+ BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase((DependencyObject)(object)control, dependencyProperty);
+ if (bindingExpressionBase != null)
+ {
+ Validation.ClearInvalid(bindingExpressionBase);
+ if (!valid)
+ {
+ Validation.MarkInvalid(bindingExpressionBase, val);
+ }
+ }
+ }
+
+ internal static void BindData<T>(this CheckComboBox comboBox, bool withSelect = true, bool enumDefault = true, string defaultValue = "", bool orderByLabel = false)
+ {
+ DefaultBinding<T>(comboBox, withSelect, enumDefault, defaultValue, string.Empty, orderByLabel);
+ }
+
+ private static void DefaultBinding<T>(CheckComboBox comboBox, bool withSelect, bool enumDefault, string defaultValue = "", string defaultText = "", bool orderByLabel = false)
+ {
+ List<KeyValuePair<string, string>> source = (List<KeyValuePair<string, string>>)(((ItemsControl)comboBox).ItemsSource = BindingHelper.BindingData<T>(withSelect, enumDefault, defaultValue, defaultText, orderByLabel));
+ ((Selector)comboBox).ValueMemberPath = "Key";
+ ((ItemsControl)comboBox).DisplayMemberPath = "Value";
+ ((Selector)comboBox).SelectedItem = source.First();
+ }
+}