diff options
| author | Lucas Faria Mendes <lucas.fariamo08@gmail.com> | 2026-03-30 13:38:18 +0000 |
|---|---|---|
| committer | Lucas Faria Mendes <lucas.fariamo08@gmail.com> | 2026-03-30 13:38:18 +0000 |
| commit | 1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1 (patch) | |
| tree | e1c3b20ea08f0cf71122a1e73f0d395f8fd83874 /Codemerx/Gestor.Application/Helpers | |
| parent | 674ca83ba9243a9e95a7568c797668dab6aee26a (diff) | |
| download | gestor-1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1.tar.gz gestor-1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1.zip | |
chore: location
Diffstat (limited to 'Codemerx/Gestor.Application/Helpers')
25 files changed, 11705 insertions, 0 deletions
diff --git a/Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs b/Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs new file mode 100644 index 0000000..1250a2e --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ApplicationHelper.cs @@ -0,0 +1,98 @@ +using Agger.Registro;
+using Gestor.Common.Helpers;
+using System;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+ public class ApplicationHelper
+ {
+ private static string _numeroSerial;
+
+ private const string ChaveSerial = "NS";
+
+ public static bool Beta
+ {
+ get;
+ set;
+ }
+
+ public static DateTime ChecagemVersao
+ {
+ get;
+ set;
+ }
+
+ public static bool Conectado
+ {
+ get;
+ set;
+ }
+
+ public static long IdFornecedor
+ {
+ get;
+ set;
+ }
+
+ public static string NumeroSerial
+ {
+ get
+ {
+ return ApplicationHelper._numeroSerial ?? ApplicationHelper.GetSerialNumber();
+ }
+ set
+ {
+ ApplicationHelper._numeroSerial = value;
+ }
+ }
+
+ public static string Subkey
+ {
+ get;
+ set;
+ }
+
+ public static Version Versao
+ {
+ get;
+ set;
+ }
+
+ static ApplicationHelper()
+ {
+ ApplicationHelper.Conectado = true;
+ ApplicationHelper.Beta = false;
+ ApplicationHelper.ChecagemVersao = Funcoes.GetNetworkTime();
+ }
+
+ public ApplicationHelper()
+ {
+ }
+
+ internal static string GetSerialNumber()
+ {
+ string numeroSerial;
+ string str;
+ try
+ {
+ string str1 = (new RegistryHelper(ApplicationHelper.Subkey)).Read("NS", true);
+ if (string.IsNullOrEmpty(str1))
+ {
+ str = null;
+ }
+ else
+ {
+ str = EncryptionHelper.Decrypt(str1);
+ }
+ ApplicationHelper.NumeroSerial = str;
+ numeroSerial = ApplicationHelper.NumeroSerial;
+ }
+ catch (Exception exception)
+ {
+ numeroSerial = null;
+ }
+ return numeroSerial;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs b/Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs new file mode 100644 index 0000000..c140906 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ArquivoDigital.cs @@ -0,0 +1,65 @@ +using ArquivoDigital.Infrastructure.UnitOfWork.Logic;
+using Gestor.Application.Servicos.Generic;
+using Gestor.Model.Domain.Common;
+using System;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public static class ArquivoDigital
+ {
+ public static string ConexaoAd;
+
+ public static string Banco
+ {
+ get;
+ set;
+ }
+
+ public static UnitOfWork Commited
+ {
+ get
+ {
+ return Gestor.Application.Helpers.ArquivoDigital.UnitOfWork(true, false);
+ }
+ }
+
+ public static UnitOfWork Read
+ {
+ get
+ {
+ return Gestor.Application.Helpers.ArquivoDigital.UnitOfWork(false, false);
+ }
+ }
+
+ public static string Tabela
+ {
+ get;
+ set;
+ }
+
+ static ArquivoDigital()
+ {
+ Gestor.Application.Helpers.ArquivoDigital.ConexaoAd = null;
+ Gestor.Application.Helpers.ArquivoDigital.Tabela = "arquivodigital";
+ }
+
+ public static void SetConnection(string banco = "")
+ {
+ ControleArquivoDigital controleArquivoDigital = (string.IsNullOrEmpty(banco) ? (new BaseServico()).ArquivoDigital().Result : (new BaseServico()).ArquivoDigital(banco).Result);
+ Gestor.Application.Helpers.ArquivoDigital.Banco = controleArquivoDigital.get_Catalogo();
+ Gestor.Application.Helpers.ArquivoDigital.Tabela = (string.IsNullOrWhiteSpace(controleArquivoDigital.get_Tabela()) ? "arquivodigital" : controleArquivoDigital.get_Tabela());
+ Gestor.Application.Helpers.ArquivoDigital.ConexaoAd = string.Concat(new string[] { "Server=", Connection.Server, ";initial catalog=", controleArquivoDigital.get_Catalogo(), ";user=", Connection.User, ";password=", Connection.Password, ";" });
+ }
+
+ private static UnitOfWork UnitOfWork(bool withTransaction = true, bool reconect = false)
+ {
+ if (Gestor.Application.Helpers.ArquivoDigital.ConexaoAd == null)
+ {
+ Gestor.Application.Helpers.ArquivoDigital.SetConnection("");
+ }
+ return new UnitOfWork(Gestor.Application.Helpers.ArquivoDigital.ConexaoAd, Gestor.Application.Helpers.ArquivoDigital.Tabela, withTransaction);
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs b/Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs new file mode 100644 index 0000000..2a6939d --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/AssinadorHelper.cs @@ -0,0 +1,211 @@ +using Agger.Registro;
+using Assinador.Model.Domain;
+using Newtonsoft.Json;
+using Sign.Modelos;
+using System;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public static class AssinadorHelper
+ {
+ private static ParametrosAssinaturaAssinador _parametros;
+
+ public const string Authorization = "Authorization";
+
+ public const string Server = "Server";
+
+ public const string Contrato = "Purchase";
+
+ public const string Adquirir = "Purchase/BuyPackage";
+
+ public const string Disponiveis = "Sign/Availble";
+
+ public const string Contratadas = "Sign/Purchased";
+
+ private static string ApiKey
+ {
+ get;
+ set;
+ }
+
+ public static ParametrosAssinaturaAssinador Parametros
+ {
+ get
+ {
+ return AssinadorHelper._parametros;
+ }
+ set
+ {
+ AssinadorHelper._parametros = value;
+ if (value == null)
+ {
+ return;
+ }
+ Sign.Modelos.Remetente remetente = new Sign.Modelos.Remetente();
+ remetente.set_Id(ApplicationHelper.IdFornecedor);
+ remetente.set_Documento(value.get_Documento());
+ remetente.set_Email(value.get_Email());
+ remetente.set_Nome(value.get_Nome());
+ remetente.set_Serial(ApplicationHelper.NumeroSerial);
+ AssinadorHelper.Remetente = remetente;
+ }
+ }
+
+ public static Sign.Modelos.Remetente Remetente
+ {
+ get;
+ set;
+ }
+
+ private static string Base64EncodeBasic(string plainText)
+ {
+ return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
+ }
+
+ public static string BasicKey(this string serial)
+ {
+ DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime();
+ return AssinadorHelper.Base64EncodeBasic(string.Format("{0}:{1}", serial, universalTime.Ticks));
+ }
+
+ public static async Task<bool> Contratado(long id)
+ {
+ bool flag = await AssinadorHelper.Get<string>(string.Format("{0}{1}/{2}/86", Address.GestorApi(), "Purchase", id), ApplicationHelper.NumeroSerial.BasicKey(), true) == "true";
+ return flag;
+ }
+
+ public static async Task<HttpStatusCode> Get(string command, string token = null, bool basic = false)
+ {
+ HttpStatusCode statusCode;
+ HttpResponseMessage httpResponseMessage;
+ string str = (basic ? "Basic" : "Token");
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient httpClient = new HttpClient();
+ if (!string.IsNullOrWhiteSpace(token))
+ {
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token));
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ ConfiguredTaskAwaitable<HttpResponseMessage> configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+ httpResponseMessage = await configuredTaskAwaitable;
+ }
+ catch (Exception exception)
+ {
+ statusCode = HttpStatusCode.InternalServerError;
+ return statusCode;
+ }
+ statusCode = httpResponseMessage.get_StatusCode();
+ return statusCode;
+ }
+
+ internal static async Task<T> Get<T>(string command, string token = null, bool basic = false)
+ where T : class
+ {
+ T t;
+ HttpResponseMessage httpResponseMessage;
+ string str = (basic ? "Basic" : "Token");
+ Uri uri = new Uri(command);
+ HttpClient httpClient = new HttpClient();
+ if (!string.IsNullOrWhiteSpace(token))
+ {
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token));
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ ConfiguredTaskAwaitable<HttpResponseMessage> configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+ httpResponseMessage = await configuredTaskAwaitable;
+ }
+ catch (Exception exception)
+ {
+ t = default(T);
+ return t;
+ }
+ if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK)
+ {
+ string result = httpResponseMessage.get_Content().ReadAsStringAsync().Result;
+ t = JsonConvert.DeserializeObject<T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+ }
+ else
+ {
+ t = default(T);
+ }
+ return t;
+ }
+
+ public static async Task<string> Key()
+ {
+ string str = null;
+ try
+ {
+ str = await AssinadorHelper.Get<string>(string.Format("{0}{1}/86", Address.AssinadorApi(), "Authorization"), ApplicationHelper.NumeroSerial.BasicKey(), true);
+ }
+ catch (Exception exception)
+ {
+ }
+ string str1 = str;
+ str = null;
+ return str1;
+ }
+
+ public static async Task<int> Licencas(string key)
+ {
+ int num;
+ if (key != null)
+ {
+ int num1 = 0;
+ try
+ {
+ string str = await AssinadorHelper.Get<string>(string.Format("{0}{1}/{2}", Address.AssinadorApi(), "Sign/Availble", ApplicationHelper.IdFornecedor), key, false);
+ num1 = int.Parse(str);
+ }
+ catch (Exception exception)
+ {
+ }
+ num = num1;
+ }
+ else
+ {
+ num = 0;
+ }
+ return num;
+ }
+
+ internal static async Task<T> Put<T>(string command, T keyValues, string token = null, bool basic = false)
+ where T : class
+ {
+ T t;
+ string str = (basic ? "Basic" : "Token");
+ Uri uri = new Uri(command);
+ object obj = keyValues;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+ HttpClient httpClient = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ if (!string.IsNullOrWhiteSpace(token))
+ {
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue(str, token));
+ }
+ HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent);
+ if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK || httpResponseMessage.get_StatusCode() == HttpStatusCode.NoContent)
+ {
+ t = (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent ? JsonConvert.DeserializeObject<T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result) : default(T));
+ }
+ else
+ {
+ t = default(T);
+ }
+ return t;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs b/Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs new file mode 100644 index 0000000..54e9330 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/BindingEnumHelper.cs @@ -0,0 +1,56 @@ +using System;
+using System.ComponentModel;
+using System.Reflection;
+using System.Text;
+
+namespace Gestor.Application.Helpers
+{
+ public class BindingEnumHelper
+ {
+ public BindingEnumHelper()
+ {
+ }
+
+ public static string ConcatenarDescricoesEnum<TEnum>(string valores)
+ where TEnum : Enum
+ {
+ if (valores == null)
+ {
+ return null;
+ }
+ return BindingEnumHelper.ConcatenarDescricoesEnum<TEnum>(Array.ConvertAll<string, int>(valores.Split(new char[] { ',' }), new Converter<string, int>(int.Parse)));
+ }
+
+ private static string ConcatenarDescricoesEnum<TEnum>(int[] valores)
+ where TEnum : Enum
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ int[] numArray = valores;
+ for (int i = 0; i < (int)numArray.Length; i++)
+ {
+ int num = numArray[i];
+ if (!Enum.IsDefined(typeof(TEnum), num))
+ {
+ stringBuilder.Append("Valor desconhecido, ");
+ }
+ else
+ {
+ string str = BindingEnumHelper.ObterDescricaoEnum<TEnum>((TEnum)Enum.ToObject(typeof(TEnum), num));
+ stringBuilder.Append(string.Concat(str, ", "));
+ }
+ }
+ return stringBuilder.ToString().TrimEnd(new char[] { ',', ' ' });
+ }
+
+ private static string ObterDescricaoEnum<TEnum>(TEnum valor)
+ where TEnum : Enum
+ {
+ DescriptionAttribute[] customAttributes = (DescriptionAttribute[])valor.GetType().GetField(valor.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
+ if (customAttributes == null || customAttributes.Length == 0)
+ {
+ return valor.ToString();
+ }
+ return customAttributes[0].Description;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/BindingHelper.cs b/Codemerx/Gestor.Application/Helpers/BindingHelper.cs new file mode 100644 index 0000000..3c9d76e --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/BindingHelper.cs @@ -0,0 +1,239 @@ +using CurrencyTextBoxControl;
+using Gestor.Common.Helpers;
+using Gestor.Model.Helper;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+
+namespace Gestor.Application.Helpers
+{
+ public static class BindingHelper
+ {
+ public static void AddBinding(object control, string path, ValidationRule rule = null)
+ {
+ Type type = control.GetType();
+ Binding binding = new Binding()
+ {
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
+ Path = new PropertyPath(path, Array.Empty<object>())
+ };
+ if (rule != null)
+ {
+ binding.ValidationRules.Add(rule);
+ binding.ValidationRules[0].ValidatesOnTargetUpdated = true;
+ }
+ string name = type.Name;
+ if (name == "TextBox")
+ {
+ ((TextBox)control).SetBinding(TextBox.TextProperty, binding);
+ return;
+ }
+ if (name == "DatePicker")
+ {
+ ((DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, binding);
+ return;
+ }
+ if (name != "CurrencyTextBox")
+ {
+ return;
+ }
+ ((CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, binding);
+ }
+
+ public static void AddValidationRule(object control, ValidationRule rule = null)
+ {
+ //
+ // Current member / type: System.Void Gestor.Application.Helpers.BindingHelper::AddValidationRule(System.Object,System.Windows.Controls.ValidationRule)
+ // File path: C:\AggerSeguros\Gestor.Application.exe
+ //
+ // Product version: 0.0.0.0
+ // Exception in: System.Void AddValidationRule(System.Object,System.Windows.Controls.ValidationRule)
+ //
+ // Object reference not set to an instance of an object.
+ // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515
+ // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459
+ // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378
+ // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331
+ // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104
+ // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100
+ // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72
+ // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61
+ // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133
+ //
+ // mailto: JustDecompilePublicFeedback@telerik.com
+
+ }
+
+ private static List<KeyValuePair<string, string>> AfterTreatment<T>(bool withSelect, bool orderByLabel, List<KeyValuePair<string, string>> comboData, List<KeyValuePair<string, string>> comboValues, bool orderbyAttr = false)
+ {
+ List<KeyValuePair<string, string>> list = comboData;
+ if (!withSelect)
+ {
+ list.RemoveAt(0);
+ }
+ list.AddRange(comboValues);
+ if (orderbyAttr)
+ {
+ Type type = typeof(T);
+ list = list.OrderBy<KeyValuePair<string, string>, int?>((KeyValuePair<string, string> s) => {
+ if (s.Key == string.Empty)
+ {
+ return new int?(0);
+ }
+ return EnumHelper.GetOrder<T>((T)Enum.Parse(type, s.Key));
+ }).ToList<KeyValuePair<string, string>>();
+ return list;
+ }
+ if (!orderByLabel)
+ {
+ return list;
+ }
+ list = (
+ from in list
+ orderby Math.Sign(ValidationHelper.ToFloat(x.Key)), Math.Abs(ValidationHelper.ToFloat(x.Key))
+ select ).ToList<KeyValuePair<string, string>>();
+ list = (
+ from in list
+ orderby list.IndexOf(s) != 0, s.Value
+ select ).ToList<KeyValuePair<string, string>>();
+ return list;
+ }
+
+ 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)
+ };
+ }
+
+ 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>> keyValuePairs = BindingHelper.BeforeTreatment<T>(defaultValue, defaultText);
+ Type type = typeof(T);
+ List<KeyValuePair<string, string>> list = Enum.GetNames(type).AsEnumerable<string>().Where<string>((string x) => {
+ if (showAll)
+ {
+ return true;
+ }
+ T t = (T)Enum.Parse(type, x);
+ bool? @default = EnumHelper.GetDefault<T>(t);
+ bool hidden = EnumHelper.GetHidden<T>(t);
+ if (@default.HasValue && @default.Value != enumDefault)
+ {
+ return false;
+ }
+ return !hidden;
+ }).Select<string, KeyValuePair<string, string>>((string x) => {
+ T t = (T)Enum.Parse(type, x);
+ return new KeyValuePair<string, string>(EnumHelper.Value<T>(t), EnumHelper.GetDescription<T>(t));
+ }).ToList<KeyValuePair<string, string>>();
+ return BindingHelper.AfterTreatment<T>(withSelect, orderByLabel, keyValuePairs, list, orderbyAttr);
+ }
+
+ public static void DeleteValidationRule(object control)
+ {
+ Binding binding;
+ string name = control.GetType().Name;
+ if (name == "TextBox")
+ {
+ binding = BindingOperations.GetBinding((TextBox)control, TextBox.TextProperty) ?? new Binding()
+ {
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ binding.ValidationRules.Clear();
+ ((TextBox)control).SetBinding(TextBox.TextProperty, binding);
+ return;
+ }
+ if (name == "DatePicker")
+ {
+ binding = BindingOperations.GetBinding((DatePicker)control, DatePicker.SelectedDateProperty) ?? new Binding()
+ {
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ binding.ValidationRules.Clear();
+ ((DatePicker)control).SetBinding(DatePicker.SelectedDateProperty, binding);
+ return;
+ }
+ if (name != "CurrencyTextBox")
+ {
+ return;
+ }
+ binding = BindingOperations.GetBinding((CurrencyTextBox)control, CurrencyTextBox.NumberProperty) ?? new Binding()
+ {
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ binding.ValidationRules.Clear();
+ ((CurrencyTextBox)control).SetBinding(CurrencyTextBox.NumberProperty, binding);
+ }
+
+ public static string GetPath(object control)
+ {
+ Binding binding;
+ PropertyPath path;
+ string name = control.GetType().Name;
+ if (name == "TextBox")
+ {
+ binding = BindingOperations.GetBinding((TextBox)control, TextBox.TextProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ }
+ else if (name == "DatePicker")
+ {
+ binding = BindingOperations.GetBinding((DatePicker)control, DatePicker.SelectedDateProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ }
+ else if (name == "CurrencyTextBox")
+ {
+ binding = BindingOperations.GetBinding((CurrencyTextBox)control, CurrencyTextBox.NumberProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ }
+ else if (name == "ComboBox")
+ {
+ binding = BindingOperations.GetBinding((ComboBox)control, Selector.SelectedItemProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ }
+ else
+ {
+ if (name != "AutoCompleteBox")
+ {
+ return "";
+ }
+ binding = BindingOperations.GetBinding((AutoCompleteBox)control, AutoCompleteBox.SelectedItemProperty);
+ if (binding == null)
+ {
+ return "";
+ }
+ path = binding.Path;
+ }
+ return path.Path;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Connection.cs b/Codemerx/Gestor.Application/Helpers/Connection.cs new file mode 100644 index 0000000..7458e99 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Connection.cs @@ -0,0 +1,632 @@ +using Agger.Registro;
+using Gestor.Common.Security;
+using Gestor.Common.Validation;
+using Gestor.Model.API;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public static class Connection
+ {
+ private const bool defaultUsaAzureStorage = false;
+
+ private const string defaultAzureStorage = "ad1";
+
+ public static string Server;
+
+ public static string Catalog;
+
+ public static string User;
+
+ public static string Password;
+
+ public static string Pool;
+
+ public static string Type;
+
+ public static Gestor.Model.API.ConnectionAddress ConnectionAddress
+ {
+ get;
+ set;
+ }
+
+ public static string LinkAggilizador
+ {
+ get;
+ set;
+ }
+
+ public static string UrlCentralSegurado
+ {
+ get;
+ set;
+ }
+
+ private static string AdApiV2(string storage)
+ {
+ if (Address.get_ApiAD().ToString().Contains("/api/v1"))
+ {
+ return string.Empty;
+ }
+ return storage;
+ }
+
+ internal static Uri Append(this Uri uri, params string[] paths)
+ {
+ return new Uri(paths.Aggregate<string, string>(uri.AbsoluteUri, (string current, string path) => string.Concat(current.TrimEnd(new char[] { '/' }), "/", path.TrimStart(new char[] { '/' }))));
+ }
+
+ public static string Base64Encode(this string plainText)
+ {
+ return (new Token()).Encrypt(plainText);
+ }
+
+ public static string BasicKey()
+ {
+ string numeroSerial = ApplicationHelper.NumeroSerial;
+ DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime();
+ return string.Format("{0}:{1}", numeroSerial, universalTime.Ticks).Base64Encode();
+ }
+
+ public static async Task<bool> Delete(string command)
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient httpClient = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ if (await httpClient.DeleteAsync(uri).get_StatusCode() != HttpStatusCode.OK)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+ }
+ return true;
+ }
+
+ internal static async Task<bool> DeleteFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad")
+ {
+ bool flag;
+ string str;
+ bool flag1;
+ str = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
+ azureStorage = str;
+ Uri apiAD = Address.get_ApiAD();
+ string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(azureStorage) };
+ Uri uri = apiAD.Append(strArrays);
+ string[] strArrays1 = new string[] { path };
+ Uri uri1 = uri.Append(strArrays1);
+ string[] str1 = new string[] { ano.ToString() };
+ Uri uri2 = uri1.Append(str1);
+ string[] str2 = new string[] { id.ToString() };
+ Uri uri3 = uri2.Append(str2);
+ string[] strArrays2 = new string[] { extensao.Replace(".", string.Empty) };
+ Uri uri4 = uri3.Append(strArrays2);
+ try
+ {
+ using (HttpClient httpClient = new HttpClient())
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().Clear();
+ httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage httpResponseMessage = await httpClient.DeleteAsync(uri4);
+ flag1 = (!httpResponseMessage.get_IsSuccessStatusCode() ? false : httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent);
+ flag = flag1;
+ return flag;
+ }
+ }
+ catch
+ {
+ }
+ flag = false;
+ return flag;
+ }
+
+ internal static async Task<byte[]> DownloadFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad", bool forceDownload = false)
+ {
+ byte[] numArray;
+ string str;
+ str = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
+ azureStorage = str;
+ Uri apiAD = Address.get_ApiAD();
+ string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(azureStorage) };
+ Uri uri = apiAD.Append(strArrays);
+ string[] strArrays1 = new string[] { path };
+ Uri uri1 = uri.Append(strArrays1);
+ string[] str1 = new string[] { ano.ToString() };
+ Uri uri2 = uri1.Append(str1);
+ string[] str2 = new string[] { id.ToString() };
+ Uri uri3 = uri2.Append(str2);
+ string[] strArrays2 = new string[] { extensao.Replace(".", string.Empty) };
+ Uri uri4 = uri3.Append(strArrays2);
+ try
+ {
+ string str3 = string.Format("{0}{1}{2}", Path.GetTempPath(), id, extensao);
+ if (forceDownload || !File.Exists(str3))
+ {
+ using (HttpClient httpClient = new HttpClient())
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().Clear();
+ httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage async = await httpClient.GetAsync(uri4);
+ if (async.get_IsSuccessStatusCode() && async.get_StatusCode() != HttpStatusCode.NotFound)
+ {
+ numArray = await async.get_Content().ReadAsByteArrayAsync();
+ return numArray;
+ }
+ }
+ httpClient = null;
+ }
+ else
+ {
+ numArray = File.ReadAllBytes(str3);
+ return numArray;
+ }
+ }
+ catch
+ {
+ }
+ numArray = null;
+ return numArray;
+ }
+
+ public static string EncodeBase64(this string plainText)
+ {
+ string base64String;
+ try
+ {
+ base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
+ }
+ catch
+ {
+ return string.Empty;
+ }
+ return base64String;
+ }
+
+ internal static async Task<double> EspacoUsadoAzureInBytes(string path = "")
+ {
+ double num;
+ Uri apiAD = Address.get_ApiAD();
+ string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(Gestor.Application.Helpers.Connection.ConnectionAddress.get_AzureStorage()) };
+ Uri uri = apiAD.Append(strArrays);
+ string[] strArrays1 = new string[] { "tamanho" };
+ Uri uri1 = uri.Append(strArrays1);
+ if (!string.IsNullOrEmpty(path))
+ {
+ string[] strArrays2 = new string[] { path };
+ uri1.Append(strArrays2);
+ }
+ try
+ {
+ using (HttpClient httpClient = new HttpClient())
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().Clear();
+ httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage async = await httpClient.GetAsync(uri1);
+ if (async.get_IsSuccessStatusCode() && async.get_StatusCode() != HttpStatusCode.NoContent)
+ {
+ num = double.Parse(await async.get_Content().ReadAsStringAsync());
+ return num;
+ }
+ }
+ httpClient = null;
+ }
+ catch
+ {
+ }
+ num = 0;
+ return num;
+ }
+
+ public static async Task<T> Get<T>(string command, bool autorizar = true, bool verificarConexao = false)
+ where T : class
+ {
+ Gestor.Application.Helpers.T t;
+ HttpResponseMessage httpResponseMessage;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient httpClient = new HttpClient();
+ if (autorizar)
+ {
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ ConfiguredTaskAwaitable<HttpResponseMessage> configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+ httpResponseMessage = await configuredTaskAwaitable;
+ }
+ catch (Exception exception)
+ {
+ ApplicationHelper.Conectado = false;
+ t = default(Gestor.Application.Helpers.T);
+ return t;
+ }
+ if (verificarConexao)
+ {
+ ApplicationHelper.Conectado = true;
+ }
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+ {
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+ }
+ t = JsonConvert.DeserializeObject<Gestor.Application.Helpers.T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+ }
+ else
+ {
+ t = default(Gestor.Application.Helpers.T);
+ }
+ return t;
+ }
+
+ public static async Task<HttpStatusCode> Get(string command, bool autorizar = true)
+ {
+ HttpStatusCode statusCode;
+ HttpResponseMessage httpResponseMessage;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient httpClient = new HttpClient();
+ if (autorizar)
+ {
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ ConfiguredTaskAwaitable<HttpResponseMessage> configuredTaskAwaitable = httpClient.GetAsync(uri).ConfigureAwait(false);
+ httpResponseMessage = await configuredTaskAwaitable;
+ }
+ catch (Exception exception)
+ {
+ statusCode = HttpStatusCode.InternalServerError;
+ return statusCode;
+ }
+ statusCode = httpResponseMessage.get_StatusCode();
+ return statusCode;
+ }
+
+ public static string GetAdConnection(string serial)
+ {
+ ApplicationHelper.NumeroSerial = serial;
+ if (string.IsNullOrWhiteSpace(Gestor.Application.Helpers.Connection.Server))
+ {
+ Gestor.Application.Helpers.Connection.GetAdConnection(serial);
+ }
+ return string.Concat(new string[] { "Server=", Gestor.Application.Helpers.Connection.Server, ";initial catalog=", Gestor.Application.Helpers.Connection.Catalog, "AD;user=", Gestor.Application.Helpers.Connection.User, ";password=", Gestor.Application.Helpers.Connection.Password, ";" });
+ }
+
+ public static string GetConnection(bool tryconnect = true)
+ {
+ string str;
+ string aggilizador;
+ string urlCentralSegurado;
+ try
+ {
+ Token token = new Token();
+ RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey);
+ bool usaAzureStorage = false;
+ string str1 = "ad1";
+ if (ApplicationHelper.Conectado)
+ {
+ List<Gestor.Model.API.ConnectionAddress> result = Gestor.Application.Helpers.Connection.Get<List<Gestor.Model.API.ConnectionAddress>>(string.Format("Server/{0}", ApplicationHelper.IdFornecedor), true, false).Result;
+ for (int i = 0; i < result.Count; i++)
+ {
+ string str2 = token.AggerEncrypt(token.Decrypt(result[i].get_Server()));
+ string str3 = token.AggerEncrypt(token.Decrypt(result[i].get_Catalog()));
+ string str4 = token.AggerEncrypt(token.Decrypt(result[i].get_User()));
+ string str5 = token.AggerEncrypt(token.Decrypt(result[i].get_Password()));
+ string str6 = token.AggerEncrypt(token.Decrypt(result[i].get_Pool()));
+ string str7 = result[i].get_Type().ToString();
+ if (string.IsNullOrEmpty(result[i].get_Aggilizador()))
+ {
+ aggilizador = null;
+ }
+ else
+ {
+ aggilizador = result[i].get_Aggilizador();
+ }
+ Gestor.Application.Helpers.Connection.LinkAggilizador = aggilizador;
+ if (string.IsNullOrEmpty(result[i].get_UrlCentralSegurado()))
+ {
+ urlCentralSegurado = null;
+ }
+ else
+ {
+ urlCentralSegurado = result[0].get_UrlCentralSegurado();
+ }
+ Gestor.Application.Helpers.Connection.UrlCentralSegurado = urlCentralSegurado;
+ usaAzureStorage = result[i].get_UsaAzureStorage();
+ str1 = (string.IsNullOrEmpty(result[i].get_AzureStorage()) ? "ad1" : token.Decrypt(result[i].get_AzureStorage()));
+ registryHelper.Write<string>(string.Format("SERVER{0}", i + 1), str2, true);
+ registryHelper.Write<string>(string.Format("DB{0}", i + 1), str3, true);
+ registryHelper.Write<string>(string.Format("USER{0}", i + 1), str4, true);
+ registryHelper.Write<string>(string.Format("PASSWORD{0}", i + 1), str5, true);
+ registryHelper.Write<string>(string.Format("POOL{0}", i + 1), str6, true);
+ registryHelper.Write<string>(string.Format("TYPE{0}", i + 1), str7, true);
+ }
+ }
+ string str8 = "";
+ for (int j = 0; j < 3 && registryHelper.Read(string.Format("SERVER{0}", j + 1), true) != null; j++)
+ {
+ if (registryHelper.Read(string.Format("TYPE{0}", j + 1), true) != "4")
+ {
+ Gestor.Application.Helpers.Connection.Server = token.AggerDecrypt(registryHelper.Read(string.Format("SERVER{0}", j + 1), true));
+ Gestor.Application.Helpers.Connection.Catalog = token.AggerDecrypt(registryHelper.Read(string.Format("DB{0}", j + 1), true));
+ Gestor.Application.Helpers.Connection.User = token.AggerDecrypt(registryHelper.Read(string.Format("USER{0}", j + 1), true));
+ Gestor.Application.Helpers.Connection.Password = token.AggerDecrypt(registryHelper.Read(string.Format("PASSWORD{0}", j + 1), true));
+ Gestor.Application.Helpers.Connection.Pool = token.AggerDecrypt(registryHelper.Read(string.Format("POOL{0}", j + 1), true));
+ Gestor.Application.Helpers.Connection.Type = registryHelper.Read(string.Format("TYPE{0}", j + 1), true);
+ if (!usaAzureStorage)
+ {
+ usaAzureStorage = Task.Run<bool>(async () => await Gestor.Application.Helpers.Connection.SaveInAzureStorage()).Result;
+ }
+ Gestor.Model.API.ConnectionAddress connectionAddress = new Gestor.Model.API.ConnectionAddress();
+ connectionAddress.set_Server(Gestor.Application.Helpers.Connection.Server);
+ connectionAddress.set_Catalog(Gestor.Application.Helpers.Connection.Catalog);
+ connectionAddress.set_User(Gestor.Application.Helpers.Connection.User);
+ connectionAddress.set_Password(Gestor.Application.Helpers.Connection.Password);
+ connectionAddress.set_Pool(Gestor.Application.Helpers.Connection.Pool);
+ connectionAddress.set_Aggilizador(Gestor.Application.Helpers.Connection.LinkAggilizador);
+ connectionAddress.set_UrlCentralSegurado(Gestor.Application.Helpers.Connection.UrlCentralSegurado);
+ connectionAddress.set_UsaAzureStorage(usaAzureStorage);
+ connectionAddress.set_AzureStorage(str1);
+ connectionAddress.set_Type(int.Parse((Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(Gestor.Application.Helpers.Connection.Type) ? "0" : Gestor.Application.Helpers.Connection.Type)));
+ Gestor.Application.Helpers.Connection.ConnectionAddress = connectionAddress;
+ string connectionString = Gestor.Application.Helpers.Connection.GetConnectionString();
+ if (!tryconnect || Gestor.Application.Helpers.Connection.TryConnect(connectionString, 1))
+ {
+ str8 = connectionString;
+ break;
+ }
+ }
+ }
+ str = str8;
+ }
+ catch (Exception exception)
+ {
+ str = null;
+ }
+ return str;
+ }
+
+ public static string GetConnectionString()
+ {
+ return string.Concat(new string[] { "Server=", Gestor.Application.Helpers.Connection.Server, ";initial catalog=", Gestor.Application.Helpers.Connection.Catalog, ";user=", Gestor.Application.Helpers.Connection.User, ";password=", Gestor.Application.Helpers.Connection.Password, ";" });
+ }
+
+ public static async Task<string> GetPool()
+ {
+ string pool;
+ Gestor.Model.API.ConnectionAddress connectionAddress = await Gestor.Application.Helpers.Connection.Get<Gestor.Model.API.ConnectionAddress>("Server/Pool", true, false);
+ if (connectionAddress != null)
+ {
+ Gestor.Application.Helpers.Connection.Pool = (new Token()).Decrypt(connectionAddress.get_Pool());
+ pool = Gestor.Application.Helpers.Connection.Pool;
+ }
+ else
+ {
+ pool = "";
+ }
+ return pool;
+ }
+
+ public static async Task<T> Post<T>(string command, T keyValues)
+ where T : class
+ {
+ Gestor.Application.Helpers.T t;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ object obj = keyValues;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ jsonSerializerSetting.set_MissingMemberHandling(0);
+ StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+ HttpClient httpClient = new HttpClient();
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, stringContent);
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+ {
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+ }
+ t = JsonConvert.DeserializeObject<Gestor.Application.Helpers.T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+ }
+ else
+ {
+ t = default(Gestor.Application.Helpers.T);
+ }
+ return t;
+ }
+
+ public static async Task<T> Post<T>(string command, object keyValues)
+ where T : class
+ {
+ Gestor.Application.Helpers.T t;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ object obj = keyValues;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ jsonSerializerSetting.set_MissingMemberHandling(0);
+ StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+ HttpClient httpClient = new HttpClient();
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, stringContent);
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+ {
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+ }
+ t = JsonConvert.DeserializeObject<Gestor.Application.Helpers.T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+ }
+ else
+ {
+ t = default(Gestor.Application.Helpers.T);
+ }
+ return t;
+ }
+
+ public static async Task<T> Put<T>(string command, T keyValues)
+ where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), command);
+ object obj = keyValues;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+ HttpClient httpClient = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent);
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+ }
+ Gestor.Application.Helpers.T t = JsonConvert.DeserializeObject<Gestor.Application.Helpers.T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+ return t;
+ }
+
+ public static async Task<T> Put<T>(string command, object keyValues)
+ where T : class
+ {
+ Gestor.Application.Helpers.T t;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ object obj = keyValues;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+ HttpClient httpClient = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri, stringContent);
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent)
+ {
+ if (httpResponseMessage.get_StatusCode() != HttpStatusCode.OK)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " ", command), null);
+ }
+ t = JsonConvert.DeserializeObject<Gestor.Application.Helpers.T>(httpResponseMessage.get_Content().ReadAsStringAsync().Result);
+ }
+ else
+ {
+ t = default(Gestor.Application.Helpers.T);
+ }
+ return t;
+ }
+
+ public static async void PutError<T>(T keyValues)
+ where T : class
+ {
+ Uri uri = new Uri(Address.GestorApi(), "Error/Objeto");
+ object obj = keyValues;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ StringContent stringContent = new StringContent(JsonConvert.SerializeObject(obj, 1, jsonSerializerSetting), Encoding.UTF8, "application/json");
+ HttpClient httpClient = new HttpClient();
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ if (await httpClient.PutAsync(uri, stringContent).get_StatusCode() != HttpStatusCode.NoContent)
+ {
+ throw new Exception(string.Concat("Api connection Error ", Environment.NewLine, " Error"), null);
+ }
+ }
+
+ internal static async Task<bool> SaveInAzureStorage()
+ {
+ bool flag;
+ string str = string.Format("{0}Data", Address.GestorApi());
+ try
+ {
+ using (HttpClient httpClient = new HttpClient())
+ {
+ httpClient.get_DefaultRequestHeaders().Clear();
+ httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage async = await httpClient.GetAsync(str);
+ if (async.get_IsSuccessStatusCode())
+ {
+ flag = await async.get_Content().ReadAsStringAsync() == "true";
+ return flag;
+ }
+ }
+ httpClient = null;
+ }
+ catch
+ {
+ }
+ flag = false;
+ return flag;
+ }
+
+ internal static bool TryConnect(string connectionString, int retryCount = 1)
+ {
+ bool flag;
+ List<Exception> exceptions = new List<Exception>();
+ int num = 0;
+ Label1:
+ while (num < retryCount)
+ {
+ try
+ {
+ using (SqlConnection sqlConnection = new SqlConnection(connectionString))
+ {
+ sqlConnection.Open();
+ }
+ flag = true;
+ }
+ catch (Exception exception)
+ {
+ exceptions.Add(exception);
+ goto Label0;
+ }
+ return flag;
+ }
+ return exceptions.Count == 0;
+ Label0:
+ num++;
+ goto Label1;
+ }
+
+ internal static async Task<bool> UploadFile(UploadFile upload, string path = "ad")
+ {
+ bool flag;
+ bool flag1;
+ Uri apiAD = Address.get_ApiAD();
+ string[] strArrays = new string[] { Gestor.Application.Helpers.Connection.AdApiV2(Gestor.Application.Helpers.Connection.ConnectionAddress.get_AzureStorage()) };
+ Uri uri = apiAD.Append(strArrays);
+ string[] strArrays1 = new string[] { path };
+ Uri uri1 = uri.Append(strArrays1);
+ try
+ {
+ using (HttpClient httpClient = new HttpClient())
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ httpClient.get_DefaultRequestHeaders().Clear();
+ httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Token ", Gestor.Application.Helpers.Connection.BasicKey()));
+ HttpResponseMessage httpResponseMessage = await httpClient.PutAsync(uri1, new StringContent(JsonConvert.SerializeObject(upload), Encoding.UTF8, "application/json"));
+ flag1 = (!httpResponseMessage.get_IsSuccessStatusCode() ? false : httpResponseMessage.get_StatusCode() != HttpStatusCode.NoContent);
+ flag = flag1;
+ return flag;
+ }
+ }
+ catch
+ {
+ }
+ flag = false;
+ return flag;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs b/Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs new file mode 100644 index 0000000..1b364ca --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ConnectionHelper.cs @@ -0,0 +1,521 @@ +using Agger.Registro;
+using Gestor.Application.Migration;
+using Gestor.Common.Exceptions;
+using Gestor.Model.API;
+using System;
+using System.Collections.Generic;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public class ConnectionHelper
+ {
+ public static bool BancoAtualizado
+ {
+ get;
+ set;
+ }
+
+ public ConnectionHelper()
+ {
+ }
+
+ public async Task<string> AtualizarBanco()
+ {
+ string str;
+ bool flag = await (new Migrator()).Execute();
+ ConnectionHelper.BancoAtualizado = flag;
+ if (flag)
+ {
+ str = null;
+ }
+ else
+ {
+ str = "HOUVE UM PROBLEMA AO ATUALIZAR O BANCO DE DADOS.";
+ }
+ return str;
+ }
+
+ public bool BDConvertido()
+ {
+ bool flag;
+ try
+ {
+ using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(false)))
+ {
+ sqlConnection.Open();
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT OBJECT_ID('dbo.AtualizacaoDados', 'U')";
+ if (sqlCommand.ExecuteScalar() == DBNull.Value)
+ {
+ flag = true;
+ return flag;
+ }
+ }
+ using (SqlCommand sqlCommand1 = sqlConnection.CreateCommand())
+ {
+ sqlCommand1.CommandText = "SELECT COUNT(IdArquivo) FROM AtualizacaoDados";
+ flag = (int)sqlCommand1.ExecuteScalar() == 0;
+ }
+ }
+ }
+ catch
+ {
+ return true;
+ }
+ return flag;
+ }
+
+ public static async Task<string> CheckDatabase()
+ {
+ string message;
+ string str;
+ try
+ {
+ bool flag = await ConnectionHelper.DatabaseExists();
+ bool flag1 = await ConnectionHelper.LoginExists();
+ bool flag2 = await ConnectionHelper.UserExists();
+ bool flag3 = false;
+ if (!(flag & flag1 & flag2))
+ {
+ if (!flag)
+ {
+ flag = await ConnectionHelper.CreateDatabase();
+ }
+ if (flag)
+ {
+ if (!flag1)
+ {
+ bool flag4 = await ConnectionHelper.CreateLogin();
+ bool flag5 = flag4;
+ flag3 = flag4;
+ flag1 = flag5;
+ }
+ if (flag1)
+ {
+ if (!flag2)
+ {
+ flag2 = await ConnectionHelper.CreateUser();
+ }
+ if (flag3)
+ {
+ int num = 10;
+ while (num > 1)
+ {
+ try
+ {
+ using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(true)))
+ {
+ sqlConnection.Open();
+ break;
+ }
+ }
+ catch
+ {
+ Thread.Sleep(10000);
+ num--;
+ }
+ }
+ }
+ if (!flag2)
+ {
+ str = "ERRO AO CRIAR USUÁRIO";
+ }
+ else
+ {
+ str = null;
+ }
+ message = str;
+ }
+ else
+ {
+ message = "ERRO AO CRIAR LOGIN";
+ }
+ }
+ else
+ {
+ message = "ERRO AO CRIAR BANCO DE DADOS";
+ }
+ }
+ else
+ {
+ message = null;
+ }
+ }
+ catch (ValidationException validationException)
+ {
+ message = validationException.Message;
+ }
+ catch (Exception exception)
+ {
+ message = "ERRO AO CRIAR BANCO DE DADOS";
+ }
+ return message;
+ }
+
+ private static async Task<bool> CreateDatabase()
+ {
+ bool flag;
+ bool i;
+ string str = Uri.EscapeDataString(ApplicationHelper.NumeroSerial);
+ if (await ConnectionHelper.Post(string.Concat("Data/CreateData?token=", str)) != "ERRO INTERNO")
+ {
+ int num = 0;
+ for (i = false; num < 24 && !i; i = await ConnectionHelper.DatabaseExists())
+ {
+ await Task.Delay(5000);
+ num++;
+ }
+ flag = i;
+ }
+ else
+ {
+ flag = false;
+ }
+ return flag;
+ }
+
+ private static async Task<bool> CreateLogin()
+ {
+ bool flag;
+ bool i;
+ if (await ConnectionHelper.Post("Data/CreateLogin") != "ERRO INTERNO")
+ {
+ int num = 0;
+ for (i = false; num < 24 && !i; i = await ConnectionHelper.Get("Data/ServerLoginExists", true) == null)
+ {
+ await Task.Delay(5000);
+ num++;
+ }
+ flag = i;
+ }
+ else
+ {
+ flag = false;
+ }
+ return flag;
+ }
+
+ private static async Task<bool> CreateUser()
+ {
+ bool flag;
+ bool i;
+ if (await ConnectionHelper.Post("Data/CreateUser") != "ERRO INTERNO")
+ {
+ int num = 0;
+ for (i = false; num < 24 && !i; i = await ConnectionHelper.Get("Data/UserExists", true) == null)
+ {
+ await Task.Delay(5000);
+ num++;
+ }
+ flag = i;
+ }
+ else
+ {
+ flag = false;
+ }
+ return flag;
+ }
+
+ private static async Task<bool> DatabaseExists()
+ {
+ return await ConnectionHelper.Get("Data/DataExists", true) == null;
+ }
+
+ private static async Task<string> DatabaseTest()
+ {
+ return await ConnectionHelper.Get("Data/Verify", true);
+ }
+
+ public bool ExisteEmpresa()
+ {
+ bool flag;
+ try
+ {
+ using (SqlConnection sqlConnection = new SqlConnection(Gestor.Application.Helpers.Connection.GetConnection(false)))
+ {
+ sqlConnection.Open();
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT OBJECT_ID (N'empresa', N'U')";
+ if (sqlCommand.ExecuteScalar() == DBNull.Value)
+ {
+ flag = false;
+ return flag;
+ }
+ }
+ using (SqlCommand sqlCommand1 = sqlConnection.CreateCommand())
+ {
+ sqlCommand1.CommandText = "SELECT COUNT(idempresa) FROM empresa WHERE idempresa = 1";
+ flag = (int)sqlCommand1.ExecuteScalar() > 0;
+ }
+ }
+ }
+ catch
+ {
+ return true;
+ }
+ return flag;
+ }
+
+ private static async Task<string> Get(string command, bool autorizar = true)
+ {
+ string str;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient httpClient = new HttpClient();
+ httpClient.set_Timeout(new TimeSpan(0, 2, 0));
+ HttpClient httpClient1 = httpClient;
+ if (autorizar)
+ {
+ httpClient1.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ }
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ ConfiguredTaskAwaitable<HttpResponseMessage> configuredTaskAwaitable = httpClient1.GetAsync(uri).ConfigureAwait(false);
+ HttpResponseMessage httpResponseMessage = await configuredTaskAwaitable;
+ if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK)
+ {
+ str = null;
+ }
+ else
+ {
+ str = await httpResponseMessage.get_Content().ReadAsStringAsync();
+ }
+ }
+ catch (Exception exception)
+ {
+ str = "ERRO INTERNO";
+ }
+ return str;
+ }
+
+ internal static async Task<bool> HasLogin(string connectionString)
+ {
+ bool flag1 = await Task.Run<bool>(() => {
+ bool flag;
+ List<Exception> exceptions = new List<Exception>();
+ try
+ {
+ using (SqlConnection sqlConnection = new SqlConnection(connectionString))
+ {
+ sqlConnection.Open();
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT 1 FROM [dbo].[usuario] WHERE [removido] IS NULL OR [removido] = '0'";
+ SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
+ if (sqlDataReader.HasRows)
+ {
+ sqlDataReader.Close();
+ sqlCommand.CommandText = "SELECT 1 FROM [dbo].[empresa] WHERE [idempresa] = 1";
+ sqlDataReader = sqlCommand.ExecuteReader();
+ if (sqlDataReader.HasRows)
+ {
+ sqlDataReader.Close();
+ sqlCommand.CommandText = "SELECT 1 FROM [dbo].[vendedor] WHERE [corretora] = '1'";
+ sqlDataReader = sqlCommand.ExecuteReader();
+ if (sqlDataReader.HasRows)
+ {
+ sqlDataReader.Close();
+ flag = true;
+ }
+ else
+ {
+ flag = false;
+ }
+ }
+ else
+ {
+ flag = false;
+ }
+ }
+ else
+ {
+ flag = false;
+ }
+ }
+ }
+ }
+ catch (Exception exception)
+ {
+ exceptions.Add(exception);
+ return exceptions.Count == 0;
+ }
+ return flag;
+ });
+ return flag1;
+ }
+
+ private static async Task<bool> LoginExists()
+ {
+ return await ConnectionHelper.Get("Data/ServerLoginExists", true) == null;
+ }
+
+ private static async Task<string> Post(string command)
+ {
+ string str;
+ Uri uri = new Uri(Address.GestorApi(), command);
+ HttpClient httpClient = new HttpClient();
+ httpClient.get_DefaultRequestHeaders().set_Authorization(new AuthenticationHeaderValue("Token", Gestor.Application.Helpers.Connection.BasicKey()));
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+ try
+ {
+ HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, null);
+ if (httpResponseMessage.get_StatusCode() == HttpStatusCode.OK)
+ {
+ str = null;
+ }
+ else
+ {
+ str = await httpResponseMessage.get_Content().ReadAsStringAsync();
+ }
+ }
+ catch (Exception exception)
+ {
+ str = "ERRO INTERNO";
+ }
+ return str;
+ }
+
+ public async Task<Tuple<bool, bool>> PrimeiroAcesso()
+ {
+ Tuple<bool, bool> tuple;
+ Tuple<bool, bool> tuple1;
+ string connection = Gestor.Application.Helpers.Connection.GetConnection(false);
+ if (!await ConnectionHelper.TryConnect(connection, 1))
+ {
+ if (await ConnectionHelper.DatabaseExists())
+ {
+ bool flag = !await ConnectionHelper.LoginExists();
+ if (flag)
+ {
+ flag = !await ConnectionHelper.CreateLogin();
+ }
+ if (!flag)
+ {
+ flag = !await ConnectionHelper.UserExists();
+ if (flag)
+ {
+ flag = !await ConnectionHelper.CreateUser();
+ }
+ if (flag)
+ {
+ tuple = new Tuple<bool, bool>(false, false);
+ connection = null;
+ return tuple;
+ }
+ }
+ else
+ {
+ tuple = new Tuple<bool, bool>(false, false);
+ connection = null;
+ return tuple;
+ }
+ }
+ else
+ {
+ tuple = new Tuple<bool, bool>(false, false);
+ connection = null;
+ return tuple;
+ }
+ }
+ tuple1 = (!await ConnectionHelper.HasLogin(connection) ? new Tuple<bool, bool>(true, false) : new Tuple<bool, bool>(true, true));
+ tuple = tuple1;
+ connection = null;
+ return tuple;
+ }
+
+ internal static async Task<bool> TryConnect(string connectionString, int retryCount = 1)
+ {
+ bool flag1 = await Task.Run<bool>(() => {
+ bool flag;
+ List<Exception> exceptions = new List<Exception>();
+ int num = 0;
+ Label1:
+ while (num < retryCount)
+ {
+ try
+ {
+ using (SqlConnection sqlConnection = new SqlConnection(string.Concat(connectionString, "Connection Timeout=5")))
+ {
+ sqlConnection.Open();
+ }
+ flag = true;
+ }
+ catch (Exception exception)
+ {
+ exceptions.Add(exception);
+ goto Label0;
+ }
+ return flag;
+ }
+ return exceptions.Count == 0;
+ Label0:
+ num++;
+ goto Label1;
+ });
+ return flag1;
+ }
+
+ private static async Task<bool> UserExists()
+ {
+ return await ConnectionHelper.Get("Data/UserExists", true) == null;
+ }
+
+ public async Task<string> VerifyConnection()
+ {
+ string str;
+ try
+ {
+ if (!await ConnectionHelper.TryConnect(Gestor.Application.Helpers.Connection.GetConnection(false), 1))
+ {
+ string str1 = await ConnectionHelper.DatabaseTest();
+ if (str1 == null)
+ {
+ string str2 = string.Concat(Gestor.Application.Helpers.Connection.ConnectionAddress.get_Catalog(), ".cfg");
+ string str3 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Data_", str2);
+ string str4 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Files_", str2);
+ string str5 = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "Sign_", str2);
+ if (File.Exists(str3))
+ {
+ File.Delete(str3);
+ }
+ if (File.Exists(str4))
+ {
+ File.Delete(str4);
+ }
+ if (File.Exists(str5))
+ {
+ File.Delete(str5);
+ }
+ string str6 = await ConnectionHelper.CheckDatabase();
+ await Task.Delay(2000);
+ str = str6;
+ }
+ else
+ {
+ str = str1;
+ }
+ }
+ else
+ {
+ str = null;
+ }
+ }
+ catch (Exception exception)
+ {
+ str = "ERRO AO CONECTAR NO BANCO DE DADOS DA CORRETORA";
+ }
+ return str;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/CustomLinq.cs b/Codemerx/Gestor.Application/Helpers/CustomLinq.cs new file mode 100644 index 0000000..2900b2e --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/CustomLinq.cs @@ -0,0 +1,421 @@ +using Gestor.Common.Validation;
+using Gestor.Model.Domain.Relatorios;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+ public static class CustomLinq
+ {
+ public static List<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>((T x) => {
+ Func<FiltroPersonalizado, bool> func8 = null;
+ Func<FiltroPersonalizado, bool> func9 = null;
+ Func<FiltroPersonalizado, bool> func10 = null;
+ Func<FiltroPersonalizado, bool> func11 = null;
+ Func<FiltroPersonalizado, bool> func12 = null;
+ Func<FiltroPersonalizado, bool> func13 = null;
+ Func<FiltroPersonalizado, bool> func14 = null;
+ List<FiltroPersonalizado> filtroPersonalizados = property;
+ Func<FiltroPersonalizado, string> u003cu003e9_21 = CustomLinq.u003cu003ec__2<T>.u003cu003e9__2_1;
+ if (u003cu003e9_21 == null)
+ {
+ u003cu003e9_21 = (FiltroPersonalizado p) => p.get_Propriedade();
+ CustomLinq.u003cu003ec__2<T>.u003cu003e9__2_1 = u003cu003e9_21;
+ }
+ return filtroPersonalizados.GroupBy<FiltroPersonalizado, string>(u003cu003e9_21).ToList<IGrouping<string, FiltroPersonalizado>>().All<IGrouping<string, FiltroPersonalizado>>((IGrouping<string, FiltroPersonalizado> p) => {
+ Func<FiltroPersonalizado, bool> func;
+ IGrouping<string, FiltroPersonalizado> strs = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_23 = CustomLinq.u003cu003ec__2<T>.u003cu003e9__2_3;
+ if (u003cu003e9_23 == null)
+ {
+ u003cu003e9_23 = (FiltroPersonalizado s) => s.get_SemValor();
+ CustomLinq.u003cu003ec__2<T>.u003cu003e9__2_3 = u003cu003e9_23;
+ }
+ if (strs.Any<FiltroPersonalizado>(u003cu003e9_23))
+ {
+ IGrouping<string, FiltroPersonalizado> strs1 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_4 = func8;
+ if (u003cu003e9_4 == null)
+ {
+ Func<FiltroPersonalizado, bool> func1 = (FiltroPersonalizado v) => {
+ bool value;
+ string str;
+ PropertyInfo propertyInfo1 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo1 != null ? propertyInfo1.GetValue(x) : false);
+ if (!value)
+ {
+ return true;
+ }
+ PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade());
+ str = (propertyInfo != null ? propertyInfo.GetValue(x).ToString() : null);
+ return string.IsNullOrWhiteSpace(str);
+ };
+ func = func1;
+ func8 = func1;
+ u003cu003e9_4 = func;
+ }
+ return strs1.All<FiltroPersonalizado>(u003cu003e9_4);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(DateTime))
+ {
+ IGrouping<string, FiltroPersonalizado> strs2 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_5 = func9;
+ if (u003cu003e9_5 == null)
+ {
+ Func<FiltroPersonalizado, bool> func2 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo2 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo2 != null ? propertyInfo2.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return (DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != DateTime.Parse(v.get_ValorIncial());
+ };
+ func = func2;
+ func9 = func2;
+ u003cu003e9_5 = func;
+ }
+ return strs2.All<FiltroPersonalizado>(u003cu003e9_5);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(long))
+ {
+ IGrouping<string, FiltroPersonalizado> strs3 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_6 = func10;
+ if (u003cu003e9_6 == null)
+ {
+ Func<FiltroPersonalizado, bool> func3 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo3 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo3 != null ? propertyInfo3.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != long.Parse(v.get_ValorIncial());
+ };
+ func = func3;
+ func10 = func3;
+ u003cu003e9_6 = func;
+ }
+ return strs3.All<FiltroPersonalizado>(u003cu003e9_6);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(int))
+ {
+ IGrouping<string, FiltroPersonalizado> strs4 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_7 = func11;
+ if (u003cu003e9_7 == null)
+ {
+ Func<FiltroPersonalizado, bool> func4 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo4 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo4 != null ? propertyInfo4.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != int.Parse(v.get_ValorIncial());
+ };
+ func = func4;
+ func11 = func4;
+ u003cu003e9_7 = func;
+ }
+ return strs4.All<FiltroPersonalizado>(u003cu003e9_7);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(decimal))
+ {
+ IGrouping<string, FiltroPersonalizado> strs5 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_8 = func12;
+ if (u003cu003e9_8 == null)
+ {
+ Func<FiltroPersonalizado, bool> func5 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo5 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo5 != null ? propertyInfo5.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return (decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) != decimal.Parse(v.get_ValorIncial());
+ };
+ func = func5;
+ func12 = func5;
+ u003cu003e9_8 = func;
+ }
+ return strs5.All<FiltroPersonalizado>(u003cu003e9_8);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() != typeof(Enum))
+ {
+ IGrouping<string, FiltroPersonalizado> strs6 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_10 = func14;
+ if (u003cu003e9_10 == null)
+ {
+ Func<FiltroPersonalizado, bool> func6 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo6 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo6 != null ? propertyInfo6.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return !ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim()));
+ };
+ func = func6;
+ func14 = func6;
+ u003cu003e9_10 = func;
+ }
+ return strs6.All<FiltroPersonalizado>(u003cu003e9_10);
+ }
+ IGrouping<string, FiltroPersonalizado> strs7 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_9 = func13;
+ if (u003cu003e9_9 == null)
+ {
+ Func<FiltroPersonalizado, bool> func7 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo7 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo7 != null ? propertyInfo7.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return !ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x)).ToLower().Contains(v.get_ValorIncial().ToLower());
+ };
+ func = func7;
+ func13 = func7;
+ u003cu003e9_9 = func;
+ }
+ return strs7.All<FiltroPersonalizado>(u003cu003e9_9);
+ });
+ }).ToList<T>();
+ }
+
+ public static List<T> CustomWhere<T>(this List<T> list, string propertyName, string query)
+ where T : class
+ {
+ PropertyInfo property = typeof(T).GetProperty(propertyName);
+ return (
+ from in list
+ where property.GetValue(x).ToString().ToLower().Contains(query.ToLower())
+ select ).ToList<T>();
+ }
+
+ 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>((T x) => {
+ Func<FiltroPersonalizado, bool> func7 = null;
+ Func<FiltroPersonalizado, bool> func8 = null;
+ Func<FiltroPersonalizado, bool> func9 = null;
+ Func<FiltroPersonalizado, bool> func10 = null;
+ Func<FiltroPersonalizado, bool> func11 = null;
+ Func<FiltroPersonalizado, bool> func12 = null;
+ Func<FiltroPersonalizado, bool> func13 = null;
+ List<FiltroPersonalizado> filtroPersonalizados = property;
+ Func<FiltroPersonalizado, string> u003cu003e9_11 = CustomLinq.u003cu003ec__1<T>.u003cu003e9__1_1;
+ if (u003cu003e9_11 == null)
+ {
+ u003cu003e9_11 = (FiltroPersonalizado p) => p.get_Propriedade();
+ CustomLinq.u003cu003ec__1<T>.u003cu003e9__1_1 = u003cu003e9_11;
+ }
+ return filtroPersonalizados.GroupBy<FiltroPersonalizado, string>(u003cu003e9_11).ToList<IGrouping<string, FiltroPersonalizado>>().All<IGrouping<string, FiltroPersonalizado>>((IGrouping<string, FiltroPersonalizado> p) => {
+ Func<FiltroPersonalizado, bool> func;
+ IGrouping<string, FiltroPersonalizado> strs = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_13 = CustomLinq.u003cu003ec__1<T>.u003cu003e9__1_3;
+ if (u003cu003e9_13 == null)
+ {
+ u003cu003e9_13 = (FiltroPersonalizado s) => s.get_SemValor();
+ CustomLinq.u003cu003ec__1<T>.u003cu003e9__1_3 = u003cu003e9_13;
+ }
+ if (strs.Any<FiltroPersonalizado>(u003cu003e9_13))
+ {
+ IGrouping<string, FiltroPersonalizado> strs1 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_4 = func7;
+ if (u003cu003e9_4 == null)
+ {
+ Func<FiltroPersonalizado, bool> func1 = (FiltroPersonalizado v) => {
+ bool value;
+ string str;
+ string str1;
+ PropertyInfo propertyInfo1 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo1 != null ? propertyInfo1.GetValue(x) : false);
+ if (value)
+ {
+ PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade());
+ str = (propertyInfo != null ? propertyInfo.GetValue(x).ToString() : null);
+ if (!string.IsNullOrWhiteSpace(str))
+ {
+ PropertyInfo property1 = typeof(T).GetProperty(v.get_Propriedade());
+ str1 = (property1 != null ? property1.GetValue(x).ToString() : null);
+ return string.IsNullOrEmpty(str1);
+ }
+ }
+ return true;
+ };
+ func = func1;
+ func7 = func1;
+ u003cu003e9_4 = func;
+ }
+ return strs1.Any<FiltroPersonalizado>(u003cu003e9_4);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(DateTime))
+ {
+ IGrouping<string, FiltroPersonalizado> strs2 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_5 = func8;
+ if (u003cu003e9_5 == null)
+ {
+ Func<FiltroPersonalizado, bool> func2 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo2 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo2 != null ? propertyInfo2.GetValue(x) : false);
+ if (!value || !((DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) >= DateTime.Parse(v.get_ValorIncial())))
+ {
+ return false;
+ }
+ DateTime dateTime = (DateTime)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x);
+ DateTime dateTime1 = DateTime.Parse(v.get_ValorFinal());
+ dateTime1 = dateTime1.AddDays(1);
+ return dateTime <= dateTime1.AddSeconds(-1);
+ };
+ func = func2;
+ func8 = func2;
+ u003cu003e9_5 = func;
+ }
+ return strs2.Any<FiltroPersonalizado>(u003cu003e9_5);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(long))
+ {
+ IGrouping<string, FiltroPersonalizado> strs3 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_6 = func9;
+ if (u003cu003e9_6 == null)
+ {
+ Func<FiltroPersonalizado, bool> func3 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo3 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo3 != null ? propertyInfo3.GetValue(x) : false);
+ if (!value || (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) < long.Parse(v.get_ValorIncial()))
+ {
+ return false;
+ }
+ return (long)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= long.Parse(v.get_ValorFinal());
+ };
+ func = func3;
+ func9 = func3;
+ u003cu003e9_6 = func;
+ }
+ return strs3.Any<FiltroPersonalizado>(u003cu003e9_6);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(int))
+ {
+ IGrouping<string, FiltroPersonalizado> strs4 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_7 = func10;
+ if (u003cu003e9_7 == null)
+ {
+ Func<FiltroPersonalizado, bool> func4 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo4 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo4 != null ? propertyInfo4.GetValue(x) : false);
+ if (!value || (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) < int.Parse(v.get_ValorIncial()))
+ {
+ return false;
+ }
+ return (int)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= int.Parse(v.get_ValorFinal());
+ };
+ func = func4;
+ func10 = func4;
+ u003cu003e9_7 = func;
+ }
+ return strs4.Any<FiltroPersonalizado>(u003cu003e9_7);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() == typeof(decimal))
+ {
+ IGrouping<string, FiltroPersonalizado> strs5 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_8 = func11;
+ if (u003cu003e9_8 == null)
+ {
+ Func<FiltroPersonalizado, bool> func5 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo5 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo5 != null ? propertyInfo5.GetValue(x) : false);
+ if (!value || !((decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) >= decimal.Parse(v.get_ValorIncial())))
+ {
+ return false;
+ }
+ return (decimal)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x) <= decimal.Parse(v.get_ValorFinal());
+ };
+ func = func5;
+ func11 = func5;
+ u003cu003e9_8 = func;
+ }
+ return strs5.Any<FiltroPersonalizado>(u003cu003e9_8);
+ }
+ if (p.First<FiltroPersonalizado>().get_Tipo() != typeof(Enum))
+ {
+ IGrouping<string, FiltroPersonalizado> strs6 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_10 = func13;
+ if (u003cu003e9_10 == null)
+ {
+ Func<FiltroPersonalizado, bool> cSu0024u003cu003e8_locals1 = (FiltroPersonalizado v) => {
+ bool value;
+ bool flag;
+ if (!buscaIgual)
+ {
+ PropertyInfo propertyInfo6 = typeof(T).GetProperty(v.get_Propriedade());
+ flag = (propertyInfo6 != null ? propertyInfo6.GetValue(x) : false);
+ if (!flag)
+ {
+ return false;
+ }
+ return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Contains(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim()));
+ }
+ PropertyInfo propertyInfo = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo != null ? propertyInfo.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return ValidationHelper.AlphanumericAndSpace(typeof(T).GetProperty(v.get_Propriedade()).GetValue(x).ToString().ToLower().Trim()).Equals(ValidationHelper.AlphanumericAndSpace(v.get_ValorIncial().ToLower().Trim()));
+ };
+ func = cSu0024u003cu003e8_locals1;
+ func13 = cSu0024u003cu003e8_locals1;
+ u003cu003e9_10 = func;
+ }
+ return strs6.Any<FiltroPersonalizado>(u003cu003e9_10);
+ }
+ IGrouping<string, FiltroPersonalizado> strs7 = p;
+ Func<FiltroPersonalizado, bool> u003cu003e9_9 = func12;
+ if (u003cu003e9_9 == null)
+ {
+ Func<FiltroPersonalizado, bool> func6 = (FiltroPersonalizado v) => {
+ bool value;
+ PropertyInfo propertyInfo7 = typeof(T).GetProperty(v.get_Propriedade());
+ value = (propertyInfo7 != null ? propertyInfo7.GetValue(x) : false);
+ if (!value)
+ {
+ return false;
+ }
+ return ValidationHelper.GetDescription((Enum)typeof(T).GetProperty(v.get_Propriedade()).GetValue(x)).ToLower().Equals(v.get_ValorIncial().ToLower());
+ };
+ func = func6;
+ func12 = func6;
+ u003cu003e9_9 = func;
+ }
+ return strs7.Any<FiltroPersonalizado>(u003cu003e9_9);
+ });
+ }).ToList<T>();
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs b/Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs new file mode 100644 index 0000000..acffb1d --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/DataGridExtensions.cs @@ -0,0 +1,83 @@ +using Gestor.Common.Validation;
+using Gestor.Model.Common;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Media;
+
+namespace Gestor.Application.Helpers
+{
+ public static class DataGridExtensions
+ {
+ public static void EsconderToggles(this DataGrid grid, TipoTela tela, TipoToggle toggles)
+ {
+ try
+ {
+ foreach (object item in grid.ItemContainerGenerator.Items)
+ {
+ grid.ScrollIntoView(item, grid.Columns[0]);
+ grid.UpdateLayout();
+ DataGridRow dataGridRow = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item);
+ if (dataGridRow == null)
+ {
+ continue;
+ }
+ grid.ScrollIntoView(dataGridRow, grid.Columns[4]);
+ grid.UpdateLayout();
+ DataGridCellsPresenter visualChild = DataGridExtensions.GetVisualChild<DataGridCellsPresenter>(dataGridRow);
+ DataGridCell dataGridCell = (DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(0);
+ if (dataGridCell == null || !dataGridCell.ToString().Contains(ValidationHelper.GetDescription(tela)))
+ {
+ continue;
+ }
+ if (toggles.HasFlag(TipoToggle.Consultar))
+ {
+ ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(1)).Visibility = Visibility.Hidden;
+ }
+ if (toggles.HasFlag(TipoToggle.Incluir))
+ {
+ ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(2)).Visibility = Visibility.Hidden;
+ }
+ if (toggles.HasFlag(TipoToggle.Alterar))
+ {
+ ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(3)).Visibility = Visibility.Hidden;
+ }
+ if (toggles.HasFlag(TipoToggle.Excluir))
+ {
+ ((DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(4)).Visibility = Visibility.Hidden;
+ }
+ return;
+ }
+ }
+ catch (Exception exception)
+ {
+ }
+ }
+
+ public static T GetVisualChild<T>(Visual parent)
+ where T : Visual
+ {
+ T t = default(T);
+ int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
+ for (int i = 0; i < childrenCount; i++)
+ {
+ Visual child = (Visual)VisualTreeHelper.GetChild(parent, i);
+ T visualChild = (T)(child as T);
+ if (visualChild == null)
+ {
+ visualChild = DataGridExtensions.GetVisualChild<T>(child);
+ }
+ t = visualChild;
+ if (t != null)
+ {
+ break;
+ }
+ }
+ return t;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Erro.cs b/Codemerx/Gestor.Application/Helpers/Erro.cs new file mode 100644 index 0000000..52f70f5 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Erro.cs @@ -0,0 +1,24 @@ +using Gestor.Application.Views.Generic;
+using Gestor.Model.API;
+using System;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Threading;
+
+namespace Gestor.Application.Helpers
+{
+ public static class Erro
+ {
+ public static void RegistrarErro(LogError log, bool abrirTela = true)
+ {
+ string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Gestor.Exceptions.log");
+ File.AppendAllText(str, string.Format("CORRETORA: {1} - {2}{0} USUÁRIO LOGADO: {3}{0} VERSÃO: {4}{0} DATA: {5}{0} ERRO: {6} - {7}{0} HRESULT: {8}{0} HELPLINK: {9}{0} MESSAGE: {10}{0} SOURCE: {11}{0} STACKTRACE: {12}{0} MAQUINA: {13}{0} USUARIO MAQUINA: {14}{0} LINHA: {15}{0} OBJETO: {16}{0} {0}", new object[] { Environment.NewLine, log.get_IdFornecedor(), log.get_Fornecedor(), log.get_UsuarioLogado(), log.get_Versao(), log.get_Data(), log.get_IdErro(), log.get_Erro(), log.get_HResult(), log.get_HelpLink(), log.get_Message(), log.get_Source(), log.get_StackTrace(), log.get_Maquina(), log.get_UsuarioMaquina(), log.get_Linha(), log.get_Objeto() }));
+ if (!abrirTela)
+ {
+ return;
+ }
+ System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => (new ErrorWindow(log.get_IdErro(), false)).ShowDialog()));
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Funcoes.cs b/Codemerx/Gestor.Application/Helpers/Funcoes.cs new file mode 100644 index 0000000..786f217 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Funcoes.cs @@ -0,0 +1,6825 @@ +using Agger.Registro;
+using ClosedXML.Excel;
+using CsQuery.ExtensionMethods;
+using Gestor.Application;
+using Gestor.Application.Actions;
+using Gestor.Application.Properties;
+using Gestor.Application.Servicos;
+using Gestor.Application.Servicos.Configuracoes;
+using Gestor.Application.Servicos.Ferramentas;
+using Gestor.Application.Servicos.Generic;
+using Gestor.Application.Servicos.Seguros;
+using Gestor.Application.Servicos.Seguros.Itens;
+using Gestor.Application.ViewModels.Generic;
+using Gestor.Application.Views.Generic;
+using Gestor.Common.Validation;
+using Gestor.Infrastructure.Repository.Interface;
+using Gestor.Infrastructure.UnitOfWork.Generic;
+using Gestor.Infrastructure.UnitOfWork.Logic;
+using Gestor.Model.API;
+using Gestor.Model.Attributes;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Card;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Configuracoes;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.MalaDireta;
+using Gestor.Model.Domain.Relatorios;
+using Gestor.Model.Domain.Seguros;
+using HtmlAgilityPack;
+using MaterialDesignThemes.Wpf;
+using Newtonsoft.Json;
+using OfxSharpLib;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Web;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Xceed.Wpf.AvalonDock.Controls;
+
+namespace Gestor.Application.Helpers
+{
+ public static class Funcoes
+ {
+ public static System.Diagnostics.Stopwatch Stopwatch;
+
+ public static DateTime? StartTime;
+
+ public static string AdicionarLog(string html)
+ {
+ string innerHtml;
+ HtmlDocument htmlDocument = new HtmlDocument();
+ htmlDocument.LoadHtml(html);
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ using (IEnumerator<HtmlNode> enumerator = htmlDocument.get_DocumentNode().get_ChildNodes().GetEnumerator())
+ {
+ while (enumerator.MoveNext())
+ {
+ HtmlNode current = enumerator.Current;
+ if (current.get_Name() != "body")
+ {
+ continue;
+ }
+ current.set_InnerHtml(string.Format("<p>{0} ID-{1} {2:g} </p>{3}<hr>", new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, current.get_InnerHtml() }));
+ innerHtml = current.get_InnerHtml();
+ return innerHtml;
+ }
+ return "";
+ }
+ return innerHtml;
+ }
+
+ public static async Task<string> AtualizarAssistencia(Assistance assistance, string id)
+ {
+ string str;
+ if (await Gestor.Application.Helpers.Connection.Put<string>(string.Concat("Assistance/", id), assistance) == null)
+ {
+ str = id;
+ }
+ else
+ {
+ str = null;
+ }
+ return str;
+ }
+
+ public static async Task<string> AtualizarCartao(Gestor.Model.Domain.Card.Card card, string id)
+ {
+ string str;
+ if (await Gestor.Application.Helpers.Connection.Put<string>(string.Concat("Card/", id), card) == null)
+ {
+ str = id;
+ }
+ else
+ {
+ str = null;
+ }
+ return str;
+ }
+
+ public static async Task<string> Atualizarlogo(Logo logo, string id)
+ {
+ string str = await Gestor.Application.Helpers.Connection.Put<string>(string.Concat("Card/Logo/", id), logo);
+ return str;
+ }
+
+ public static async Task<string> AtualizarSeguradora(AssistenciaCia cia, string id)
+ {
+ string str = await Gestor.Application.Helpers.Connection.Put<string>(string.Concat("Assistance/Seguradora/", id), cia);
+ return str;
+ }
+
+ public static async Task<Parcela> BaixarComissao(Parcela parcela, List<Parcela> parcelas, List<VendedorParcela> repasses, [DecimalConstant(0, 0, 0, 0, 2)] decimal tolerancia = default(decimal), bool comissaoAuto = false)
+ {
+ Parcela parcela1;
+ long? nullable1;
+ Parcela parcela2;
+ decimal num1;
+ decimal num2;
+ bool flag;
+ object nome;
+ object apolice;
+ long? nullable2;
+ bool flag1;
+ object empty;
+ string str;
+ string proposta;
+ Funcoes.u003cu003ec__DisplayClass2_0 variable;
+ Parcela parcela3 = parcela;
+ ParcelaServico parcelaServico = new ParcelaServico();
+ Parcela parcela4 = parcela3;
+ num1 = (!(parcela3.get_ValorComDesconto() == decimal.Zero) || !(Math.Abs(parcela3.get_ValorComDesconto()) < Math.Abs(parcela3.get_ValorComissao())) ? parcela3.get_ValorComDesconto() : parcela3.get_ValorComissao());
+ parcela4.set_ValorComDesconto(num1);
+ List<VendedorParcela> vendedorParcelas = repasses;
+ var groupings =
+ from x in vendedorParcelas
+ group x by new { Id = x.get_Parcela().get_Id(), vendedor = x.get_Vendedor().get_Id(), tipovendedor = x.get_TipoVendedor().get_Id() };
+ BaseDialogViewModel baseDialogViewModel = new BaseDialogViewModel();
+ if (!groupings.Any((g) => g.Count<VendedorParcela>() > 1))
+ {
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ if (parcela3.get_SubTipo() != 1 || parcela3.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1)
+ {
+ List<VendedorParcela> vendedorParcelas1 = repasses.Where<VendedorParcela>((VendedorParcela x) => {
+ FormaRepasse? nullable;
+ FormaRepasse? forma;
+ if (x.get_Parcela().get_Id() != parcela3.get_Id() || x.get_DataPagamento().HasValue)
+ {
+ return false;
+ }
+ if (x == null)
+ {
+ return false;
+ }
+ Repasse repasse = x.get_Repasse();
+ if (repasse != null)
+ {
+ forma = repasse.get_Forma();
+ }
+ else
+ {
+ nullable = null;
+ forma = nullable;
+ }
+ nullable = forma;
+ return nullable.GetValueOrDefault() == 1;
+ }).ToList<VendedorParcela>();
+ vendedorParcelas1.ForEach((VendedorParcela x) => {
+ x.set_DataPrePagamento(parcela3.get_DataRecebimento());
+ x.set_ValorRepasse(new decimal?(Funcoes.CalculaRepasse(x.get_Repasse(), parcela3, false)));
+ });
+ parcela2 = await parcelaServico.Save(parcela3, parcelas, vendedorParcelas1, false);
+ parcela3 = parcela2;
+ if (!parcelaServico.Sucesso)
+ {
+ await Funcoes.MostrarErro(24);
+ parcela1 = parcela3;
+ variable = null;
+ parcelaServico = null;
+ baseDialogViewModel = null;
+ return parcela1;
+ }
+ }
+ else
+ {
+ num2 = (parcela3.get_Documento().get_AdicionalComiss() ? parcela3.get_Documento().get_PremioLiquido() + parcela3.get_Documento().get_PremioAdicional() : parcela3.get_Documento().get_PremioLiquido());
+ decimal num3 = num2;
+ decimal comissao = (num3 * parcela3.get_Documento().get_Comissao()) * new decimal(1, 0, 0, false, 2);
+ List<Parcela> parcelas1 = parcelas;
+ IEnumerable<Parcela> parcelas2 = parcelas1.Where<Parcela>((Parcela x) => {
+ if (x.get_SubTipo() != 1)
+ {
+ return false;
+ }
+ return x.get_DataRecebimento().HasValue;
+ });
+ decimal num4 = parcelas2.Sum<Parcela>((Parcela x) => x.get_ValorComissao());
+ decimal num5 = Math.Abs(comissao) - Math.Abs(num4);
+ flag = (num5 <= tolerancia ? true : num5 < new decimal(1, 0, 0, false, 2));
+ bool flag2 = flag;
+ TipoRecebimento? tipoRecebimento = parcela3.get_Documento().get_TipoRecebimento();
+ bool flag3 = tipoRecebimento.GetValueOrDefault() == 1 & flag2;
+ bool flag4 = true;
+ if (flag3)
+ {
+ List<ConfiguracaoSistema> configuracoes = Recursos.Configuracoes;
+ if (configuracoes.Any<ConfiguracaoSistema>((ConfiguracaoSistema c) => c.get_Configuracao() == 54))
+ {
+ Parcela parcela5 = parcela3;
+ if (parcela5 != null)
+ {
+ Documento documento = parcela5.get_Documento();
+ if (documento != null)
+ {
+ Controle controle = documento.get_Controle();
+ if (controle != null)
+ {
+ Cliente cliente = controle.get_Cliente();
+ if (cliente != null)
+ {
+ nome = cliente.get_Nome();
+ }
+ else
+ {
+ nome = null;
+ }
+ }
+ else
+ {
+ nome = null;
+ }
+ }
+ else
+ {
+ nome = null;
+ }
+ }
+ else
+ {
+ nome = null;
+ }
+ if (nome == null)
+ {
+ nome = string.Empty;
+ }
+ string str1 = (string)nome;
+ if (string.IsNullOrEmpty(str1))
+ {
+ Documento documento1 = parcela3.get_Documento();
+ if (documento1 != null)
+ {
+ Controle controle1 = documento1.get_Controle();
+ if (controle1 != null)
+ {
+ Cliente cliente1 = controle1.get_Cliente();
+ if (cliente1 != null)
+ {
+ nullable2 = new long?(cliente1.get_Id());
+ }
+ else
+ {
+ nullable1 = null;
+ nullable2 = nullable1;
+ }
+ }
+ else
+ {
+ nullable1 = null;
+ nullable2 = nullable1;
+ }
+ long? nullable3 = nullable2;
+ long num6 = (long)0;
+ flag1 = nullable3.GetValueOrDefault() > num6 & nullable3.HasValue;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (flag1)
+ {
+ Cliente cliente2 = await (new ClienteServico()).BuscarClienteAsync(parcela3.get_Documento().get_Controle().get_Cliente().get_Id());
+ if (cliente2 != null)
+ {
+ empty = cliente2.get_Nome();
+ }
+ else
+ {
+ empty = null;
+ }
+ if (empty == null)
+ {
+ empty = string.Empty;
+ }
+ str1 = (string)empty;
+ }
+ }
+ if (!string.IsNullOrEmpty(str1))
+ {
+ str1 = string.Concat(", DO CLIENTE ", str1);
+ }
+ Parcela parcela6 = parcela3;
+ if (parcela6 != null)
+ {
+ Documento documento2 = parcela6.get_Documento();
+ if (documento2 != null)
+ {
+ apolice = documento2.get_Apolice();
+ }
+ else
+ {
+ apolice = null;
+ }
+ }
+ else
+ {
+ apolice = null;
+ }
+ if (apolice == null)
+ {
+ apolice = string.Empty;
+ }
+ string str2 = (string)apolice;
+ if (!string.IsNullOrEmpty(str2))
+ {
+ str2 = string.Concat(" - APÓLICE ", str2);
+ }
+ if (parcela3.get_Documento().get_NumeroParcelas() != parcela3.get_NumeroParcela())
+ {
+ bool flag5 = await baseDialogViewModel.ShowMessage(string.Format("AINDA RESTA {0:c}{1}{2} QUE NÃO SERÁ REPASSADO, CONTINUAR A BAIXA POR ESGOTAMENTO?", num5, str1, str2), "SIM, BAIXAR POR ESGOMENTO", "NÃO", false);
+ bool flag6 = flag5;
+ flag3 = flag5;
+ flag4 = flag6;
+ }
+ }
+ }
+ List<VendedorParcela> vendedorParcelas2 = repasses.Where<VendedorParcela>((VendedorParcela x) => {
+ bool valueOrDefault;
+ if (x.get_Parcela().get_Id() == this.parcela.get_Id())
+ {
+ Repasse repasse = x.get_Repasse();
+ valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false);
+ if (valueOrDefault)
+ {
+ return !x.get_DataPagamento().HasValue;
+ }
+ }
+ return false;
+ }).ToList<VendedorParcela>();
+ List<VendedorParcela> vendedorParcelas3 = new List<VendedorParcela>();
+ Parcela parcela7 = parcelas.FirstOrDefault<Parcela>((Parcela x) => {
+ if (x.get_SubTipo() != 1)
+ {
+ return false;
+ }
+ return x.get_NumeroParcela() == this.parcela.get_NumeroParcela() + 1;
+ });
+ Parcela parcela8 = parcela3;
+ List<VendedorParcela> vendedorParcelas4 = vendedorParcelas2;
+ ExtensionMethods.ForEach(
+ from g in vendedorParcelas4
+ group g by new { Id = g.get_Parcela().get_Id(), vendedor = g.get_Vendedor().get_Id(), tipovendedor = g.get_TipoVendedor().get_Id() }, (x) => {
+ if (x.First<VendedorParcela>().get_CoCorretagem())
+ {
+ return;
+ }
+ decimal valueOrDefault = x.First<VendedorParcela>().get_ValorRepasse().GetValueOrDefault();
+ decimal num = Funcoes.CalculaPagamento(x.First<VendedorParcela>(), parcela8, comissao);
+ x.First<VendedorParcela>().set_ValorRepasse(new decimal?((Math.Abs(valueOrDefault) > Math.Abs(num) ? num : valueOrDefault)));
+ x.First<VendedorParcela>().set_DataPrePagamento(parcela8.get_DataRecebimento());
+ if (flag4 && (Math.Abs(comissao) - Math.Abs(num4)) <= Math.Abs(tolerancia) || parcela7 == null)
+ {
+ return;
+ }
+ VendedorParcela vendedorParcela = new VendedorParcela();
+ vendedorParcela.set_Repasse(x.First<VendedorParcela>().get_Repasse());
+ vendedorParcela.set_Parcela(parcela7);
+ vendedorParcela.set_Documento(parcela8.get_Documento());
+ vendedorParcela.set_ValorRepasse(new decimal?(valueOrDefault - num));
+ vendedorParcela.set_Vendedor(x.First<VendedorParcela>().get_Vendedor());
+ vendedorParcela.set_ValorTotal(x.First<VendedorParcela>().get_ValorTotal());
+ vendedorParcela.set_PorcentagemRepasse(x.First<VendedorParcela>().get_PorcentagemRepasse());
+ vendedorParcela.set_TipoVendedor(x.First<VendedorParcela>().get_TipoVendedor());
+ vendedorParcela.set_CoCorretagem(x.First<VendedorParcela>().get_CoCorretagem());
+ vendedorParcelas3.Add(vendedorParcela);
+ });
+ if (vendedorParcelas3.Count > 0)
+ {
+ vendedorParcelas2.AddRange(vendedorParcelas3);
+ }
+ if (await parcelaServico.SaveRange(vendedorParcelas2))
+ {
+ parcela2 = await parcelaServico.Save(parcela3, parcelas, null, false);
+ parcela3 = parcela2;
+ if (parcelaServico.Sucesso)
+ {
+ if (flag3)
+ {
+ List<Parcela> parcelas3 = parcelas;
+ List<Parcela> parcelas4 = parcelas3.Where<Parcela>((Parcela x) => {
+ if (x.get_DataRecebimento().HasValue)
+ {
+ return false;
+ }
+ return x.get_SubTipo() == 1;
+ }).ToList<Parcela>();
+ List<VendedorParcela> vendedorParcelas5 = new List<VendedorParcela>();
+ parcelas4.ForEach((Parcela x) => {
+ x.set_Documento(parcela3.get_Documento());
+ x.set_DataRecebimento(parcela3.get_DataRecebimento());
+ x.set_DataCredito(parcela3.get_DataRecebimento());
+ x.set_ValorRealizado(decimal.Zero);
+ x.set_ValorComissao(decimal.Zero);
+ x.set_ValorComDesconto(decimal.Zero);
+ x.set_Irr(decimal.Zero);
+ x.set_Iss(decimal.Zero);
+ List<VendedorParcela> list = repasses.Where<VendedorParcela>((VendedorParcela p) => {
+ bool valueOrDefault;
+ if (p.get_Parcela().get_Id() == x.get_Id())
+ {
+ Repasse repasse = p.get_Repasse();
+ valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false);
+ if (valueOrDefault)
+ {
+ Repasse repasse1 = p.get_Repasse();
+ if (repasse1 == null)
+ {
+ return true;
+ }
+ return repasse1.get_Tipo().GetValueOrDefault() != 3;
+ }
+ }
+ return false;
+ }).ToList<VendedorParcela>();
+ list.ForEach((VendedorParcela p) => {
+ decimal? nullable;
+ p.set_Parcela(x);
+ p.set_Documento(parcela3.get_Documento());
+ p.set_DataPrePagamento(new DateTime?(networkTime));
+ VendedorParcela vendedorParcela = p;
+ decimal? valorRepasse = p.get_ValorRepasse();
+ decimal cSu0024u003cu003e8_locals1 = tolerancia;
+ if ((valorRepasse.GetValueOrDefault() > cSu0024u003cu003e8_locals1) & valorRepasse.HasValue)
+ {
+ cSu0024u003cu003e8_locals1 = new decimal();
+ nullable = new decimal?(cSu0024u003cu003e8_locals1);
+ }
+ else
+ {
+ nullable = p.get_ValorRepasse();
+ }
+ vendedorParcela.set_ValorRepasse(nullable);
+ });
+ vendedorParcelas5.AddRange(list);
+ });
+ await parcelaServico.SaveRange(parcelas);
+ if (!parcelaServico.Sucesso)
+ {
+ await Funcoes.MostrarErro(24);
+ parcela1 = parcela3;
+ variable = null;
+ parcelaServico = null;
+ baseDialogViewModel = null;
+ return parcela1;
+ }
+ else if (await parcelaServico.SaveRange(vendedorParcelas5))
+ {
+ }
+ else
+ {
+ await Funcoes.MostrarErro(24);
+ parcela1 = parcela3;
+ variable = null;
+ parcelaServico = null;
+ baseDialogViewModel = null;
+ return parcela1;
+ }
+ }
+ }
+ else
+ {
+ await Funcoes.MostrarErro(24);
+ parcela1 = parcela3;
+ variable = null;
+ parcelaServico = null;
+ baseDialogViewModel = null;
+ return parcela1;
+ }
+ }
+ else
+ {
+ await Funcoes.MostrarErro(24);
+ parcela1 = parcela3;
+ variable = null;
+ parcelaServico = null;
+ baseDialogViewModel = null;
+ return parcela1;
+ }
+ }
+ if (!comissaoAuto)
+ {
+ Funcoes.RegistrarLogBaixa(parcela3.get_Documento().get_Id(), networkTime);
+ }
+ parcela1 = parcela3;
+ }
+ else
+ {
+ Documento documento3 = parcela3.get_Documento();
+ if (documento3 != null)
+ {
+ str = documento3.get_Apolice();
+ }
+ else
+ {
+ str = null;
+ }
+ if (string.IsNullOrWhiteSpace(str))
+ {
+ Documento documento4 = parcela3.get_Documento();
+ if (documento4 != null)
+ {
+ proposta = documento4.get_Apolice();
+ }
+ else
+ {
+ proposta = null;
+ }
+ }
+ else
+ {
+ Documento documento5 = parcela3.get_Documento();
+ if (documento5 != null)
+ {
+ proposta = documento5.get_Proposta();
+ }
+ else
+ {
+ proposta = null;
+ }
+ }
+ string str3 = proposta;
+ await baseDialogViewModel.ShowMessage(string.Format("HÁ VENDEDORES DUPLICADOS PARA A PARCELA {0} DO DOCUMENTO {1}, BAIXA DE COMISSÃO INTERROMPIDA.{2}REALIZE A CORREÇÃO DOS VENDEDORES E TENTE NOVAMENTE.", parcela3.get_NumeroParcela(), str3, Environment.NewLine), "OK", "", false);
+ parcela3.set_DataRecebimento(null);
+ parcela3.set_ValorComissao(decimal.Zero);
+ parcela3.set_ValorComDesconto(decimal.Zero);
+ parcela3.set_Irr(decimal.Zero);
+ parcela3.set_Iss(decimal.Zero);
+ parcela3.set_Outros(decimal.Zero);
+ parcela3.set_Desconto(decimal.Zero);
+ parcela1 = parcela3;
+ }
+ variable = null;
+ parcelaServico = null;
+ baseDialogViewModel = null;
+ return parcela1;
+ }
+
+ public static string BoolToString(this bool boolean)
+ {
+ if (!boolean)
+ {
+ return "0";
+ }
+ return "1";
+ }
+
+ public static void BringToFront(this string programName)
+ {
+ try
+ {
+ Process[] processesByName = Process.GetProcessesByName(programName);
+ if (processesByName.Length != 0)
+ {
+ IntPtr mainWindowHandle = processesByName[0].MainWindowHandle;
+ Funcoes.ShowWindow(mainWindowHandle, 5);
+ Funcoes.ShowWindow(mainWindowHandle, 9);
+ Funcoes.SetForegroundWindow(mainWindowHandle);
+ }
+ }
+ catch (Exception exception)
+ {
+ }
+ }
+
+ public static decimal CalculaPagamento(VendedorParcela pagamento, Parcela parcela, decimal comissaoPrevista)
+ {
+ TipoRepasse? tipo;
+ bool valueOrDefault;
+ bool flag;
+ bool valueOrDefault1;
+ bool flag1;
+ decimal num;
+ decimal num1 = pagamento.get_PorcentagemRepasse().GetValueOrDefault();
+ decimal valueOrDefault2 = pagamento.get_ValorRepasse().GetValueOrDefault();
+ decimal valorComDesconto = parcela.get_ValorComDesconto();
+ Repasse repasse = pagamento.get_Repasse();
+ if (repasse != null)
+ {
+ valueOrDefault = repasse.get_Incidencia().GetValueOrDefault() == 2;
+ }
+ else
+ {
+ valueOrDefault = false;
+ }
+ if (valueOrDefault)
+ {
+ decimal comissao = (parcela.get_Documento().get_Comissao() * parcela.get_Documento().get_PremioLiquido()) * new decimal(1, 0, 0, false, 2);
+ num = (parcela.get_ValorComissao() != decimal.Zero ? parcela.get_ValorComissao() / comissao : decimal.Zero);
+ valorComDesconto = parcela.get_Documento().get_PremioLiquido() * num;
+ }
+ Repasse repasse1 = pagamento.get_Repasse();
+ if (repasse1 != null)
+ {
+ tipo = repasse1.get_Tipo();
+ flag = tipo.GetValueOrDefault() != 1;
+ }
+ else
+ {
+ flag = true;
+ }
+ if (flag)
+ {
+ decimal? porcentagemRepasse = pagamento.get_PorcentagemRepasse();
+ num1 = (valorComDesconto * porcentagemRepasse.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2);
+ }
+ Repasse repasse2 = pagamento.get_Repasse();
+ if (repasse2 != null)
+ {
+ tipo = repasse2.get_Tipo();
+ valueOrDefault1 = tipo.GetValueOrDefault() == 1;
+ }
+ else
+ {
+ valueOrDefault1 = false;
+ }
+ if (valueOrDefault1)
+ {
+ Repasse repasse3 = pagamento.get_Repasse();
+ if (repasse3 != null)
+ {
+ flag1 = repasse3.get_Forma().GetValueOrDefault() == 1;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (flag1)
+ {
+ if (Recursos.Configuracoes.Any<ConfiguracaoSistema>((ConfiguracaoSistema x) => x.get_Configuracao() == 25))
+ {
+ num1 *= (comissaoPrevista == decimal.Zero ? decimal.One : parcela.get_ValorComissao() / comissaoPrevista);
+ }
+ }
+ }
+ if (Math.Abs(num1) <= Math.Abs(valueOrDefault2))
+ {
+ return num1;
+ }
+ return valueOrDefault2;
+ }
+
+ public static decimal CalculaRepasse(Repasse repasse, Parcela parcela, bool apolice = true)
+ {
+ decimal num;
+ decimal num1;
+ decimal num2;
+ decimal comissao;
+ decimal num3;
+ if (repasse == null)
+ {
+ return decimal.Zero;
+ }
+ NegocioCorretora? negocioCorretora = parcela.get_Documento().get_NegocioCorretora();
+ bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1;
+ if (!apolice || parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 || parcela.get_SubTipo() != 1)
+ {
+ decimal num4 = (parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela.get_ValorLiquidoFatura() : parcela.get_Valor());
+ if (repasse.get_Incidencia().GetValueOrDefault() == 2)
+ {
+ num3 = num4;
+ }
+ else
+ {
+ num3 = (parcela.get_ValorComDesconto() == decimal.Zero ? num4 : parcela.get_ValorComDesconto());
+ }
+ num1 = num3;
+ num2 = num1;
+ comissao = (parcela.get_ValorComDesconto() == decimal.Zero ? parcela.get_Comissao() * new decimal(1, 0, 0, false, 2) : decimal.One);
+ }
+ else
+ {
+ num1 = (parcela.get_Documento().get_AdicionalComiss() ? parcela.get_Documento().get_PremioLiquido() + parcela.get_Documento().get_PremioAdicional() : parcela.get_Documento().get_PremioLiquido());
+ num2 = (parcela.get_Documento().get_AdicionalComiss() ? parcela.get_Documento().get_PremioLiquido() + parcela.get_Documento().get_PremioAdicional() : parcela.get_Documento().get_PremioLiquido());
+ comissao = parcela.get_Documento().get_Comissao() * new decimal(1, 0, 0, false, 2);
+ }
+ num1 = (repasse.get_Incidencia().GetValueOrDefault() == 2 ? num1 : num1 * comissao);
+ num1 = (repasse.get_Tipo().GetValueOrDefault() == 1 ? num1 : (num1 * (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo())) * new decimal(1, 0, 0, false, 2));
+ decimal num5 = (repasse.get_Incidencia().GetValueOrDefault() == 2 ? num2 : num2 * comissao);
+ if (repasse.get_Tipo().GetValueOrDefault() != 1)
+ {
+ num = (num5 * (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo())) * new decimal(1, 0, 0, false, 2);
+ }
+ else
+ {
+ num = (valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo());
+ if (Recursos.Configuracoes.Any<ConfiguracaoSistema>((ConfiguracaoSistema x) => x.get_Configuracao() == 24) && parcela.get_Valor() < decimal.Zero)
+ {
+ num = -num;
+ }
+ }
+ if (parcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 2 && parcela.get_SubTipo() == 1 && parcela.get_Documento().get_TipoEndosso().GetValueOrDefault() != 2)
+ {
+ if (Math.Abs(num) > Math.Abs(num1))
+ {
+ (new BaseDialogViewModel()).ShowMessage("OS VALORES DE REPASSE ULTRAPASSARAM O VALOR DE COMISSÃO FECHADA. REVEJA OS VALORES.", "OK", "", false);
+ }
+ if (Math.Abs(num) <= Math.Abs(num1))
+ {
+ return num;
+ }
+ return num1;
+ }
+ if (parcela.get_ValorComDesconto() != decimal.Zero && Math.Abs(num) > Math.Abs(parcela.get_ValorComDesconto()))
+ {
+ if (Recursos.Configuracoes.All<ConfiguracaoSistema>((ConfiguracaoSistema x) => x.get_Configuracao() != 15))
+ {
+ return parcela.get_ValorComDesconto();
+ }
+ }
+ return num;
+ }
+
+ public static string Clear(this string stringToClean)
+ {
+ if (stringToClean == null)
+ {
+ return null;
+ }
+ return Regex.Replace(stringToClean, "[^\\d]", string.Empty);
+ }
+
+ private static void CloseSlackBar()
+ {
+ Thread.Sleep(5000);
+ Dispatcher dispatcher = App.ProgressRing.Dispatcher;
+ if (dispatcher == null)
+ {
+ return;
+ }
+ dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => Funcoes.ToggleSnackBar("", false)));
+ }
+
+ public static List<ParametrosRelatorio> ColunasRelatorio<T>(Relatorio relatorio, List<ParametrosRelatorio> parametrosAdicionados)
+ {
+ long id;
+ int ordem;
+ List<ParametrosRelatorio> parametrosRelatorios = new List<ParametrosRelatorio>();
+ foreach (PropertyInfo propertyInfo in
+ from in (IEnumerable<PropertyInfo>)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
+ orderby x.GetDescriptionAttribute()
+ select )
+ {
+ if (propertyInfo.Name == "ValidationEvent" || propertyInfo.GetTypeAttribute() == "INVALID" || parametrosAdicionados.Any<ParametrosRelatorio>((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name))
+ {
+ continue;
+ }
+ ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio();
+ ParametrosRelatorio parametrosRelatorio1 = parametrosAdicionados.FirstOrDefault<ParametrosRelatorio>((ParametrosRelatorio x) => {
+ if (x.get_IdUsuario() == 0)
+ {
+ return false;
+ }
+ return x.get_Campo() == propertyInfo.Name;
+ });
+ if (parametrosRelatorio1 != null)
+ {
+ id = parametrosRelatorio1.get_Id();
+ }
+ else
+ {
+ id = (long)0;
+ }
+ parametrosRelatorio.set_Id(id);
+ parametrosRelatorio.set_Campo(propertyInfo.Name);
+ parametrosRelatorio.set_Header(propertyInfo.GetDescriptionAttribute());
+ parametrosRelatorio.set_IdUsuario(Recursos.Usuario.get_Id());
+ parametrosRelatorio.set_Relatorio(relatorio);
+ parametrosRelatorio.set_Tipo(propertyInfo.GetTypeAttribute());
+ parametrosRelatorio.set_Width(0);
+ ParametrosRelatorio parametrosRelatorio2 = parametrosAdicionados.FirstOrDefault<ParametrosRelatorio>((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name);
+ if (parametrosRelatorio2 != null)
+ {
+ ordem = parametrosRelatorio2.get_Ordem();
+ }
+ else
+ {
+ ordem = 0;
+ }
+ parametrosRelatorio.set_Ordem(ordem);
+ parametrosRelatorios.Add(parametrosRelatorio);
+ }
+ return parametrosRelatorios;
+ }
+
+ public static List<SinteticModelList> ConstruirSintetico(this List<Sintetico> sintetico, Relatorio relatorio)
+ {
+ if (sintetico == null)
+ {
+ return null;
+ }
+ List<SinteticModelList> sinteticModelLists = new List<SinteticModelList>();
+ typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList<PropertyInfo>().ForEach((PropertyInfo props) => {
+ char chr;
+ if (props.GetValue(sintetico.First<Sintetico>()) == null)
+ {
+ return;
+ }
+ string descriptionAttribute = props.GetDescriptionAttribute();
+ TipoRestricao? nullable = null;
+ if (descriptionAttribute != null)
+ {
+ switch (descriptionAttribute.Length)
+ {
+ case 5:
+ {
+ if (descriptionAttribute == "VALOR")
+ {
+ nullable = new TipoRestricao?(100);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 7:
+ {
+ if (descriptionAttribute == "REPASSE")
+ {
+ nullable = new TipoRestricao?(81);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 8:
+ {
+ if (descriptionAttribute == "IMPOSTOS")
+ {
+ nullable = new TipoRestricao?(93);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 10:
+ {
+ if (descriptionAttribute == "VALOR PAGO")
+ {
+ nullable = new TipoRestricao?(104);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 11:
+ {
+ if (descriptionAttribute == "TOTAL GERAL")
+ {
+ nullable = new TipoRestricao?(75);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 12:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'M')
+ {
+ if (descriptionAttribute == "META ATINGIR")
+ {
+ nullable = new TipoRestricao?(88);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'P')
+ {
+ if (descriptionAttribute == "PRÊMIO TOTAL")
+ {
+ nullable = new TipoRestricao?(65);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'V')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "VALOR ORÇADO")
+ {
+ nullable = new TipoRestricao?(101);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 13:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'M')
+ {
+ if (descriptionAttribute == "META CUMPRIDA")
+ {
+ nullable = new TipoRestricao?(89);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'V')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "VALOR SALVADO")
+ {
+ nullable = new TipoRestricao?(105);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 14:
+ {
+ chr = descriptionAttribute[8];
+ switch (chr)
+ {
+ case 'A':
+ {
+ if (descriptionAttribute == "VALOR FRANQUIA")
+ {
+ nullable = new TipoRestricao?(106);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 'B':
+ {
+ if (descriptionAttribute == "VALOR LIBERADO")
+ {
+ nullable = new TipoRestricao?(103);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 'C':
+ case 'D':
+ {
+ goto Label0;
+ }
+ case 'E':
+ {
+ if (descriptionAttribute == "TOTAL PREVISTO")
+ {
+ nullable = new TipoRestricao?(82);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ default:
+ {
+ if (chr == 'R')
+ {
+ if (descriptionAttribute == "TOTAL PARCELAS")
+ {
+ nullable = new TipoRestricao?(102);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'Í')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "PRÊMIO LÍQUIDO")
+ {
+ nullable = new TipoRestricao?(67);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ }
+ break;
+ }
+ case 15:
+ {
+ if (descriptionAttribute == "VALOR LIQUIDADO")
+ {
+ nullable = new TipoRestricao?(86);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 16:
+ {
+ if (descriptionAttribute == "TOTAL DE LÍQUIDO")
+ {
+ nullable = new TipoRestricao?(76);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 17:
+ {
+ chr = descriptionAttribute[10];
+ if (chr == 'E')
+ {
+ if (descriptionAttribute == "COMISSÃO PENDENTE")
+ {
+ nullable = new TipoRestricao?(87);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'L')
+ {
+ if (descriptionAttribute == "TOTAL DE CLIENTES")
+ {
+ goto Label1;
+ }
+ goto Label0;
+ }
+ else if (chr != 'R')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "COMISSÃO PREVISTA")
+ {
+ nullable = new TipoRestricao?(80);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 18:
+ {
+ if (descriptionAttribute == "TOTAL DE TERCEIROS")
+ {
+ nullable = new TipoRestricao?(83);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 19:
+ {
+ if (descriptionAttribute == "QUANTIDADE PENDENTE")
+ {
+ nullable = new TipoRestricao?(85);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 20:
+ {
+ if (descriptionAttribute == "QUANTIDADE LIQUIDADO")
+ {
+ nullable = new TipoRestricao?(84);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 21:
+ {
+ if (descriptionAttribute == "QUANTIDADE DE FATURAS")
+ {
+ nullable = new TipoRestricao?(74);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 22:
+ {
+ chr = descriptionAttribute[14];
+ if (chr == 'A')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE APÓLICES")
+ {
+ nullable = new TipoRestricao?(72);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'E')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "QUANTIDADE DE ENDOSSOS")
+ {
+ nullable = new TipoRestricao?(73);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 23:
+ {
+ if (descriptionAttribute == "COMISSÃO RECEBIDA BRUTA")
+ {
+ nullable = new TipoRestricao?(79);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 24:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'M')
+ {
+ if (descriptionAttribute == "MÉDIA DE COMISSÃO GERADA")
+ {
+ break;
+ }
+ goto Label0;
+ }
+ else if (chr == 'Q')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE RENOVAÇÕES")
+ {
+ goto Label2;
+ }
+ goto Label0;
+ }
+ else if (chr == 'T')
+ {
+ if (descriptionAttribute == "TOTAL DE CLIENTES ATIVOS")
+ {
+ goto Label1;
+ }
+ if (descriptionAttribute == "TOTAL DE COMISSÃO GERADA")
+ {
+ nullable = new TipoRestricao?(78);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 25:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'C')
+ {
+ if (descriptionAttribute == "COMISSÃO RECEBIDA LÍQUIDA")
+ {
+ nullable = new TipoRestricao?(92);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'M')
+ {
+ if (descriptionAttribute == "MÉDIA DE COMISSÃO FECHADA")
+ {
+ break;
+ }
+ goto Label0;
+ }
+ else if (chr != 'Q')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "QUANTIDADE DE PROSPECÇÕES")
+ {
+ nullable = new TipoRestricao?(77);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 26:
+ {
+ if (descriptionAttribute == "TOTAL DE CLIENTES INATIVOS")
+ {
+ goto Label1;
+ }
+ goto Label0;
+ }
+ case 27:
+ {
+ chr = descriptionAttribute[15];
+ if (chr == 'A')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE CANCELAMENTOS")
+ {
+ nullable = new TipoRestricao?(71);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'E')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE SEGUROS NOVOS")
+ {
+ goto Label2;
+ }
+ goto Label0;
+ }
+ else if (chr == 'Ã')
+ {
+ if (descriptionAttribute == "MÉDIA DE COMISSÃO PONDERADA")
+ {
+ break;
+ }
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 28:
+ {
+ if (descriptionAttribute == "QUANTIDADE DE NOVOS NEGÓCIOS")
+ {
+ goto Label3;
+ }
+ goto Label0;
+ }
+ case 31:
+ {
+ if (descriptionAttribute == "QUANTIDADE DE NEGÓCIOS PRÓPRIOS")
+ {
+ goto Label3;
+ }
+ goto Label0;
+ }
+ default:
+ {
+ goto Label0;
+ }
+ }
+ nullable = new TipoRestricao?(68);
+ }
+ Label0:
+ if (nullable.HasValue)
+ {
+ RestricaoUsuario restricaoUsuario = (new RestricaoUsuarioServico()).BuscarRestricao(Recursos.Usuario, nullable.Value);
+ if (restricaoUsuario != null && restricaoUsuario.get_Restricao())
+ {
+ return;
+ }
+ }
+ List<ParametrosTotalizacao> parametrosTotalizacaos = (new ConfuguracoesServico()).BuscarParametroTotalizacao(relatorio);
+ if (parametrosTotalizacaos != null && parametrosTotalizacaos.Count > 0 && parametrosTotalizacaos.All<ParametrosTotalizacao>((ParametrosTotalizacao y) => y.get_Campo() != props.Name) && !props.Name.ToUpperInvariant().Contains("AGRUPAMENTO"))
+ {
+ return;
+ }
+ SinteticModelList sinteticModelList = new SinteticModelList();
+ sinteticModelList.set_Hint(descriptionAttribute);
+ sinteticModelList.set_Value(new List<object>());
+ SinteticModelList sinteticModelList1 = sinteticModelList;
+ string typeAttribute = props.GetTypeAttribute();
+ sintetico.ForEach((Sintetico s) => {
+ object obj;
+ DateTime? value;
+ DateTime valueOrDefault;
+ object str;
+ object str1;
+ string str2 = typeAttribute;
+ if (str2 == "DATA/TIME" || str2 == "DATA/TIME?")
+ {
+ value = (DateTime?)props.GetValue(s);
+ if (value.HasValue)
+ {
+ valueOrDefault = value.GetValueOrDefault();
+ str = valueOrDefault.ToString("G");
+ }
+ else
+ {
+ str = null;
+ }
+ obj = str;
+ }
+ else if (str2 == "DATA" || str2 == "DATA?")
+ {
+ value = (DateTime?)props.GetValue(s);
+ if (value.HasValue)
+ {
+ valueOrDefault = value.GetValueOrDefault();
+ str1 = valueOrDefault.ToString("d");
+ }
+ else
+ {
+ str1 = null;
+ }
+ obj = str1;
+ }
+ else
+ {
+ obj = (str2 == "PERCENTUAL" ? string.Format("{0:n2} %", props.GetValue(s)) : (str2 == "VALOR" ? ((decimal)props.GetValue(s)).ToString("c2") : string.Format("{0}", props.GetValue(s))));
+ }
+ sinteticModelList1.get_Value().Add(obj);
+ });
+ sinteticModelLists.Add(sinteticModelList1);
+ return;
+ Label1:
+ nullable = new TipoRestricao?(66);
+ goto Label0;
+ Label2:
+ nullable = new TipoRestricao?(70);
+ goto Label0;
+ Label3:
+ nullable = new TipoRestricao?(69);
+ goto Label0;
+ });
+ return sinteticModelLists;
+ }
+
+ public static List<SinteticModel> ConstruirSintetico(this Sintetico sintetico, Relatorio relatorio)
+ {
+ if (sintetico == null)
+ {
+ return null;
+ }
+ List<SinteticModel> sinteticModels = new List<SinteticModel>();
+ typeof(Sintetico).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList<PropertyInfo>().ForEach((PropertyInfo x) => {
+ int length;
+ char chr;
+ DateTime? value;
+ DateTime valueOrDefault;
+ decimal num;
+ object str;
+ SinteticModel sinteticModel;
+ object obj;
+ if (x.GetValue(sintetico) == null)
+ {
+ return;
+ }
+ string descriptionAttribute = x.GetDescriptionAttribute();
+ TipoRestricao? nullable = null;
+ string str1 = null;
+ if (descriptionAttribute != null)
+ {
+ length = descriptionAttribute.Length;
+ switch (length)
+ {
+ case 5:
+ {
+ if (descriptionAttribute == "VALOR")
+ {
+ nullable = new TipoRestricao?(100);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 7:
+ {
+ if (descriptionAttribute == "REPASSE")
+ {
+ nullable = new TipoRestricao?(81);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 8:
+ {
+ if (descriptionAttribute == "IMPOSTOS")
+ {
+ nullable = new TipoRestricao?(93);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 10:
+ {
+ if (descriptionAttribute == "VALOR PAGO")
+ {
+ nullable = new TipoRestricao?(104);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 11:
+ {
+ if (descriptionAttribute == "TOTAL GERAL")
+ {
+ nullable = new TipoRestricao?(75);
+ str1 = "CONTAGEM GERAL DE DOCUMENTOS";
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 12:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'M')
+ {
+ if (descriptionAttribute == "META ATINGIR")
+ {
+ nullable = new TipoRestricao?(88);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'P')
+ {
+ if (descriptionAttribute == "PRÊMIO TOTAL")
+ {
+ nullable = new TipoRestricao?(65);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'V')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "VALOR ORÇADO")
+ {
+ nullable = new TipoRestricao?(101);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 13:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'M')
+ {
+ if (descriptionAttribute == "META CUMPRIDA")
+ {
+ nullable = new TipoRestricao?(89);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'V')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "VALOR SALVADO")
+ {
+ nullable = new TipoRestricao?(105);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 14:
+ {
+ chr = descriptionAttribute[8];
+ switch (chr)
+ {
+ case 'A':
+ {
+ if (descriptionAttribute == "VALOR FRANQUIA")
+ {
+ nullable = new TipoRestricao?(106);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 'B':
+ {
+ if (descriptionAttribute == "VALOR LIBERADO")
+ {
+ nullable = new TipoRestricao?(103);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 'C':
+ case 'D':
+ {
+ goto Label0;
+ }
+ case 'E':
+ {
+ if (descriptionAttribute == "TOTAL PREVISTO")
+ {
+ nullable = new TipoRestricao?(82);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ default:
+ {
+ if (chr == 'R')
+ {
+ if (descriptionAttribute == "TOTAL PARCELAS")
+ {
+ nullable = new TipoRestricao?(102);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'Í')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "PRÊMIO LÍQUIDO")
+ {
+ nullable = new TipoRestricao?(67);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ }
+ break;
+ }
+ case 15:
+ {
+ if (descriptionAttribute == "VALOR LIQUIDADO")
+ {
+ nullable = new TipoRestricao?(86);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 16:
+ {
+ if (descriptionAttribute == "TOTAL DE LÍQUIDO")
+ {
+ nullable = new TipoRestricao?(76);
+ str1 = "CONTAGEM GERAL DOS DOCUMENTOS ATIVOS";
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 17:
+ {
+ chr = descriptionAttribute[10];
+ if (chr == 'E')
+ {
+ if (descriptionAttribute == "COMISSÃO PENDENTE")
+ {
+ nullable = new TipoRestricao?(87);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'L')
+ {
+ if (descriptionAttribute == "TOTAL DE CLIENTES")
+ {
+ goto Label1;
+ }
+ goto Label0;
+ }
+ else if (chr != 'R')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "COMISSÃO PREVISTA")
+ {
+ nullable = new TipoRestricao?(80);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 18:
+ {
+ if (descriptionAttribute == "TOTAL DE TERCEIROS")
+ {
+ nullable = new TipoRestricao?(83);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 19:
+ {
+ if (descriptionAttribute == "QUANTIDADE PENDENTE")
+ {
+ nullable = new TipoRestricao?(85);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 20:
+ {
+ if (descriptionAttribute == "QUANTIDADE LIQUIDADO")
+ {
+ nullable = new TipoRestricao?(84);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 21:
+ {
+ if (descriptionAttribute == "QUANTIDADE DE FATURAS")
+ {
+ nullable = new TipoRestricao?(74);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 22:
+ {
+ chr = descriptionAttribute[14];
+ if (chr == 'A')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE APÓLICES")
+ {
+ nullable = new TipoRestricao?(72);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr != 'E')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "QUANTIDADE DE ENDOSSOS")
+ {
+ nullable = new TipoRestricao?(73);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 23:
+ {
+ if (descriptionAttribute == "COMISSÃO RECEBIDA BRUTA")
+ {
+ nullable = new TipoRestricao?(79);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 24:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'M')
+ {
+ if (descriptionAttribute == "MÉDIA DE COMISSÃO GERADA")
+ {
+ break;
+ }
+ goto Label0;
+ }
+ else if (chr == 'Q')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE RENOVAÇÕES")
+ {
+ goto Label2;
+ }
+ goto Label0;
+ }
+ else if (chr == 'T')
+ {
+ if (descriptionAttribute == "TOTAL DE CLIENTES ATIVOS")
+ {
+ goto Label1;
+ }
+ if (descriptionAttribute == "TOTAL DE COMISSÃO GERADA")
+ {
+ nullable = new TipoRestricao?(78);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 25:
+ {
+ chr = descriptionAttribute[0];
+ if (chr == 'C')
+ {
+ if (descriptionAttribute == "COMISSÃO RECEBIDA LÍQUIDA")
+ {
+ nullable = new TipoRestricao?(92);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'M')
+ {
+ if (descriptionAttribute == "MÉDIA DE COMISSÃO FECHADA")
+ {
+ break;
+ }
+ goto Label0;
+ }
+ else if (chr != 'Q')
+ {
+ goto Label0;
+ }
+ else if (descriptionAttribute == "QUANTIDADE DE PROSPECÇÕES")
+ {
+ nullable = new TipoRestricao?(77);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 26:
+ {
+ if (descriptionAttribute == "TOTAL DE CLIENTES INATIVOS")
+ {
+ goto Label1;
+ }
+ goto Label0;
+ }
+ case 27:
+ {
+ chr = descriptionAttribute[15];
+ if (chr == 'A')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE CANCELAMENTOS")
+ {
+ nullable = new TipoRestricao?(71);
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ else if (chr == 'E')
+ {
+ if (descriptionAttribute == "QUANTIDADE DE SEGUROS NOVOS")
+ {
+ goto Label2;
+ }
+ goto Label0;
+ }
+ else if (chr == 'Ã')
+ {
+ if (descriptionAttribute == "MÉDIA DE COMISSÃO PONDERADA")
+ {
+ break;
+ }
+ goto Label0;
+ }
+ else
+ {
+ goto Label0;
+ }
+ }
+ case 28:
+ {
+ if (descriptionAttribute == "QUANTIDADE DE NOVOS NEGÓCIOS")
+ {
+ goto Label3;
+ }
+ goto Label0;
+ }
+ case 31:
+ {
+ if (descriptionAttribute == "QUANTIDADE DE NEGÓCIOS PRÓPRIOS")
+ {
+ goto Label3;
+ }
+ goto Label0;
+ }
+ default:
+ {
+ goto Label0;
+ }
+ }
+ nullable = new TipoRestricao?(68);
+ }
+ Label0:
+ if (nullable.HasValue)
+ {
+ RestricaoUsuario restricaoUsuario = (new RestricaoUsuarioServico()).BuscarRestricao(Recursos.Usuario, nullable.Value);
+ if (restricaoUsuario != null && restricaoUsuario.get_Restricao())
+ {
+ return;
+ }
+ }
+ List<ParametrosTotalizacao> parametrosTotalizacaos = (new ConfuguracoesServico()).BuscarParametroTotalizacao(relatorio);
+ if (parametrosTotalizacaos != null && parametrosTotalizacaos.Count > 0 && parametrosTotalizacaos.All<ParametrosTotalizacao>((ParametrosTotalizacao y) => y.get_Campo() != x.Name))
+ {
+ return;
+ }
+ SinteticModel sinteticModel1 = new SinteticModel();
+ sinteticModel1.set_Hint(descriptionAttribute);
+ sinteticModel1.set_DescriptionField(str1);
+ SinteticModel sinteticModel2 = sinteticModel1;
+ string typeAttribute = x.GetTypeAttribute();
+ if (typeAttribute != null)
+ {
+ length = typeAttribute.Length;
+ switch (length)
+ {
+ case 4:
+ {
+ if (typeAttribute == "DATA")
+ {
+ break;
+ }
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ case 5:
+ {
+ chr = typeAttribute[0];
+ if (chr == 'D')
+ {
+ if (typeAttribute == "DATA?")
+ {
+ break;
+ }
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else if (chr != 'V')
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else if (typeAttribute == "VALOR")
+ {
+ num = (decimal)x.GetValue(sintetico);
+ sinteticModel2.set_Value(num.ToString("c2"));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ }
+ case 6:
+ case 7:
+ case 8:
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ case 9:
+ {
+ if (typeAttribute == "DATA/TIME")
+ {
+ sinteticModel = sinteticModel2;
+ value = (DateTime?)x.GetValue(sintetico);
+ if (value.HasValue)
+ {
+ valueOrDefault = value.GetValueOrDefault();
+ obj = valueOrDefault.ToString("G");
+ }
+ else
+ {
+ obj = null;
+ }
+ sinteticModel.set_Value(obj);
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ case 10:
+ {
+ chr = typeAttribute[0];
+ if (chr == 'D')
+ {
+ if (typeAttribute == "DATA/TIME?")
+ {
+ sinteticModel = sinteticModel2;
+ value = (DateTime?)x.GetValue(sintetico);
+ if (value.HasValue)
+ {
+ valueOrDefault = value.GetValueOrDefault();
+ obj = valueOrDefault.ToString("G");
+ }
+ else
+ {
+ obj = null;
+ }
+ sinteticModel.set_Value(obj);
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else if (chr != 'P')
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else if (typeAttribute == "PERCENTUAL")
+ {
+ sinteticModel2.set_Value(string.Format("{0} %", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ }
+ default:
+ {
+ if (length == 13)
+ {
+ if (typeAttribute != "VALORDECIMAL2")
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ num = (decimal)x.GetValue(sintetico);
+ sinteticModel2.set_Value(num.ToString("n2"));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ else
+ {
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ }
+ }
+ SinteticModel sinteticModel3 = sinteticModel2;
+ value = (DateTime?)x.GetValue(sintetico);
+ if (value.HasValue)
+ {
+ valueOrDefault = value.GetValueOrDefault();
+ str = valueOrDefault.ToString("d");
+ }
+ else
+ {
+ str = null;
+ }
+ sinteticModel3.set_Value(str);
+ sinteticModels.Add(sinteticModel2);
+ return;
+ }
+ sinteticModel2.set_Value(string.Format("{0}", x.GetValue(sintetico)));
+ sinteticModels.Add(sinteticModel2);
+ return;
+ Label1:
+ nullable = new TipoRestricao?(66);
+ goto Label0;
+ Label2:
+ nullable = new TipoRestricao?(70);
+ goto Label0;
+ Label3:
+ nullable = new TipoRestricao?(69);
+ goto Label0;
+ });
+ return sinteticModels;
+ }
+
+ public static async Task ContruirLista<T>(DataGrid grid, Relatorio relatorio)
+ {
+ List<ParametrosRelatorio> list = await (new ConfuguracoesServico()).BuscarParametros(relatorio);
+ if (list == null || list.Count == 0)
+ {
+ list = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Select<PropertyInfo, ParametrosRelatorio>((PropertyInfo x) => {
+ ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio();
+ parametrosRelatorio.set_Campo(x.Name);
+ parametrosRelatorio.set_Header(x.GetDescriptionAttribute());
+ parametrosRelatorio.set_Tipo(x.GetTypeAttribute());
+ parametrosRelatorio.set_Relatorio(relatorio);
+ parametrosRelatorio.set_Width(0);
+ parametrosRelatorio.set_Ordem(0);
+ return parametrosRelatorio;
+ }).ToList<ParametrosRelatorio>();
+ }
+ if (!Recursos.Usuario.get_Administrador())
+ {
+ list = await Funcoes.GetRestricoesColunas(list);
+ }
+ List<ParametrosRelatorio> parametrosRelatorios = list;
+ IOrderedEnumerable<ParametrosRelatorio> ordem =
+ from in parametrosRelatorios
+ orderby x.get_Ordem()
+ select ;
+ ordem.ThenBy<ParametrosRelatorio, string>((ParametrosRelatorio x) => x.get_Header()).ToList<ParametrosRelatorio>().ForEach((ParametrosRelatorio x) => {
+ char chr;
+ object upper;
+ if (x.get_Tipo() == "INVALID")
+ {
+ return;
+ }
+ if (x.get_Campo() == "DataControle" && !Recursos.Usuario.get_Administrador())
+ {
+ List<ConfiguracaoSistema> configuracoes = Recursos.Configuracoes;
+ Func<ConfiguracaoSistema, bool> u003cu003e9_324 = Funcoes.u003cu003ec__32<T>.u003cu003e9__32_4;
+ if (u003cu003e9_324 == null)
+ {
+ u003cu003e9_324 = (ConfiguracaoSistema c) => c.get_Configuracao() == 33;
+ Funcoes.u003cu003ec__32<T>.u003cu003e9__32_4 = u003cu003e9_324;
+ }
+ if (configuracoes.Any<ConfiguracaoSistema>(u003cu003e9_324))
+ {
+ return;
+ }
+ }
+ string str = "";
+ Style item = (Style)System.Windows.Application.Current.Resources["VerticalCenterStyle3"];
+ Style style = (Style)System.Windows.Application.Current.Resources["MaterialDesignDataGridColumnHeaderNew"];
+ string tipo = x.get_Tipo();
+ if (tipo != null)
+ {
+ int length = tipo.Length;
+ switch (length)
+ {
+ case 4:
+ {
+ if (tipo == "DATA")
+ {
+ break;
+ }
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ case 5:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA?")
+ {
+ break;
+ }
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else if (chr != 'V')
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else if (tipo == "VALOR")
+ {
+ str = "c";
+ item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"];
+ style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"];
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ }
+ case 6:
+ case 7:
+ case 8:
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ case 9:
+ {
+ if (tipo == "DATA/TIME")
+ {
+ goto Label1;
+ }
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ case 10:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA/TIME?")
+ {
+ goto Label1;
+ }
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else if (chr == 'P')
+ {
+ if (tipo == "PERCENTUAL")
+ {
+ str = "{0:0.00}%";
+ item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"];
+ style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"];
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ }
+ else if (chr != 'Q')
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else if (tipo == "QUANTIDADE")
+ {
+ item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"];
+ style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"];
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ }
+ default:
+ {
+ if (length != 13)
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else if (tipo == "VALORDECIMAL2")
+ {
+ str = "n2";
+ item = (Style)System.Windows.Application.Current.Resources["HorizontalRightStyle"];
+ style = (Style)System.Windows.Application.Current.Resources["HorizontalRightHeaderStyleNew"];
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ else
+ {
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ }
+ }
+ }
+ str = "d";
+ item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"];
+ style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"];
+ }
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ Label1:
+ str = "G";
+ item = (Style)System.Windows.Application.Current.Resources["HorizontalCenterStyle2"];
+ style = (Style)System.Windows.Application.Current.Resources["HorizontalCenterHeaderStyleNew"];
+ ObservableCollection<DataGridColumn> columns = grid.Columns;
+ MaterialDataGridTextColumn materialDataGridTextColumn = new MaterialDataGridTextColumn();
+ string header = x.get_Header();
+ if (header != null)
+ {
+ upper = header.ToUpper();
+ }
+ else
+ {
+ upper = null;
+ }
+ if (upper == null)
+ {
+ upper = x.get_Campo().ToUpper();
+ }
+ materialDataGridTextColumn.Header = upper;
+ materialDataGridTextColumn.Binding = new Binding()
+ {
+ Path = new PropertyPath(x.get_Campo(), Array.Empty<object>()),
+ StringFormat = str,
+ Mode = BindingMode.TwoWay,
+ UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
+ };
+ materialDataGridTextColumn.Width = (x.get_Width() == 0 ? new DataGridLength(1, DataGridLengthUnitType.Auto) : (double)x.get_Width());
+ materialDataGridTextColumn.ElementStyle = item;
+ materialDataGridTextColumn.HeaderStyle = style;
+ columns.Add(materialDataGridTextColumn);
+ return;
+ });
+ }
+
+ public static string ConvertGaragemTrabalhoEstudoCalculo(this GaragemTrabalhoEstudo garagemTrabalhoEstudo)
+ {
+ switch (garagemTrabalhoEstudo)
+ {
+ case 0:
+ {
+ return "0";
+ }
+ case 1:
+ {
+ return "1";
+ }
+ case 2:
+ {
+ return "2";
+ }
+ case 3:
+ {
+ return string.Empty;
+ }
+ case 4:
+ case 5:
+ {
+ return "3";
+ }
+ default:
+ {
+ return string.Empty;
+ }
+ }
+ }
+
+ public static TipoTela? ConvertTela(string name)
+ {
+ return new TipoTela?(((TipoTela[])Enum.GetValues(typeof(TipoTela))).ToList<TipoTela>().FirstOrDefault<TipoTela>((TipoTela x) => Gestor.Common.Validation.ValidationHelper.GetEntity(x) == name));
+ }
+
+ public static TempoHabilitacao ConvertTempoHabilitacao(int tempoHabilitacao = 0)
+ {
+ if (tempoHabilitacao == 1)
+ {
+ return 0;
+ }
+ if (tempoHabilitacao == 2)
+ {
+ return 1;
+ }
+ if (tempoHabilitacao == 3)
+ {
+ return 2;
+ }
+ if (tempoHabilitacao == 4)
+ {
+ return 3;
+ }
+ if (tempoHabilitacao == 5)
+ {
+ return 4;
+ }
+ if (tempoHabilitacao == 6)
+ {
+ return 5;
+ }
+ if (tempoHabilitacao == 7)
+ {
+ return 6;
+ }
+ if (tempoHabilitacao == 8)
+ {
+ return 7;
+ }
+ if (tempoHabilitacao == 9)
+ {
+ return 8;
+ }
+ if (tempoHabilitacao == 10)
+ {
+ return 9;
+ }
+ if (tempoHabilitacao >= 11)
+ {
+ return 10;
+ }
+ return 0;
+ }
+
+ public static string ConvertTempoHabilitacaoCalculo(this DateTime tempoHabilitacao)
+ {
+ if (tempoHabilitacao == DateTime.MinValue)
+ {
+ return "0";
+ }
+ int year = DateTime.Now.Year - tempoHabilitacao.Year;
+ if (year >= 11)
+ {
+ return "11";
+ }
+ return year.ToString();
+ }
+
+ public static string ConvertTipoSeguroCalculo(this TipoSeguro tipoSeguro)
+ {
+ if (tipoSeguro - 1 <= 1)
+ {
+ return "1";
+ }
+ return "0";
+ }
+
+ public static void CopyToClipboard(this string text)
+ {
+ try
+ {
+ Clipboard.SetText(text);
+ }
+ catch (Exception exception)
+ {
+ }
+ }
+
+ public static string CreateCard(string title, string body, bool pageBreak = false)
+ {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append((pageBreak ? "<div class='card p-0' style='page-break-after:always;'>" : "<div class='card p-0'>"));
+ stringBuilder.Append("<div class='card-body'>");
+ stringBuilder.Append(string.Concat("<h5 class='card-title'>", title, "</h5>"));
+ stringBuilder.Append(body);
+ stringBuilder.Append("</div>");
+ stringBuilder.Append("</div>");
+ return stringBuilder.ToString();
+ }
+
+ public static async Task<string> CriarAssistencia(Assistance assistance)
+ {
+ return await Gestor.Application.Helpers.Connection.Post<string>("Assistance", assistance);
+ }
+
+ public static async Task<string> CriarCartao(Gestor.Model.Domain.Card.Card card)
+ {
+ return await Gestor.Application.Helpers.Connection.Post<string>("Card", card);
+ }
+
+ public static async Task<string> Criarlogo(Logo logo)
+ {
+ return await Gestor.Application.Helpers.Connection.Post<string>("Card/Logo", logo);
+ }
+
+ public static string CriarRecibo(Vendedor vendedor, decimal valor, Filtros filtro, bool segundavia)
+ {
+ string str = (segundavia ? " acima listados" : string.Format(" no periodo de {0:d} até {1:d}", filtro.get_Inicio(), filtro.get_Fim()));
+ string str1 = "CPF";
+ if (vendedor.get_Documento() != null && Gestor.Common.Validation.ValidationHelper.OnlyNumber(vendedor.get_Documento()).Length > 12)
+ {
+ str1 = "CNPJ";
+ }
+ object[] nome = new object[] { vendedor.get_Nome(), str1, vendedor.get_Documento(), Recursos.Empresa.get_Nome(), valor, str, null };
+ nome[6] = Funcoes.GetNetworkTime().Date;
+ return string.Format(" <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 {0}, portador(a) do {1} {2} declaro que recebi de {3} o valor de {4:c} referente a comissão dos seguros{5}.</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> {6:d}</p>\r\n </div>\r\n </div>", nome);
+ }
+
+ public static async Task<string> CriarSeguradora(AssistenciaCia cia)
+ {
+ return await Gestor.Application.Helpers.Connection.Post<string>("Assistance/Seguradora", cia);
+ }
+
+ public static void DatePicker_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
+ {
+ DatePicker datePicker = (DatePicker)sender;
+ datePicker.Text = Gestor.Common.Validation.ValidationHelper.FormatDate(datePicker.Text);
+ }
+
+ public static void DatePicker_PreviewKeyDown(object sender, KeyEventArgs e)
+ {
+ if (e.Key != Key.Return)
+ {
+ return;
+ }
+ DatePicker str = (DatePicker)sender;
+ DateTime date = Funcoes.GetNetworkTime().Date;
+ str.Text = date.ToString("dd/MM/yyyy");
+ }
+
+ public static void Destroy<T>()
+ where T : Window
+ {
+ object obj = System.Windows.Application.Current.Windows.OfType<T>().FirstOrDefault<T>();
+ if (obj == null)
+ {
+ return;
+ }
+ ((Window)obj).Close();
+ }
+
+ public static void Destroy<T>(string title)
+ where T : Window
+ {
+ object obj = System.Windows.Application.Current.Windows.OfType<T>().FirstOrDefault<T>((T x) => x.Title == title);
+ if (obj == null)
+ {
+ return;
+ }
+ ((Window)obj).Close();
+ }
+
+ public static string DiaDaSemana(this int? dia)
+ {
+ if (!dia.HasValue)
+ {
+ return "";
+ }
+ switch (dia.Value)
+ {
+ case 0:
+ {
+ return "DOMINGO";
+ }
+ case 1:
+ {
+ return "SEGUNDA-FEIRA";
+ }
+ case 2:
+ {
+ return "TERÇA-FEIRA";
+ }
+ case 3:
+ {
+ return "QUARTA-FEIRA";
+ }
+ case 4:
+ {
+ return "QUINTA-FEIRA";
+ }
+ case 5:
+ {
+ return "SEXTA-FEIRA";
+ }
+ case 6:
+ {
+ return "SABADO";
+ }
+ }
+ return "";
+ }
+
+ public static IEnumerable<TSource> DistinctBy<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
+ {
+ HashSet<TKey> tKeys = new HashSet<TKey>();
+ foreach (TSource tSource in source)
+ {
+ if (!tKeys.Add(keySelector(tSource)))
+ {
+ continue;
+ }
+ yield return tSource;
+ }
+ }
+
+ public static bool EnviarWhatsapp(this string numero, string anotacoes = null)
+ {
+ bool flag;
+ Uri uri = (string.IsNullOrEmpty(anotacoes) ? Recursos.WhatsAppLink.SetQuery("phone", numero, true) : Recursos.WhatsAppLink.AddQuery<string>("phone", numero).SetQuery("text", anotacoes, true));
+ try
+ {
+ Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
+ flag = true;
+ }
+ catch (Exception exception)
+ {
+ uri.AbsoluteUri.CopyToClipboard();
+ flag = false;
+ }
+ return flag;
+ }
+
+ public static async Task<Parcela> ExcluirBaixa(Parcela parcela, List<VendedorParcela> repasses, List<Parcela> parcelas = null)
+ {
+ Parcela parcela1;
+ string str;
+ decimal num1;
+ List<Parcela> parcelas1;
+ List<Parcela> parcelas2;
+ Funcoes.u003cu003ec__DisplayClass9_0 variable;
+ ParcelaServico parcelaServico;
+ VendedorServico vendedorServico;
+ Parcela parcela2 = parcela;
+ ParcelaServico parcelaServico1 = new ParcelaServico();
+ if (parcela2.get_SubTipo() != 1 || parcela2.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1)
+ {
+ List<VendedorParcela> list = repasses.Where<VendedorParcela>((VendedorParcela x) => {
+ if (x.get_Parcela().get_Id() != parcela2.get_Id())
+ {
+ return false;
+ }
+ return !x.get_DataPagamento().HasValue;
+ }).ToList<VendedorParcela>();
+ List<VendedorParcela> vendedorParcelas1 = list;
+ vendedorParcelas1.ForEach((VendedorParcela x) => {
+ x.set_DataPrePagamento(null);
+ VendedorParcela vendedorParcela = x;
+ decimal? valorTotal = x.get_ValorTotal();
+ vendedorParcela.set_ValorRepasse(new decimal?((valorTotal.HasValue ? valorTotal.GetValueOrDefault() : Funcoes.CalculaPagamento(x, x.get_Parcela(), decimal.Zero))));
+ });
+ parcela2.set_ValorComissao(decimal.Zero);
+ parcela2.set_ValorComDesconto(decimal.Zero);
+ DateTime? nullable1 = null;
+ parcela2.set_DataRecebimento(nullable1);
+ nullable1 = null;
+ parcela2.set_DataCredito(nullable1);
+ parcela2.set_ValorRealizado(decimal.Zero);
+ Parcela parcela3 = await parcelaServico1.Save(parcela2, parcelas, list, false);
+ parcela2 = parcela3;
+ if (!parcelaServico1.Sucesso)
+ {
+ await Funcoes.MostrarErro(191);
+ parcela1 = parcela2;
+ variable = null;
+ parcelaServico1 = null;
+ parcelaServico = null;
+ vendedorServico = null;
+ return parcela1;
+ }
+ }
+ else
+ {
+ List<VendedorParcela> list1 = repasses.Where<VendedorParcela>((VendedorParcela x) => {
+ bool valueOrDefault;
+ if (x.get_Parcela().get_SubTipo() == 1)
+ {
+ Repasse repasse = x.get_Repasse();
+ valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false);
+ if (valueOrDefault)
+ {
+ if (x.get_Parcela().get_Id() == this.parcela.get_Id())
+ {
+ return true;
+ }
+ return !x.get_DataPrePagamento().HasValue;
+ }
+ }
+ return false;
+ }).ToList<VendedorParcela>();
+ decimal premioLiquido = parcela2.get_Documento().get_PremioLiquido();
+ num1 = (parcela2.get_Documento().get_AdicionalComiss() ? parcela2.get_Documento().get_PremioAdicional() : decimal.Zero);
+ decimal comissao = ((premioLiquido + num1) * parcela2.get_Documento().get_Comissao()) * new decimal(1, 0, 0, false, 2);
+ List<VendedorParcela> vendedorParcelas2 = list1;
+ List<VendedorParcela> list2 = (
+ from x in vendedorParcelas2
+ group x by x.get_Vendedor().get_Id()).Select<IGrouping<long, VendedorParcela>, VendedorParcela>((IGrouping<long, VendedorParcela> x) => {
+ TipoRepasse? nullable;
+ decimal? valorTotal;
+ decimal num;
+ TipoRepasse? tipo;
+ bool valueOrDefault;
+ bool hasValue;
+ decimal? valorRepasse;
+ bool flag;
+ VendedorParcela vendedorParcela = new VendedorParcela();
+ vendedorParcela.set_Repasse(x.First<VendedorParcela>().get_Repasse());
+ vendedorParcela.set_Parcela(parcela2);
+ vendedorParcela.set_Documento(parcela2.get_Documento());
+ VendedorParcela vendedorParcela1 = x.First<VendedorParcela>();
+ if (vendedorParcela1 != null)
+ {
+ Repasse repasse = vendedorParcela1.get_Repasse();
+ if (repasse != null)
+ {
+ tipo = repasse.get_Tipo();
+ }
+ else
+ {
+ nullable = null;
+ tipo = nullable;
+ }
+ nullable = tipo;
+ valueOrDefault = nullable.GetValueOrDefault() != 3;
+ }
+ else
+ {
+ valueOrDefault = true;
+ }
+ if (valueOrDefault)
+ {
+ VendedorParcela vendedorParcela2 = x.First<VendedorParcela>();
+ if (vendedorParcela2 != null)
+ {
+ valorTotal = vendedorParcela2.get_ValorTotal();
+ hasValue = valorTotal.HasValue;
+ }
+ else
+ {
+ hasValue = false;
+ }
+ if (hasValue)
+ {
+ VendedorParcela vendedorParcela3 = x.First<VendedorParcela>();
+ if (vendedorParcela3 != null)
+ {
+ valorTotal = vendedorParcela3.get_ValorTotal();
+ num = new decimal();
+ flag = !((valorTotal.GetValueOrDefault() == num) & valorTotal.HasValue);
+ }
+ else
+ {
+ flag = true;
+ }
+ if (!flag)
+ {
+ goto Label1;
+ }
+ VendedorParcela vendedorParcela4 = x.First<VendedorParcela>();
+ if (vendedorParcela4 != null)
+ {
+ valorRepasse = vendedorParcela4.get_ValorTotal();
+ vendedorParcela.set_ValorTotal(valorRepasse);
+ vendedorParcela.set_Vendedor(x.First<VendedorParcela>().get_Vendedor());
+ vendedorParcela.set_PorcentagemRepasse(x.First<VendedorParcela>().get_PorcentagemRepasse());
+ vendedorParcela.set_TipoVendedor(x.First<VendedorParcela>().get_TipoVendedor());
+ vendedorParcela.set_CoCorretagem(x.First<VendedorParcela>().get_CoCorretagem());
+ return vendedorParcela;
+ }
+ else
+ {
+ valorTotal = null;
+ valorRepasse = valorTotal;
+ vendedorParcela.set_ValorTotal(valorRepasse);
+ vendedorParcela.set_Vendedor(x.First<VendedorParcela>().get_Vendedor());
+ vendedorParcela.set_PorcentagemRepasse(x.First<VendedorParcela>().get_PorcentagemRepasse());
+ vendedorParcela.set_TipoVendedor(x.First<VendedorParcela>().get_TipoVendedor());
+ vendedorParcela.set_CoCorretagem(x.First<VendedorParcela>().get_CoCorretagem());
+ return vendedorParcela;
+ }
+ }
+ Label1:
+ num = comissao;
+ valorTotal = x.First<VendedorParcela>().get_PorcentagemRepasse();
+ valorRepasse = (valorTotal.HasValue ? new decimal?((num * valorTotal.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2)) : null);
+ }
+ else
+ {
+ valorRepasse = x.First<VendedorParcela>().get_ValorRepasse();
+ }
+ vendedorParcela.set_ValorTotal(valorRepasse);
+ vendedorParcela.set_Vendedor(x.First<VendedorParcela>().get_Vendedor());
+ vendedorParcela.set_PorcentagemRepasse(x.First<VendedorParcela>().get_PorcentagemRepasse());
+ vendedorParcela.set_TipoVendedor(x.First<VendedorParcela>().get_TipoVendedor());
+ vendedorParcela.set_CoCorretagem(x.First<VendedorParcela>().get_CoCorretagem());
+ return vendedorParcela;
+ }).ToList<VendedorParcela>();
+ parcelas1 = (parcelas != null ? parcelas.Where<Parcela>((Parcela x) => {
+ if (x.get_SubTipo() != 1)
+ {
+ return false;
+ }
+ return x.get_NumeroParcela() < this.parcela.get_NumeroParcela();
+ }).ToList<Parcela>() : new List<Parcela>());
+ List<Parcela> parcelas3 = parcelas1;
+ list2.ForEach((VendedorParcela y) => {
+ VendedorParcela vendedorParcela = y;
+ decimal? valorTotal = y.get_ValorTotal();
+ IEnumerable<VendedorParcela> vendedorParcelas = repasses.Where<VendedorParcela>((VendedorParcela x) => {
+ bool valueOrDefault;
+ if (x.get_Parcela().get_SubTipo() == 1)
+ {
+ Repasse repasse = x.get_Repasse();
+ valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false);
+ if (valueOrDefault && x.get_Vendedor().get_Id() == y.get_Vendedor().get_Id())
+ {
+ List<Parcela> cSu0024u003cu003e8_locals2 = parcelas3;
+ Func<Parcela, long> u003cu003e9_912 = Funcoes.u003cu003ec.u003cu003e9__9_12;
+ if (u003cu003e9_912 == null)
+ {
+ u003cu003e9_912 = (Parcela z) => z.get_Id();
+ Funcoes.u003cu003ec.u003cu003e9__9_12 = u003cu003e9_912;
+ }
+ return cSu0024u003cu003e8_locals2.Select<Parcela, long>(u003cu003e9_912).ToList<long>().Contains(x.get_Parcela().get_Id());
+ }
+ }
+ return false;
+ });
+ Func<VendedorParcela, decimal?> u003cu003e9_911 = Funcoes.u003cu003ec.u003cu003e9__9_11;
+ if (u003cu003e9_911 == null)
+ {
+ u003cu003e9_911 = (VendedorParcela x) => x.get_ValorRepasse();
+ Funcoes.u003cu003ec.u003cu003e9__9_11 = u003cu003e9_911;
+ }
+ decimal? nullable = vendedorParcelas.Sum<VendedorParcela>(u003cu003e9_911);
+ vendedorParcela.set_ValorRepasse((valorTotal.HasValue & nullable.HasValue ? new decimal?(valorTotal.GetValueOrDefault() - nullable.GetValueOrDefault()) : null));
+ });
+ parcelas2 = (parcelas != null ? parcelas.Where<Parcela>((Parcela x) => {
+ if (x.get_SubTipo() != 1)
+ {
+ return false;
+ }
+ return x.get_NumeroParcela() > this.parcela.get_NumeroParcela();
+ }).ToList<Parcela>() : new List<Parcela>());
+ List<Parcela> list3 = parcelas2;
+ list3.Add(parcela2);
+ List<VendedorParcela> vendedorParcelas3 = repasses.Where<VendedorParcela>((VendedorParcela x) => {
+ bool valueOrDefault;
+ if (x.get_Parcela().get_SubTipo() == 1)
+ {
+ Repasse repasse = x.get_Repasse();
+ valueOrDefault = (repasse != null ? repasse.get_Forma().GetValueOrDefault() == 1 : false);
+ if (valueOrDefault)
+ {
+ if (x.get_Parcela().get_NumeroParcela() >= this.parcela.get_NumeroParcela())
+ {
+ return true;
+ }
+ return !x.get_DataPrePagamento().HasValue;
+ }
+ }
+ return false;
+ }).ToList<VendedorParcela>();
+ if (!await parcelaServico1.DeletePagamentoRange(vendedorParcelas3))
+ {
+ await Funcoes.MostrarErro(191);
+ parcela1 = parcela2;
+ variable = null;
+ parcelaServico1 = null;
+ parcelaServico = null;
+ vendedorServico = null;
+ return parcela1;
+ }
+ else if (await parcelaServico1.SaveRange(list2))
+ {
+ List<Parcela> parcelas4 = list3;
+ list3 = parcelas4.Where<Parcela>((Parcela dParcela) => {
+ if (dParcela.get_ValorComissao() != decimal.Zero || dParcela.get_ValorComissao() != decimal.Zero || dParcela.get_DataRecebimento().HasValue || dParcela.get_DataCredito().HasValue)
+ {
+ return true;
+ }
+ return dParcela.get_ValorRealizado() != decimal.Zero;
+ }).ToList<Parcela>();
+ if (list3 != null && list3.Count > 0)
+ {
+ list3.ForEach((Parcela dParcela) => {
+ dParcela.set_Documento(this.parcela.get_Documento());
+ dParcela.set_ValorComissao(decimal.Zero);
+ dParcela.set_ValorComDesconto(decimal.Zero);
+ DateTime? nullable = null;
+ dParcela.set_DataRecebimento(nullable);
+ nullable = null;
+ dParcela.set_DataCredito(nullable);
+ dParcela.set_ValorRealizado(decimal.Zero);
+ });
+ list3 = await parcelaServico1.UpdateRange(list3);
+ if (parcelaServico1.Sucesso)
+ {
+ parcela2 = list3.FirstOrDefault<Parcela>((Parcela x) => x.get_Id() == this.parcela.get_Id());
+ }
+ else
+ {
+ await Funcoes.MostrarErro(191);
+ parcela1 = parcela2;
+ variable = null;
+ parcelaServico1 = null;
+ parcelaServico = null;
+ vendedorServico = null;
+ return parcela1;
+ }
+ }
+ list2 = null;
+ list3 = null;
+ }
+ else
+ {
+ await Funcoes.MostrarErro(191);
+ parcela1 = parcela2;
+ variable = null;
+ parcelaServico1 = null;
+ parcelaServico = null;
+ vendedorServico = null;
+ return parcela1;
+ }
+ }
+ ApoliceServico apoliceServico = new ApoliceServico();
+ parcelaServico = new ParcelaServico();
+ vendedorServico = new VendedorServico();
+ if (parcela2 != null)
+ {
+ Documento documento = await apoliceServico.BuscarApoliceAsync(parcela2.get_Documento().get_Id(), false, false);
+ Documento documento1 = documento;
+ ObservableCollection<Parcela> observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id());
+ documento1.set_Parcelas(observableCollection);
+ documento1 = null;
+ List<VendedorParcela> vendedorParcelas4 = await vendedorServico.BuscaRepasse(documento.get_Id());
+ foreach (Parcela parcela4 in documento.get_Parcelas())
+ {
+ foreach (VendedorParcela vendedorParcela5 in vendedorParcelas4)
+ {
+ if (vendedorParcela5.get_Parcela().get_Id() != parcela4.get_Id())
+ {
+ continue;
+ }
+ if (parcela4.get_Vendedores() == null)
+ {
+ parcela4.set_Vendedores(new ObservableCollection<VendedorParcela>());
+ }
+ parcela4.get_Vendedores().Add(vendedorParcela5);
+ }
+ }
+ IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
+ RegistroLog registroLog = new RegistroLog();
+ registroLog.set_Acao(2);
+ registroLog.set_Usuario(Recursos.Usuario);
+ registroLog.set_DataHora(Funcoes.GetNetworkTime());
+ Documento documento2 = documento;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ registroLog.set_Descricao(JsonConvert.SerializeObject(documento2, jsonSerializerSetting));
+ registroLog.set_EntidadeId(documento.get_Id());
+ registroLog.set_Tela(2);
+ registroLog.set_NomeMaquina(Environment.MachineName);
+ registroLog.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] addressList = hostEntry.AddressList;
+ IPAddress pAddress = ((IEnumerable<IPAddress>)addressList).FirstOrDefault<IPAddress>((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork);
+ if (pAddress != null)
+ {
+ str = pAddress.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ registroLog.set_Ip(str);
+ RegistroLog registroLog1 = registroLog;
+ await Task.Run(() => {
+ using (UnitOfWork commited = Instancia.Commited)
+ {
+ commited.get_RegistroLogRepository().SaveOrUpdate(registroLog1);
+ commited.Commit();
+ }
+ });
+ documento = null;
+ }
+ parcela1 = parcela2;
+ variable = null;
+ parcelaServico1 = null;
+ parcelaServico = null;
+ vendedorServico = null;
+ return parcela1;
+ }
+
+ public static async Task<bool> ExcluirPagamento(VendedorParcela pagamento)
+ {
+ pagamento.set_DataPagamento(null);
+ ParcelaServico parcelaServico = new ParcelaServico()
+ {
+ Sucesso = true
+ };
+ await parcelaServico.Save(pagamento);
+ bool sucesso = parcelaServico.Sucesso;
+ parcelaServico = null;
+ return sucesso;
+ }
+
+ public static string ExportarHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "")
+ {
+ string str = string.Format("DATA DE EMISSÃO DO RELATÓRIO EM {0:G}", Funcoes.GetNetworkTime());
+ if (tipo.get_Inicio() != DateTime.MinValue && tipo.get_Nome() != "RELATÓRIO DE CLIENTE")
+ {
+ str = string.Format("PERÍODO DE {0:d} ATÉ {1:d}. DATA DE EMISSÃO DO RELATÓRIO EM {2:G}", tipo.get_Inicio(), tipo.get_Fim(), Funcoes.GetNetworkTime());
+ }
+ string str1 = (!search ? "<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}", str1).Replace("Orientation", orientation).Replace("{NomeRelatorio}", string.Concat(Recursos.Empresa.get_NomeSocial(), " - ", tipo.get_Nome())).Replace("{EmissaoRelatorio}", str).Replace("{Grafico}", grafico).Replace("{DadosRelatorio}", dados));
+ return stringBuilder.ToString();
+ }
+
+ public static string ExportarMultipleHtml(TipoRelatorio tipo, string dados, string porcentagem = "60", string orientation = "landscape", bool search = false, string grafico = "")
+ {
+ string str = string.Format("DATA DE EMISSÃO DO RELATÓRIO EM {0:G}", Funcoes.GetNetworkTime());
+ if (tipo.get_Inicio() != DateTime.MinValue && tipo.get_Nome() != "RELATÓRIO DE CLIENTE")
+ {
+ str = string.Format("PERÍODO DE {0:d} ATÉ {1:d}. DATA DE EMISSÃO DO RELATÓRIO EM {2:G}", tipo.get_Inicio(), tipo.get_Fim(), Funcoes.GetNetworkTime());
+ }
+ string str1 = (!search ? "<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}", str1).Replace("Orientation", orientation).Replace("{NomeRelatorio}", string.Concat(Recursos.Empresa.get_NomeSocial(), " - ", tipo.get_Nome())).Replace("{EmissaoRelatorio}", str).Replace("{Grafico}", grafico).Replace("{DadosRelatorio}", dados));
+ return stringBuilder.ToString();
+ }
+
+ public static async Task<string> GenerateMultipleTable(List<List<Listagem>> analiticos, List<string> colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null)
+ {
+ string str4;
+ string str5;
+ Action<Listagem> action2 = null;
+ if (analiticos == null)
+ {
+ str4 = "";
+ }
+ else if (analiticos.Count != 0)
+ {
+ int tamanhoFonte = 0;
+ if (config != null)
+ {
+ tamanhoFonte = config.get_TamanhoFonte();
+ }
+ str5 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte));
+ string str6 = str5;
+ str4 = await Task.Run<string>(() => {
+ StringBuilder stringBuilder2 = new StringBuilder();
+ int num = 0;
+ foreach (List<Listagem> analitico in analiticos)
+ {
+ StringBuilder stringBuilder3 = new StringBuilder();
+ StringBuilder stringBuilder4 = new StringBuilder();
+ StringBuilder stringBuilder5 = new StringBuilder();
+ int num1 = 0;
+ stringBuilder4.Append(Resources.HeaderTemplate.Replace("{Align}", "text-start").Replace("{Size}", "").Replace("{FontWeight}", "fw-bold").Replace("{Content}", analitico[0].get_NomeRelatorio()));
+ stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", ""));
+ List<Listagem> listagems = analitico;
+ Action<Listagem> u003cu003e9_1 = action2;
+ if (u003cu003e9_1 == null)
+ {
+ Action<Listagem> action = (Listagem x) => {
+ Sinal sinal;
+ string str;
+ char chr;
+ string str1;
+ PropertyInfo[] properties = x.GetType().GetProperties();
+ Func<PropertyInfo, bool> u003cu003e9_222 = Funcoes.u003cu003ec.u003cu003e9__22_2;
+ if (u003cu003e9_222 == null)
+ {
+ u003cu003e9_222 = (PropertyInfo b) => b.Name == "Bold";
+ Funcoes.u003cu003ec.u003cu003e9__22_2 = u003cu003e9_222;
+ }
+ PropertyInfo propertyInfo = ((IEnumerable<PropertyInfo>)properties).FirstOrDefault<PropertyInfo>(u003cu003e9_222);
+ bool flag = (propertyInfo == null ? false : (bool)propertyInfo.GetValue(x));
+ Func<PropertyInfo, bool> u003cu003e9_223 = Funcoes.u003cu003ec.u003cu003e9__22_3;
+ if (u003cu003e9_223 == null)
+ {
+ u003cu003e9_223 = (PropertyInfo b) => b.Name == "Sinal";
+ Funcoes.u003cu003ec.u003cu003e9__22_3 = u003cu003e9_223;
+ }
+ PropertyInfo propertyInfo1 = ((IEnumerable<PropertyInfo>)properties).FirstOrDefault<PropertyInfo>(u003cu003e9_223);
+ string str2 = (!(propertyInfo1 != null) || propertyInfo1.GetValue(x) == null || !Enum.TryParse<Sinal>(propertyInfo1.GetValue(x).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;");
+ if (flag)
+ {
+ string.Concat("<tr style='font-weight: bold; ", str2, "'>");
+ }
+ else
+ {
+ string.Concat("<tr style='", str2, "'>");
+ }
+ StringBuilder stringBuilder = new StringBuilder();
+ PropertyInfo[] propertyInfoArray = properties;
+ for (int i = 0; i < (int)propertyInfoArray.Length; i++)
+ {
+ PropertyInfo propertyInfo2 = propertyInfoArray[i];
+ if (propertyInfo2.Name != "ValidationEvent")
+ {
+ object obj = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj != null)
+ {
+ string description = ((DescriptionAttribute)obj).Description;
+ if ((!propertyName || !colunasOcultas.Contains(propertyInfo2.Name)) && (propertyName || !colunasOcultas.Contains(description)))
+ {
+ object obj1 = propertyInfo2.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault<object>();
+ string description1 = "";
+ if (obj1 != null)
+ {
+ description1 = ((TipoAttribute)obj1).get_Description();
+ }
+ string str3 = "text-start";
+ if (description1 != null)
+ {
+ switch (description1.Length)
+ {
+ case 4:
+ {
+ chr = description1[0];
+ if (chr == 'D')
+ {
+ if (description1 == "DATA")
+ {
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) == null || (DateTime)propertyInfo2.GetValue(x) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo2.GetValue(x)));
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ else if (chr != 'E')
+ {
+ goto Label1;
+ }
+ else if (description1 == "ENUM")
+ {
+ str = (propertyInfo2.GetValue(x) != null ? Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo2.GetValue(x)) ?? "" : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ case 5:
+ {
+ chr = description1[0];
+ if (chr == 'D')
+ {
+ if (description1 == "DATA?")
+ {
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:d}", (DateTime?)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ else if (chr != 'V')
+ {
+ goto Label1;
+ }
+ else if (description1 == "VALOR")
+ {
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ case 6:
+ {
+ if (description1 != "VALOR?")
+ {
+ goto Label1;
+ }
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal?)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ case 9:
+ {
+ if (description1 == "DATA/TIME")
+ {
+ break;
+ }
+ goto Label1;
+ }
+ case 10:
+ {
+ chr = description1[0];
+ if (chr == 'D')
+ {
+ if (description1 == "DATA/TIME?")
+ {
+ break;
+ }
+ goto Label1;
+ }
+ else if (chr == 'P')
+ {
+ if (description1 == "PERCENTUAL")
+ {
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:p2}", (decimal)propertyInfo2.GetValue(x) * new decimal(1, 0, 0, false, 2)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ else if (chr != 'Q')
+ {
+ goto Label1;
+ }
+ else if (description1 == "QUANTIDADE")
+ {
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ default:
+ {
+ goto Label1;
+ }
+ }
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:G}", (DateTime?)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ Label1:
+ str1 = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : "");
+ str = str1;
+ Label0:
+ StringBuilder stringBuilder1 = stringBuilder;
+ stringBuilder1.Append(Resources.ColumnTemplate.Replace("{Align}", str3).Replace("{Size}", str6).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", str));
+ }
+ }
+ }
+ }
+ };
+ Action<Listagem> action1 = action;
+ action2 = action;
+ u003cu003e9_1 = action1;
+ }
+ listagems.ForEach(u003cu003e9_1);
+ StringBuilder stringBuilder6 = new StringBuilder();
+ if (grafico)
+ {
+ stringBuilder5.Append(string.Format("<div id=\"donutchart{0}\" style=\"width: 70%; height: 125px;\"></div>", num));
+ }
+ num++;
+ stringBuilder6.Append(Resources.TableMultipleTemplate.Replace("{Head}", stringBuilder3.ToString()).Replace("{Body}", stringBuilder5.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("<tr><td colspan='{0}' style='color:gray'>{1}</td></tr>", num1, footer)) : "")));
+ stringBuilder2.Append(stringBuilder6.ToString());
+ }
+ return stringBuilder2.ToString();
+ });
+ }
+ else
+ {
+ str4 = "";
+ }
+ return str4;
+ }
+
+ public static async Task<string> GenerateTable<T>(List<T> analitico, List<string> colunasOcultas, bool grafico = false, bool propertyName = false, string footer = "", ConfiguracaoImpressao config = null)
+ {
+ string str7;
+ string str8;
+ if (analitico == null)
+ {
+ str7 = "";
+ }
+ else if (analitico.Count != 0)
+ {
+ int tamanhoFonte = 0;
+ if (config != null)
+ {
+ tamanhoFonte = config.get_TamanhoFonte();
+ }
+ str8 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte));
+ string str9 = str8;
+ str7 = await Task.Run<string>(() => {
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder stringBuilder3 = new StringBuilder();
+ StringBuilder stringBuilder4 = new StringBuilder();
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties = type.GetProperties();
+ int num = 0;
+ PropertyInfo[] propertyInfoArray3 = properties;
+ for (int i1 = 0; i1 < (int)propertyInfoArray3.Length; i1++)
+ {
+ PropertyInfo propertyInfo3 = propertyInfoArray3[i1];
+ if (propertyInfo3.Name != "ValidationEvent")
+ {
+ object obj2 = propertyInfo3.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj2 != null)
+ {
+ string str4 = ((DescriptionAttribute)obj2).Description;
+ if ((!propertyName || !colunasOcultas.Contains(propertyInfo3.Name)) && (propertyName || !colunasOcultas.Contains(str4)))
+ {
+ object obj3 = propertyInfo3.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault<object>();
+ string str5 = "";
+ if (obj3 != null)
+ {
+ str5 = ((TipoAttribute)obj3).get_Description();
+ }
+ string str6 = "text-start";
+ if (str5 == "PERCENTUAL" || str5 == "VALOR")
+ {
+ str6 = "text-center";
+ }
+ else if (str5 == "QUANTIDADE" || str5 == "DATA")
+ {
+ str6 = "text-end";
+ }
+ stringBuilder3.Append(Resources.HeaderTemplate.Replace("{Align}", str6).Replace("{Size}", str9).Replace("{FontWeight}", "fw-bold").Replace("{Content}", str4));
+ num++;
+ }
+ }
+ }
+ }
+ stringBuilder2.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder3.ToString()).Replace("{Color}", ""));
+ analitico.ForEach((T x) => {
+ Sinal sinal;
+ string str;
+ char chr;
+ string str1;
+ type = x.GetType();
+ properties = type.GetProperties();
+ PropertyInfo[] propertyInfoArray = properties;
+ Func<PropertyInfo, bool> u003cu003e9_212 = Funcoes.u003cu003ec__21<T>.u003cu003e9__21_2;
+ if (u003cu003e9_212 == null)
+ {
+ u003cu003e9_212 = (PropertyInfo b) => b.Name == "Bold";
+ Funcoes.u003cu003ec__21<T>.u003cu003e9__21_2 = u003cu003e9_212;
+ }
+ PropertyInfo propertyInfo = ((IEnumerable<PropertyInfo>)propertyInfoArray).FirstOrDefault<PropertyInfo>(u003cu003e9_212);
+ bool flag = (propertyInfo == null ? false : (bool)propertyInfo.GetValue(x));
+ PropertyInfo[] propertyInfoArray1 = properties;
+ Func<PropertyInfo, bool> u003cu003e9_213 = Funcoes.u003cu003ec__21<T>.u003cu003e9__21_3;
+ if (u003cu003e9_213 == null)
+ {
+ u003cu003e9_213 = (PropertyInfo b) => b.Name == "Sinal";
+ Funcoes.u003cu003ec__21<T>.u003cu003e9__21_3 = u003cu003e9_213;
+ }
+ PropertyInfo propertyInfo1 = ((IEnumerable<PropertyInfo>)propertyInfoArray1).FirstOrDefault<PropertyInfo>(u003cu003e9_213);
+ string str2 = (!(propertyInfo1 != null) || propertyInfo1.GetValue(x) == null || !Enum.TryParse<Sinal>(propertyInfo1.GetValue(x).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;");
+ if (flag)
+ {
+ string.Concat("<tr style='font-weight: bold; ", str2, "'>");
+ }
+ else
+ {
+ string.Concat("<tr style='", str2, "'>");
+ }
+ StringBuilder stringBuilder = new StringBuilder();
+ PropertyInfo[] propertyInfoArray2 = properties;
+ for (int i = 0; i < (int)propertyInfoArray2.Length; i++)
+ {
+ PropertyInfo propertyInfo2 = propertyInfoArray2[i];
+ if (propertyInfo2.Name != "ValidationEvent")
+ {
+ object obj = propertyInfo2.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj != null)
+ {
+ string description = ((DescriptionAttribute)obj).Description;
+ if ((!propertyName || !colunasOcultas.Contains(propertyInfo2.Name)) && (propertyName || !colunasOcultas.Contains(description)))
+ {
+ object obj1 = propertyInfo2.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault<object>();
+ string description1 = "";
+ if (obj1 != null)
+ {
+ description1 = ((TipoAttribute)obj1).get_Description();
+ }
+ string str3 = "text-start";
+ if (description1 != null)
+ {
+ switch (description1.Length)
+ {
+ case 4:
+ {
+ chr = description1[0];
+ if (chr == 'D')
+ {
+ if (description1 == "DATA")
+ {
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) == null || (DateTime)propertyInfo2.GetValue(x) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo2.GetValue(x)));
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ else if (chr != 'E')
+ {
+ goto Label1;
+ }
+ else if (description1 == "ENUM")
+ {
+ str = (propertyInfo2.GetValue(x) != null ? Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo2.GetValue(x)) ?? "" : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ case 5:
+ {
+ chr = description1[0];
+ if (chr == 'D')
+ {
+ if (description1 == "DATA?")
+ {
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:d}", (DateTime?)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ else if (chr != 'V')
+ {
+ goto Label1;
+ }
+ else if (description1 == "VALOR")
+ {
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ case 6:
+ {
+ if (description1 != "VALOR?")
+ {
+ goto Label1;
+ }
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:c2}", (decimal?)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ case 9:
+ {
+ if (description1 == "DATA/TIME")
+ {
+ break;
+ }
+ goto Label1;
+ }
+ case 10:
+ {
+ chr = description1[0];
+ if (chr == 'D')
+ {
+ if (description1 == "DATA/TIME?")
+ {
+ break;
+ }
+ goto Label1;
+ }
+ else if (chr == 'P')
+ {
+ if (description1 == "PERCENTUAL")
+ {
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:p2}", (decimal)propertyInfo2.GetValue(x) * new decimal(1, 0, 0, false, 2)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ else if (chr != 'Q')
+ {
+ goto Label1;
+ }
+ else if (description1 == "QUANTIDADE")
+ {
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ case 13:
+ {
+ if (description1 == "VALORDECIMAL2")
+ {
+ str3 = "text-end";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:n2}", (decimal)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ else
+ {
+ goto Label1;
+ }
+ }
+ default:
+ {
+ goto Label1;
+ }
+ }
+ str3 = "text-center";
+ str = (propertyInfo2.GetValue(x) != null ? string.Format("{0:G}", (DateTime?)propertyInfo2.GetValue(x)) : "");
+ goto Label0;
+ }
+ Label1:
+ str1 = (propertyInfo2.GetValue(x) != null ? string.Format("{0}", propertyInfo2.GetValue(x)) : "");
+ str = str1;
+ Label0:
+ StringBuilder stringBuilder1 = stringBuilder;
+ stringBuilder1.Append(Resources.ColumnTemplate.Replace("{Align}", str3).Replace("{Size}", str9).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", str));
+ }
+ }
+ }
+ }
+ stringBuilder4.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder.ToString()).Replace("{Color}", string.Concat("style='", str2, "'")));
+ });
+ StringBuilder stringBuilder5 = new StringBuilder();
+ if (grafico)
+ {
+ stringBuilder4.Append("<td>");
+ stringBuilder4.Append("<div id=\"donutchart\" style=\"width: 500px; height: 300px;\"></div>");
+ stringBuilder4.Append("<h6 style='text-align:center'>*VALORES NEGATIVOS NÃO SÃO REPRESENTADOS NO GRÁFICO DE PIZZA.</h6>");
+ stringBuilder4.Append("</td>");
+ }
+ stringBuilder5.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder2.ToString()).Replace("{Body}", stringBuilder4.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("<tr><td colspan='{0}' style='color:gray'>{1}</td></tr>", num, footer)) : "")));
+ return stringBuilder5.ToString();
+ });
+ }
+ else
+ {
+ str7 = "";
+ }
+ return str7;
+ }
+
+ public static async Task<string> GenerateTable<T>(List<T> analitico, Relatorio relatorio, bool grafico = false, bool verificarColunas = true, string footer = "", ConfiguracaoImpressao config = null)
+ {
+ string str6;
+ List<ParametrosRelatorio> restricoesColunas;
+ string str7;
+ List<ParametrosRelatorio> campos;
+ int tamanhoFonte = 0;
+ if (config != null)
+ {
+ campos = config.get_Campos();
+ tamanhoFonte = config.get_TamanhoFonte();
+ }
+ else
+ {
+ if (!verificarColunas)
+ {
+ restricoesColunas = null;
+ }
+ else
+ {
+ restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio);
+ }
+ campos = restricoesColunas;
+ if (campos == null || campos.Count == 0)
+ {
+ PropertyInfo[] propertyInfoArray2 = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ campos = propertyInfoArray2.Select<PropertyInfo, ParametrosRelatorio>((PropertyInfo x) => {
+ ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio();
+ parametrosRelatorio.set_Campo(x.Name);
+ parametrosRelatorio.set_Header(x.GetDescriptionAttribute());
+ parametrosRelatorio.set_Tipo(x.GetTypeAttribute());
+ parametrosRelatorio.set_Relatorio(relatorio);
+ parametrosRelatorio.set_Width(0);
+ parametrosRelatorio.set_Ordem(0);
+ return parametrosRelatorio;
+ }).ToList<ParametrosRelatorio>();
+ }
+ }
+ str7 = (tamanhoFonte == 0 ? "" : string.Format("fs-{0}'", tamanhoFonte));
+ string str8 = str7;
+ restricoesColunas = await Funcoes.GetRestricoesColunas(campos);
+ campos = restricoesColunas;
+ if (analitico == null)
+ {
+ str6 = "";
+ }
+ else if (analitico.Count != 0)
+ {
+ str6 = await Task.Run<string>(() => {
+ StringBuilder stringBuilder3 = new StringBuilder();
+ StringBuilder stringBuilder4 = new StringBuilder();
+ StringBuilder stringBuilder5 = new StringBuilder();
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties = type.GetProperties();
+ int num = 0;
+ List<ParametrosRelatorio> parametrosRelatorios1 = campos;
+ Func<ParametrosRelatorio, int> u003cu003e9_242 = Funcoes.u003cu003ec__24<T>.u003cu003e9__24_2;
+ if (u003cu003e9_242 == null)
+ {
+ u003cu003e9_242 = (ParametrosRelatorio x) => x.get_Ordem();
+ Funcoes.u003cu003ec__24<T>.u003cu003e9__24_2 = u003cu003e9_242;
+ }
+ IOrderedEnumerable<ParametrosRelatorio> parametrosRelatorios2 = parametrosRelatorios1.OrderBy<ParametrosRelatorio, int>(u003cu003e9_242);
+ Func<ParametrosRelatorio, string> u003cu003e9_243 = Funcoes.u003cu003ec__24<T>.u003cu003e9__24_3;
+ if (u003cu003e9_243 == null)
+ {
+ u003cu003e9_243 = (ParametrosRelatorio x) => x.get_Header();
+ Funcoes.u003cu003ec__24<T>.u003cu003e9__24_3 = u003cu003e9_243;
+ }
+ ExtensionMethods.ForEach<ParametrosRelatorio>(parametrosRelatorios2.ThenBy<ParametrosRelatorio, string>(u003cu003e9_243), (ParametrosRelatorio x) => {
+ if (x.get_Tipo() == "INVALID")
+ {
+ return;
+ }
+ PropertyInfo propertyInfo = properties.FirstOrDefault<PropertyInfo>((PropertyInfo p) => p.Name == x.get_Campo());
+ if (propertyInfo == null)
+ {
+ return;
+ }
+ string descriptionAttribute = propertyInfo.GetDescriptionAttribute();
+ string str = "text-start";
+ string tipo = x.get_Tipo();
+ if (tipo == "PERCENTUAL" || tipo == "VALOR")
+ {
+ str = "text-center";
+ }
+ else if (tipo == "QUANTIDADE" || tipo == "DATA")
+ {
+ str = "text-end";
+ }
+ stringBuilder4.Append(Resources.HeaderTemplate.Replace("{Align}", str).Replace("{Size}", str8).Replace("{FontWeight}", "fw-bold").Replace("{Content}", descriptionAttribute));
+ num++;
+ });
+ stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", ""));
+ analitico.ForEach((T a) => {
+ Sinal sinal;
+ StringBuilder stringBuilder2 = new StringBuilder();
+ type = a.GetType();
+ properties = type.GetProperties();
+ PropertyInfo[] propertyInfoArray = properties;
+ Func<PropertyInfo, bool> u003cu003e9_247 = Funcoes.u003cu003ec__24<T>.u003cu003e9__24_7;
+ if (u003cu003e9_247 == null)
+ {
+ u003cu003e9_247 = (PropertyInfo b) => b.Name == "Bold";
+ Funcoes.u003cu003ec__24<T>.u003cu003e9__24_7 = u003cu003e9_247;
+ }
+ PropertyInfo propertyInfo1 = ((IEnumerable<PropertyInfo>)propertyInfoArray).FirstOrDefault<PropertyInfo>(u003cu003e9_247);
+ bool flag = (propertyInfo1 == null ? false : (bool)propertyInfo1.GetValue(a));
+ PropertyInfo[] propertyInfoArray1 = properties;
+ Func<PropertyInfo, bool> u003cu003e9_248 = Funcoes.u003cu003ec__24<T>.u003cu003e9__24_8;
+ if (u003cu003e9_248 == null)
+ {
+ u003cu003e9_248 = (PropertyInfo b) => b.Name == "Sinal";
+ Funcoes.u003cu003ec__24<T>.u003cu003e9__24_8 = u003cu003e9_248;
+ }
+ PropertyInfo propertyInfo2 = ((IEnumerable<PropertyInfo>)propertyInfoArray1).FirstOrDefault<PropertyInfo>(u003cu003e9_248);
+ string str5 = (!(propertyInfo2 != null) || propertyInfo2.GetValue(a) == null || !Enum.TryParse<Sinal>(propertyInfo2.GetValue(a).ToString(), true, out sinal) || sinal != 1 ? "color: black;" : "color: red;");
+ if (flag)
+ {
+ string.Concat("<tr class='fw-bold' style='", str5, "'>");
+ }
+ else
+ {
+ string.Concat("<tr style='", str5, "'>");
+ }
+ List<ParametrosRelatorio> cSu0024u003cu003e8_locals1 = campos;
+ Func<ParametrosRelatorio, int> u003cu003e9_249 = Funcoes.u003cu003ec__24<T>.u003cu003e9__24_9;
+ if (u003cu003e9_249 == null)
+ {
+ u003cu003e9_249 = (ParametrosRelatorio x) => x.get_Ordem();
+ Funcoes.u003cu003ec__24<T>.u003cu003e9__24_9 = u003cu003e9_249;
+ }
+ IOrderedEnumerable<ParametrosRelatorio> parametrosRelatorios = cSu0024u003cu003e8_locals1.OrderBy<ParametrosRelatorio, int>(u003cu003e9_249);
+ Func<ParametrosRelatorio, string> u003cu003e9_2410 = Funcoes.u003cu003ec__24<T>.u003cu003e9__24_10;
+ if (u003cu003e9_2410 == null)
+ {
+ u003cu003e9_2410 = (ParametrosRelatorio x) => x.get_Header();
+ Funcoes.u003cu003ec__24<T>.u003cu003e9__24_10 = u003cu003e9_2410;
+ }
+ ExtensionMethods.ForEach<ParametrosRelatorio>(parametrosRelatorios.ThenBy<ParametrosRelatorio, string>(u003cu003e9_2410), (ParametrosRelatorio x) => {
+ string str;
+ char chr;
+ string str1;
+ string str2;
+ string str3;
+ StringBuilder stringBuilder;
+ StringBuilder stringBuilder1;
+ if (x.get_Tipo() == "INVALID")
+ {
+ return;
+ }
+ PropertyInfo propertyInfo = properties.FirstOrDefault<PropertyInfo>((PropertyInfo p) => p.Name == x.get_Campo());
+ if (propertyInfo == null)
+ {
+ return;
+ }
+ string str4 = "text-start";
+ string tipo = x.get_Tipo();
+ if (tipo != null)
+ {
+ switch (tipo.Length)
+ {
+ case 4:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA")
+ {
+ str4 = "text-center";
+ str = (propertyInfo.GetValue(a) == null || (DateTime)propertyInfo.GetValue(a) == DateTime.MinValue ? "" : string.Format("{0:d}", (DateTime)propertyInfo.GetValue(a)));
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ else if (chr != 'E')
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else if (tipo == "ENUM")
+ {
+ str = (propertyInfo.GetValue(a) == null || Convert.ToInt32(propertyInfo.GetValue(a)) == 0 ? "" : Gestor.Common.Validation.ValidationHelper.GetDescription((Enum)propertyInfo.GetValue(a)) ?? "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ case 5:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA?")
+ {
+ str4 = "text-center";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0:d}", (DateTime?)propertyInfo.GetValue(a)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ else if (chr != 'V')
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else if (tipo == "VALOR")
+ {
+ str4 = "text-end";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0:c2}", (decimal)propertyInfo.GetValue(a)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ case 6:
+ {
+ if (tipo != "VALOR?")
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ str4 = "text-end";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0:c2}", (decimal?)propertyInfo.GetValue(a)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ case 7:
+ case 8:
+ case 11:
+ case 12:
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ case 9:
+ {
+ if (tipo == "DATA/TIME")
+ {
+ break;
+ }
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ case 10:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA/TIME?")
+ {
+ break;
+ }
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else if (chr == 'P')
+ {
+ if (tipo == "PERCENTUAL")
+ {
+ str4 = "text-end";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0:p2}", (decimal)propertyInfo.GetValue(a) * new decimal(1, 0, 0, false, 2)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ else if (chr != 'Q')
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else if (tipo == "QUANTIDADE")
+ {
+ str4 = "text-center";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ case 13:
+ {
+ if (tipo == "VALORDECIMAL2")
+ {
+ str4 = "text-end";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0:n2}", (decimal)propertyInfo.GetValue(a)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ else
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ default:
+ {
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ }
+ str4 = "text-center";
+ str = (propertyInfo.GetValue(a) != null ? string.Format("{0:G}", (DateTime?)propertyInfo.GetValue(a)) : "");
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ return;
+ }
+ str1 = (propertyInfo.GetValue(a) != null ? string.Format("{0}", propertyInfo.GetValue(a)) : "");
+ str = str1;
+ stringBuilder = stringBuilder2;
+ str2 = Resources.ColumnTemplate.Replace("{Align}", str4).Replace("{Size}", str8);
+ str3 = (flag ? "fw-bold" : "");
+ stringBuilder1 = stringBuilder.Append(str2.Replace("{FontWeight}", str3).Replace("{Content}", str));
+ });
+ stringBuilder5.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", string.Concat("style='", str5, "'")));
+ });
+ StringBuilder stringBuilder6 = new StringBuilder();
+ stringBuilder6.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder3.ToString()).Replace("{Body}", stringBuilder5.ToString()).Replace("{Footer}", (!string.IsNullOrEmpty(footer) ? Resources.FooterTemplate.Replace("{Content}", string.Format("<tr><td colspan='{0}' style='color:gray'>{1}</td></tr>", num, footer)) : "")));
+ return stringBuilder6.ToString();
+ });
+ }
+ else
+ {
+ str6 = "";
+ }
+ return str6;
+ }
+
+ public static async Task<string> GenerateTableSintetic(List<SinteticModel> sintetic, int fontSize = 0)
+ {
+ string str;
+ string str1;
+ if (sintetic == null || sintetic.Count == 0)
+ {
+ str = "";
+ }
+ else
+ {
+ str1 = (fontSize == 0 ? "" : string.Format("fs-{0}'", fontSize));
+ string str2 = str1;
+ str = await Task.Run<string>(() => {
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder stringBuilder1 = new StringBuilder();
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder stringBuilder3 = new StringBuilder();
+ StringBuilder stringBuilder4 = new StringBuilder();
+ sintetic.ForEach((SinteticModel x) => {
+ stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "fw-bold").Replace("{Content}", x.get_Hint()));
+ stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "").Replace("{Content}", (x.get_Value() == null ? "" : x.get_Value().ToString())));
+ });
+ stringBuilder1.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", ""));
+ stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", ""));
+ stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder1.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", ""));
+ return stringBuilder.ToString();
+ });
+ }
+ return str;
+ }
+
+ public static async Task<string> GenerateTableSintetic(List<SinteticModelList> sintetic, int fontSize = 0)
+ {
+ string str;
+ string str1;
+ if (sintetic == null || sintetic.Count == 0)
+ {
+ str = "";
+ }
+ else
+ {
+ str1 = (fontSize == 0 ? "" : string.Format("fs-{0}'", fontSize));
+ string str2 = str1;
+ str = await Task.Run<string>(() => {
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder stringBuilder1 = new StringBuilder();
+ StringBuilder stringBuilder2 = new StringBuilder();
+ StringBuilder stringBuilder3 = new StringBuilder();
+ sintetic.ForEach((SinteticModelList x) => stringBuilder2.Append(Resources.HeaderTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", "fw-bold").Replace("{Content}", x.get_Hint())));
+ stringBuilder1.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder2.ToString()).Replace("{Color}", ""));
+ for (int i = 0; i < sintetic.First<SinteticModelList>().get_Value().Count; i++)
+ {
+ StringBuilder stringBuilder4 = new StringBuilder();
+ bool flag = false;
+ foreach (SinteticModelList sinteticModelList in sintetic)
+ {
+ flag = (flag ? true : (sinteticModelList.get_Value()[0] == null ? false : sinteticModelList.get_Value()[i].ToString() == "TOTAL"));
+ stringBuilder4.Append(Resources.ColumnTemplate.Replace("{Align}", "text-center").Replace("{Size}", str2).Replace("{FontWeight}", (flag ? "fw-bold" : "")).Replace("{Content}", string.Format("{0}", sinteticModelList.get_Value()[i])));
+ }
+ stringBuilder3.Append(Resources.RowTemplate.Replace("{Content}", stringBuilder4.ToString()).Replace("{Color}", ""));
+ }
+ stringBuilder.Append(Resources.TableTemplate.Replace("{Head}", stringBuilder1.ToString()).Replace("{Body}", stringBuilder3.ToString()).Replace("{Footer}", ""));
+ return stringBuilder.ToString();
+ });
+ }
+ return str;
+ }
+
+ public static string GeraAssistencia(this long id)
+ {
+ string str;
+ try
+ {
+ DateTime now = DateTime.Now;
+ str = HttpUtility.UrlEncode(string.Format("{0}:{1}:A:{2}", now.Ticks, ApplicationHelper.IdFornecedor, id).Base64Encode());
+ }
+ catch
+ {
+ return "";
+ }
+ return str;
+ }
+
+ public static string GeraCartaoVisita(this long id)
+ {
+ string str;
+ try
+ {
+ DateTime now = DateTime.Now;
+ str = HttpUtility.UrlEncode(string.Format("{0}:{1}:V:{2}", now.Ticks, ApplicationHelper.IdFornecedor, id).Base64Encode());
+ }
+ catch
+ {
+ return "";
+ }
+ return str;
+ }
+
+ public static async Task<string> GerarCsv<T>(List<T> Conteudo, IEnumerable<string> colunasExportacao)
+ {
+ PropertyInfo[] array = (
+ from in typeof(T).GetProperties()
+ where colunasExportacao.Contains<string>(p.Name)
+ select ).ToArray<PropertyInfo>();
+ StringBuilder stringBuilder = new StringBuilder();
+ StringBuilder stringBuilder1 = stringBuilder;
+ PropertyInfo[] propertyInfoArray = array;
+ stringBuilder1.AppendLine(string.Join(";",
+ from in (IEnumerable<PropertyInfo>)propertyInfoArray
+ select p.Name));
+ foreach (T conteudo in Conteudo)
+ {
+ IEnumerable<string> strs = array.Select<PropertyInfo, string>((PropertyInfo p) => {
+ object str;
+ object value = p.GetValue(conteudo, null);
+ if (value != null)
+ {
+ str = value.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ if (str == null)
+ {
+ str = string.Empty;
+ }
+ return str;
+ });
+ stringBuilder.AppendLine(string.Join(";", strs));
+ }
+ return stringBuilder.ToString();
+ }
+
+ public static string GerarGrafico(List<ValorSintetico> sinteticoLista)
+ {
+ string str = "['NOME', 'VALOR'], ";
+ sinteticoLista.ForEach((ValorSintetico x) => {
+ if (x.get_Indice() != "TOTAL" && x.get_Valor() > decimal.Zero)
+ {
+ string[] indice = new string[] { str, "[`", x.get_Indice(), " ", x.get_Porcentagem(), "`, ", null, null };
+ indice[6] = x.get_Valor().ToString("F2", CultureInfo.InvariantCulture);
+ indice[7] = "], ";
+ str = string.Concat(indice);
+ }
+ });
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.Append("<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(string.Concat("var data = google.visualization.arrayToDataTable([", str, "]);"));
+ 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 str1 = "['NOME', 'VALOR'], ";
+ sinteticosLista.ForEach((ValorSintetico x) => {
+ if (x.get_Indice() != "TOTAL")
+ {
+ string str = string.Format("{0}", x.get_Valor());
+ if (x.get_Unidate() != null && x.get_Unidate().Equals("R$"))
+ {
+ str = string.Format("{0:c2}", x.get_Valor());
+ }
+ string[] indice = new string[] { str1, "[`", x.get_Indice(), " \n", str, "\n", x.get_Porcentagem(), "`, ", null, null };
+ indice[8] = x.get_Valor().ToString("F2", CultureInfo.InvariantCulture);
+ indice[9] = "], ";
+ str1 = string.Concat(indice);
+ }
+ });
+ stringBuilder.Append(string.Concat("data = google.visualization.arrayToDataTable([", str1, "]);"));
+ stringBuilder.Append(string.Format("chart = new google.visualization.PieChart(document.getElementById('donutchart{0}'));", num));
+ stringBuilder.Append("chart.draw(data, options);");
+ num++;
+ }
+ stringBuilder.Append("}");
+ stringBuilder.Append("</script>");
+ return stringBuilder.ToString();
+ }
+
+ public static async Task<XLWorkbook> GerarXls<T>(XLWorkbook xlWorkbook, string nome, List<T> analitico, Relatorio relatorio, bool verificarColunas = true)
+ {
+ List<ParametrosRelatorio> restricoesColunas;
+ string str = nome;
+ str = str.ValidaNomePlanilha("", 0);
+ if (!verificarColunas)
+ {
+ restricoesColunas = null;
+ }
+ else
+ {
+ restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio);
+ }
+ List<ParametrosRelatorio> list = restricoesColunas;
+ if (list == null || list.Count == 0)
+ {
+ PropertyInfo[] propertyInfoArray = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ list = propertyInfoArray.Select<PropertyInfo, ParametrosRelatorio>((PropertyInfo x) => {
+ ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio();
+ parametrosRelatorio.set_Campo(x.Name);
+ parametrosRelatorio.set_Header(x.GetDescriptionAttribute());
+ parametrosRelatorio.set_Tipo(x.GetTypeAttribute());
+ parametrosRelatorio.set_Relatorio(relatorio);
+ parametrosRelatorio.set_Width(0);
+ parametrosRelatorio.set_Ordem(0);
+ return parametrosRelatorio;
+ }).ToList<ParametrosRelatorio>();
+ }
+ restricoesColunas = await Funcoes.GetRestricoesColunas(list);
+ list = restricoesColunas;
+ XLWorkbook xLWorkbook1 = await Task.Run<XLWorkbook>(() => {
+ XLWorkbook xLWorkbook;
+ try
+ {
+ IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(str);
+ PropertyInfo[] properties = analitico[0].GetType().GetProperties();
+ int num1 = 1;
+ List<ParametrosRelatorio> parametrosRelatorios1 = list;
+ Func<ParametrosRelatorio, int> u003cu003e9_252 = Funcoes.u003cu003ec__25<T>.u003cu003e9__25_2;
+ if (u003cu003e9_252 == null)
+ {
+ u003cu003e9_252 = (ParametrosRelatorio x) => x.get_Ordem();
+ Funcoes.u003cu003ec__25<T>.u003cu003e9__25_2 = u003cu003e9_252;
+ }
+ IOrderedEnumerable<ParametrosRelatorio> parametrosRelatorios2 = parametrosRelatorios1.OrderBy<ParametrosRelatorio, int>(u003cu003e9_252);
+ Func<ParametrosRelatorio, string> u003cu003e9_253 = Funcoes.u003cu003ec__25<T>.u003cu003e9__25_3;
+ if (u003cu003e9_253 == null)
+ {
+ u003cu003e9_253 = (ParametrosRelatorio x) => x.get_Header();
+ Funcoes.u003cu003ec__25<T>.u003cu003e9__25_3 = u003cu003e9_253;
+ }
+ ExtensionMethods.ForEach<ParametrosRelatorio>(parametrosRelatorios2.ThenBy<ParametrosRelatorio, string>(u003cu003e9_253), (ParametrosRelatorio x) => {
+ if (x.get_Tipo() == "INVALID")
+ {
+ return;
+ }
+ PropertyInfo propertyInfo = properties.FirstOrDefault<PropertyInfo>((PropertyInfo p) => {
+ if (p.Name == x.get_Campo() || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("VENDEDOR") && str.Equals("SINTÉTICO POR VENDEDOR") && relatorio == 7 || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("SEGURADORA") && str.Equals("SINTÉTICO POR SEGURADORA") && relatorio == 7)
+ {
+ return true;
+ }
+ if (!p.Name.ToUpper().Equals("NOME") || !x.get_Campo().ToUpper().Equals("RAMO") || !str.Equals("SINTÉTICO POR RAMO"))
+ {
+ return false;
+ }
+ return relatorio == 7;
+ });
+ if (propertyInfo == null)
+ {
+ return;
+ }
+ xLWorksheet.Cell(1, num1).set_Value(propertyInfo.GetDescriptionAttribute());
+ num1++;
+ });
+ int num2 = 2;
+ analitico.ForEach((T a) => {
+ num1 = 1;
+ int num = num2;
+ List<ParametrosRelatorio> cSu0024u003cu003e8_locals1 = list;
+ Func<ParametrosRelatorio, int> u003cu003e9_257 = Funcoes.u003cu003ec__25<T>.u003cu003e9__25_7;
+ if (u003cu003e9_257 == null)
+ {
+ u003cu003e9_257 = (ParametrosRelatorio x) => x.get_Ordem();
+ Funcoes.u003cu003ec__25<T>.u003cu003e9__25_7 = u003cu003e9_257;
+ }
+ IOrderedEnumerable<ParametrosRelatorio> parametrosRelatorios = cSu0024u003cu003e8_locals1.OrderBy<ParametrosRelatorio, int>(u003cu003e9_257);
+ Func<ParametrosRelatorio, string> u003cu003e9_258 = Funcoes.u003cu003ec__25<T>.u003cu003e9__25_8;
+ if (u003cu003e9_258 == null)
+ {
+ u003cu003e9_258 = (ParametrosRelatorio x) => x.get_Header();
+ Funcoes.u003cu003ec__25<T>.u003cu003e9__25_8 = u003cu003e9_258;
+ }
+ ExtensionMethods.ForEach<ParametrosRelatorio>(parametrosRelatorios.ThenBy<ParametrosRelatorio, string>(u003cu003e9_258), (ParametrosRelatorio x) => {
+ int cSu0024u003cu003e8_locals3;
+ char chr;
+ if (x.get_Tipo() == "INVALID")
+ {
+ return;
+ }
+ PropertyInfo propertyInfo = properties.FirstOrDefault<PropertyInfo>((PropertyInfo p) => {
+ if (p.Name == x.get_Campo() || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("VENDEDOR") && str.Equals("SINTÉTICO POR VENDEDOR") && relatorio == 7 || p.Name.ToUpper().Equals("NOME") && x.get_Campo().ToUpper().Equals("SEGURADORA") && str.Equals("SINTÉTICO POR SEGURADORA") && relatorio == 7)
+ {
+ return true;
+ }
+ if (!p.Name.ToUpper().Equals("NOME") || !x.get_Campo().ToUpper().Equals("RAMO") || !str.Equals("SINTÉTICO POR RAMO"))
+ {
+ return false;
+ }
+ return relatorio == 7;
+ });
+ if (propertyInfo == null)
+ {
+ return;
+ }
+ Regex regex = new Regex("\\<[^\\>]*\\>");
+ object value = propertyInfo.GetValue(a);
+ if (value != null && value.ToString().Contains(">") && value.ToString().Contains("<"))
+ {
+ value = regex.Replace(value.ToString(), "");
+ }
+ string tipo = x.get_Tipo();
+ if (tipo != null)
+ {
+ switch (tipo.Length)
+ {
+ case 4:
+ {
+ if (tipo == "DATA")
+ {
+ break;
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ case 5:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA?")
+ {
+ break;
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ else if (chr == 'V')
+ {
+ if (tipo != "VALOR")
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(2);
+ xLWorksheet.Cell(num, num1).set_Value(((decimal?)value).GetValueOrDefault());
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ else
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ }
+ case 6:
+ case 7:
+ case 8:
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ case 9:
+ {
+ if (tipo == "DATA/TIME")
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy HH:mm:ss");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ case 10:
+ {
+ chr = tipo[0];
+ if (chr == 'D')
+ {
+ if (tipo == "DATA/TIME?")
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy HH:mm:ss");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ else if (chr == 'P')
+ {
+ if (tipo == "PERCENTUAL")
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(10);
+ xLWorksheet.Cell(num, num1).set_Value(((decimal?)value).GetValueOrDefault() * new decimal(1, 0, 0, false, 2));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ else
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ }
+ else if (chr != 'Q')
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ else if (tipo == "QUANTIDADE")
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().SetNumberFormatId(1);
+ xLWorksheet.Cell(num, num1).set_Value(value);
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ else
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ }
+ default:
+ {
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("dd/MM/yyyy");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ return;
+ }
+ xLWorksheet.Cell(num, num1).get_Style().get_NumberFormat().set_Format("@");
+ xLWorksheet.Cell(num, num1).set_Value(string.Format("{0}", value));
+ cSu0024u003cu003e8_locals3 = num1;
+ num1 = cSu0024u003cu003e8_locals3 + 1;
+ });
+ num2++;
+ });
+ xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true);
+ xLWorksheet.Columns().AdjustToContents();
+ xLWorkbook = xlWorkbook;
+ }
+ catch (Exception exception)
+ {
+ xLWorkbook = null;
+ }
+ return xLWorkbook;
+ });
+ return xLWorkbook1;
+ }
+
+ public static async Task<XLWorkbook> GerarXls<T>(XLWorkbook xlWorkbook, string nome, List<T> analitico, List<string> colunasOcultas = null)
+ {
+ XLWorkbook xLWorkbook1 = await Task.Run<XLWorkbook>(() => {
+ XLWorkbook xLWorkbook;
+ try
+ {
+ nome = nome.ValidaNomePlanilha("", 0);
+ IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(nome);
+ Type type = analitico[0].GetType();
+ PropertyInfo[] properties = type.GetProperties();
+ int num = 1;
+ PropertyInfo[] propertyInfoArray1 = properties;
+ for (int i1 = 0; i1 < (int)propertyInfoArray1.Length; i1++)
+ {
+ PropertyInfo propertyInfo1 = propertyInfoArray1[i1];
+ if (propertyInfo1.Name != "ValidationEvent")
+ {
+ object obj1 = propertyInfo1.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj1 != null)
+ {
+ string str = ((DescriptionAttribute)obj1).Description;
+ if (colunasOcultas == null || !colunasOcultas.Contains(str))
+ {
+ xLWorksheet.Cell(1, num).set_Value(str);
+ num++;
+ }
+ }
+ }
+ }
+ int num1 = 2;
+ analitico.ForEach((T x) => {
+ int i;
+ num = 1;
+ type = x.GetType();
+ properties = type.GetProperties();
+ PropertyInfo[] propertyInfoArray = properties;
+ for (i = 0; i < (int)propertyInfoArray.Length; i++)
+ {
+ PropertyInfo propertyInfo = propertyInfoArray[i];
+ if (propertyInfo.Name != "ValidationEvent")
+ {
+ object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj != null)
+ {
+ string description = ((DescriptionAttribute)obj).Description;
+ if (colunasOcultas == null || !colunasOcultas.Contains(description))
+ {
+ string name = propertyInfo.Name;
+ if (name.Contains("Fipe") || name == "NumeroProposta" || name == "NumeroApolice" || name == "NumeroPedidoEndosso")
+ {
+ xLWorksheet.Cell(num1, num).get_Style().get_NumberFormat().set_Format("@");
+ }
+ xLWorksheet.Cell(num1, num).set_Value(propertyInfo.GetValue(x));
+ num++;
+ }
+ }
+ }
+ }
+ i = num1;
+ num1 = i + 1;
+ });
+ xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true);
+ xLWorksheet.Columns().AdjustToContents();
+ xLWorkbook = xlWorkbook;
+ }
+ catch (Exception exception)
+ {
+ xLWorkbook = null;
+ }
+ return xLWorkbook;
+ });
+ return xLWorkbook1;
+ }
+
+ public static async Task<XLWorkbook> GerarXlsSintetico(XLWorkbook xlWorkbook, string nome, List<SinteticModel> sintetic)
+ {
+ XLWorkbook xLWorkbook1 = await Task.Run<XLWorkbook>(() => {
+ XLWorkbook xLWorkbook;
+ try
+ {
+ nome = nome.ValidaNomePlanilha("", 0);
+ IXLWorksheet xLWorksheet = xlWorkbook.get_Worksheets().Add(nome);
+ int num = 1;
+ sintetic.ForEach((SinteticModel x) => {
+ xLWorksheet.Cell(1, num).set_Value(x.get_Hint());
+ xLWorksheet.Cell(2, num).set_Value(x.get_Value());
+ num++;
+ });
+ xLWorksheet.Row(1).get_Style().get_Font().set_Bold(true);
+ xLWorksheet.Columns().AdjustToContents();
+ xLWorkbook = xlWorkbook;
+ }
+ catch (Exception exception)
+ {
+ xLWorkbook = null;
+ }
+ return xLWorkbook;
+ });
+ return xLWorkbook1;
+ }
+
+ public static string GetBody(this string html)
+ {
+ HtmlDocument htmlDocument = new HtmlDocument();
+ htmlDocument.LoadHtml(html);
+ HtmlNode htmlNode = htmlDocument.get_DocumentNode().SelectSingleNode("//body");
+ if (htmlNode != null)
+ {
+ return htmlNode.get_InnerHtml();
+ }
+ return null;
+ }
+
+ public static Categoria? GetCategoria(string text)
+ {
+ Categoria categorium;
+ if (text.Contains("caminhao") || text.Contains("caminhão"))
+ {
+ return new Categoria?(4);
+ }
+ if (text.Contains("onibus") || text.Contains("ônibus"))
+ {
+ return new Categoria?(6);
+ }
+ if (text.Contains("utilitario") || text.Contains("utilitário"))
+ {
+ return new Categoria?(6);
+ }
+ if (text.Contains("moto"))
+ {
+ return new Categoria?(9);
+ }
+ if (!Enum.TryParse<Categoria>(text, true, out categorium))
+ {
+ return null;
+ }
+ return new Categoria?((Categoria)Enum.Parse(typeof(Categoria), text, true));
+ }
+
+ public static Combustivel? GetCombustivel(string text)
+ {
+ Combustivel combustivel;
+ if (text.Contains("flex"))
+ {
+ return new Combustivel?(4);
+ }
+ if (text.Contains("gasolina") && (text.Contains("alcool") || text.Contains("álcool")))
+ {
+ if (text.Contains("gnv"))
+ {
+ return new Combustivel?(8);
+ }
+ if (!text.Contains("eletrico") && !text.Contains("elétrico"))
+ {
+ return new Combustivel?(4);
+ }
+ return new Combustivel?(12);
+ }
+ if (text.Contains("gasolina") && text.Contains("gnv"))
+ {
+ return new Combustivel?(7);
+ }
+ if (text.Contains("gasolina") && (text.Contains("eletrico") || text.Contains("elétrico")))
+ {
+ return new Combustivel?(9);
+ }
+ if (text.Contains("eletrico") || text.Contains("elétrico"))
+ {
+ return new Combustivel?(11);
+ }
+ if (text.Contains("alcool") || text.Contains("álcool"))
+ {
+ return new Combustivel?(1);
+ }
+ if (text.Contains("hibrido") || text.Contains("híbrido"))
+ {
+ return new Combustivel?(10);
+ }
+ if (text.Contains("outro"))
+ {
+ return new Combustivel?(6);
+ }
+ if (!Enum.TryParse<Combustivel>(text, true, out combustivel))
+ {
+ return null;
+ }
+ return new Combustivel?((Combustivel)Enum.Parse(typeof(Combustivel), text, true));
+ }
+
+ public static Cor? GetCor(string text)
+ {
+ Cor cor;
+ if (text.Contains("outro"))
+ {
+ return new Cor?(16);
+ }
+ if (!Enum.TryParse<Cor>(text, true, out cor))
+ {
+ return null;
+ }
+ return new Cor?((Cor)Enum.Parse(typeof(Cor), text, true));
+ }
+
+ public static Correcao? GetCorrecao(string text)
+ {
+ if (text.Contains("mercado"))
+ {
+ return new Correcao?(0);
+ }
+ if (text.Contains("determinado"))
+ {
+ return new Correcao?(1);
+ }
+ return null;
+ }
+
+ public static string GetDescriptionAttribute(this PropertyInfo pi)
+ {
+ object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj == null)
+ {
+ return pi.Name.ToUpper();
+ }
+ return ((DescriptionAttribute)obj).Description;
+ }
+
+ public static async Task<Fabricante> GetFabricante(string text)
+ {
+ Fabricante fabricante;
+ List<Fabricante> fabricantes = await (new BaseServico()).BuscarFabricante(text);
+ if (fabricantes.Count < 1)
+ {
+ fabricante = null;
+ }
+ else
+ {
+ fabricante = fabricantes.First<Fabricante>();
+ }
+ return fabricante;
+ }
+
+ public static Isencao? GetIsencao(string text)
+ {
+ if (text.Contains("sem"))
+ {
+ return new Isencao?(0);
+ }
+ if (text.Contains("ipi") && text.Contains("icms"))
+ {
+ return new Isencao?(3);
+ }
+ if (text.Contains("ipi"))
+ {
+ return new Isencao?(2);
+ }
+ if (text.Contains("icms"))
+ {
+ return new Isencao?(1);
+ }
+ return null;
+ }
+
+ public static DateTime GetNetworkTime()
+ {
+ DateTime value;
+ try
+ {
+ if (!Funcoes.StartTime.HasValue)
+ {
+ byte[] numArray = new byte[48];
+ numArray[0] = 27;
+ IPEndPoint pEndPoint = new IPEndPoint(((IEnumerable<IPAddress>)Dns.GetHostEntry("time.google.com").AddressList).First<IPAddress>((IPAddress a) => a.AddressFamily == AddressFamily.InterNetwork), 123);
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
+ {
+ socket.Connect(pEndPoint);
+ socket.ReceiveTimeout = 3000;
+ socket.Send(numArray);
+ socket.Receive(numArray);
+ socket.Close();
+ }
+ ulong num = (ulong)numArray[40] << 24 | (ulong)numArray[41] << 16 | (ulong)numArray[42] << 8 | (ulong)numArray[43];
+ ulong num1 = (ulong)numArray[44] << 24 | (ulong)numArray[45] << 16 | (ulong)numArray[46] << 8 | (ulong)numArray[47];
+ ulong num2 = num * (long)1000 + num1 * (long)1000 / 4294967296L;
+ DateTime dateTime = new DateTime(1900, 1, 1);
+ dateTime = dateTime.AddMilliseconds((double)num2);
+ Funcoes.StartTime = new DateTime?(dateTime.ToLocalTime());
+ Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew();
+ value = Funcoes.StartTime.Value;
+ }
+ else
+ {
+ value = Funcoes.StartTime.Value;
+ value = value.AddMilliseconds((double)Funcoes.Stopwatch.ElapsedMilliseconds);
+ }
+ }
+ catch (Exception exception)
+ {
+ Funcoes.StartTime = new DateTime?(DateTime.Now);
+ Funcoes.Stopwatch = System.Diagnostics.Stopwatch.StartNew();
+ value = Funcoes.StartTime.Value;
+ }
+ return value;
+ }
+
+ private static async Task<List<ParametrosRelatorio>> GetRestricoesColunas(List<ParametrosRelatorio> parametros)
+ {
+ List<RestricaoUsuarioCamposRelatorios> restricaoUsuarioCamposRelatorios = await (new RestricaoUsuarioServico()).BuscarRestricoesCamposRelatorios(Recursos.Usuario.get_Id());
+ List<RestricaoUsuarioCamposRelatorios> list = restricaoUsuarioCamposRelatorios;
+ List<RestricaoUsuarioCamposRelatorios> restricaoUsuarioCamposRelatorios1 = list;
+ list = (
+ from x in restricaoUsuarioCamposRelatorios1
+ where x.get_Restricao()
+ select x).ToList<RestricaoUsuarioCamposRelatorios>();
+ List<ParametrosRelatorio> parametrosRelatorios = (
+ from x in parametros
+ where (
+ from y in list
+ where x.get_Relatorio() == y.get_Relatorio()
+ select y).All<RestricaoUsuarioCamposRelatorios>((RestricaoUsuarioCamposRelatorios y) => x.get_Header() != y.get_Campo())
+ select x).ToList<ParametrosRelatorio>();
+ return parametrosRelatorios;
+ }
+
+ public static TabelaReferencia? GetTabelaReferencia(string text)
+ {
+ TabelaReferencia tabelaReferencium;
+ if (!Enum.TryParse<TabelaReferencia>(text, true, out tabelaReferencium))
+ {
+ return null;
+ }
+ return new TabelaReferencia?((TabelaReferencia)Enum.Parse(typeof(TabelaReferencia), text, true));
+ }
+
+ public static string GetText(string html)
+ {
+ HtmlDocument htmlDocument = new HtmlDocument();
+ htmlDocument.LoadHtml(html);
+ return Funcoes.NodeText(htmlDocument.get_DocumentNode());
+ }
+
+ public static TipoCobertura? GetTipoCobertura(string text)
+ {
+ TipoCobertura tipoCobertura;
+ if (text.Contains("incendio") || text.Contains("incêndio"))
+ {
+ return new TipoCobertura?(2);
+ }
+ if (text.Contains("roubo") && text.Contains("furto"))
+ {
+ return new TipoCobertura?(5);
+ }
+ if (text.Contains("terceiros"))
+ {
+ return new TipoCobertura?(3);
+ }
+ if (text.Contains("compreensiva"))
+ {
+ return new TipoCobertura?(1);
+ }
+ if (!Enum.TryParse<TipoCobertura>(text, true, out tipoCobertura))
+ {
+ return null;
+ }
+ return new TipoCobertura?((TipoCobertura)Enum.Parse(typeof(TipoCobertura), text, true));
+ }
+
+ public static string GetTypeAttribute(this PropertyInfo pi)
+ {
+ object obj = pi.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault<object>();
+ if (obj == null)
+ {
+ return "";
+ }
+ return ((TipoAttribute)obj).get_Description();
+ }
+
+ public static UsoVeiculo? GetUsoveiculo(string text)
+ {
+ UsoVeiculo usoVeiculo;
+ UsoVeiculo usoVeiculo1;
+ if (Enum.TryParse<UsoVeiculo>(text, true, out usoVeiculo))
+ {
+ usoVeiculo1 = usoVeiculo;
+ }
+ else
+ {
+ usoVeiculo1 = 0;
+ }
+ return new UsoVeiculo?(usoVeiculo1);
+ }
+
+ public static T GetValueFromType<T>(this object objeto)
+ {
+ Type type = typeof(T);
+ PropertyInfo[] properties = objeto.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ for (int i = 0; i < (int)properties.Length; i++)
+ {
+ PropertyInfo propertyInfo = properties[i];
+ if (propertyInfo.PropertyType == type)
+ {
+ return (T)propertyInfo.GetValue(objeto);
+ }
+ }
+ return default(T);
+ }
+
+ public static async Task<bool> InativarItens(long id, long ramo, bool delete = true)
+ {
+ bool sucesso;
+ ItemServico itemServico = new ItemServico();
+ ObservableCollection<Item> observableCollection = await itemServico.BuscarItens(id);
+ ObservableCollection<Item> observableCollection1 = observableCollection;
+ IEnumerable<Item> hasValue =
+ from x in observableCollection1
+ where x.get_Substituicao().HasValue
+ select x;
+ if (await Funcoes.ReativarItens((
+ from x in hasValue
+ select x.get_Substituicao().Value).ToList<long>()))
+ {
+ if (!delete)
+ {
+ List<Item> list = observableCollection.ToList<Item>();
+ list.ForEach((Item x) => x.set_Cancelado(true));
+ await itemServico.SaveRange(observableCollection.ToList<Item>());
+ }
+ else
+ {
+ await itemServico.DeleteRange(observableCollection.ToList<Item>(), ramo);
+ }
+ sucesso = itemServico.Sucesso;
+ }
+ else
+ {
+ sucesso = false;
+ }
+ itemServico = null;
+ observableCollection = null;
+ return sucesso;
+ }
+
+ public static bool IsEmpty(this string html)
+ {
+ int count = Regex.Matches(html, "<body>").Count;
+ bool flag = true;
+ int num = 0;
+ for (int i = 0; i < count; i++)
+ {
+ int num1 = html.IndexOf("<body>", num, StringComparison.Ordinal) + 6;
+ if (num1 == 5)
+ {
+ break;
+ }
+ int num2 = html.IndexOf("</body>", num, StringComparison.Ordinal);
+ num = num2 + 7;
+ flag = string.IsNullOrWhiteSpace(html.Substring(num1, num2 - num1));
+ if (!flag)
+ {
+ break;
+ }
+ }
+ return flag;
+ }
+
+ public static Window IsHosterOpen(string name)
+ {
+ return System.Windows.Application.Current.Windows.OfType<HosterWindow>().ToList<HosterWindow>().FirstOrDefault<HosterWindow>((HosterWindow x) => {
+ string str;
+ ContentControl contentControl = Extentions.FindVisualChildren<ContentControl>(x).FirstOrDefault<ContentControl>();
+ if (contentControl != null)
+ {
+ str = contentControl.Tag.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ return str == name;
+ });
+ }
+
+ public static bool IsWindowOpen<T>(string title)
+ where T : Window
+ {
+ return System.Windows.Application.Current.Windows.OfType<T>().Any<T>((T x) => x.Title == title);
+ }
+
+ public static List<TupleList> LogList(this List<ValorOriginal> valores, bool restricaoComissao = false)
+ {
+ List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>();
+ valores.ForEach((ValorOriginal x) => {
+ if (restricaoComissao && x.get_Campo().ToUpper().Contains("COMISSÃO"))
+ {
+ return;
+ }
+ tuples.Add(new Tuple<string, string, string>(x.get_Descricao(), (string.IsNullOrEmpty(x.get_ValorAtual()) ? "NÃO PREENCHIDO" : (x.get_ValorAtual() == "True" ? "SIM" : (x.get_ValorAtual() == "False" ? "NÃO" : x.get_ValorAtual()))), ""));
+ });
+ List<TupleList> tupleLists = new List<TupleList>();
+ TupleList tupleList = new TupleList();
+ tupleList.set_Tuples(new ObservableCollection<Tuple<string, string, string>>(tuples));
+ tupleLists.Add(tupleList);
+ return tupleLists;
+ }
+
+ public static List<TupleList> LogList(this List<Diferenca> valores, bool restricaoComissao = false)
+ {
+ List<Tuple<string, string, string>> tuples = new List<Tuple<string, string, string>>();
+ valores.ForEach((Diferenca x) => {
+ if (restricaoComissao && x.get_Campo().ToUpper().Contains("COMISSÃO"))
+ {
+ return;
+ }
+ tuples.Add(new Tuple<string, string, string>(x.get_Descricao(), (string.IsNullOrEmpty(x.get_ValorAtual()) ? "NÃO PREENCHIDO" : (x.get_ValorAtual() == "True" ? "SIM" : (x.get_ValorAtual() == "False" ? "NÃO" : x.get_ValorAtual()))), (string.IsNullOrEmpty(x.get_ValorAnterior()) ? "NÃO PREENCHIDO" : (x.get_ValorAnterior() == "True" ? "SIM" : (x.get_ValorAnterior() == "False" ? "NÃO" : x.get_ValorAnterior())))));
+ });
+ List<TupleList> tupleLists = new List<TupleList>();
+ TupleList tupleList = new TupleList();
+ tupleList.set_Tuples(new ObservableCollection<Tuple<string, string, string>>(tuples));
+ tupleLists.Add(tupleList);
+ return tupleLists;
+ }
+
+ public static async Task MostrarErro(TipoErro erro)
+ {
+ await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => (new ErrorWindow(erro, true)).ShowDialog()));
+ }
+
+ private static string NodeText(HtmlNode node)
+ {
+ string innerText = "";
+ if (node.get_HasChildNodes())
+ {
+ foreach (HtmlNode childNode in node.get_ChildNodes())
+ {
+ innerText = string.Concat(innerText, (childNode.get_NodeType() == 3 ? childNode.get_InnerText() : Funcoes.NodeText(childNode)));
+ }
+ }
+ else if (node.get_NodeType() == 3)
+ {
+ innerText = node.get_InnerText();
+ }
+ return innerText;
+ }
+
+ public static async Task<List<string>> OcultarColunas<T>(Relatorio relatorio)
+ {
+ List<string> strs;
+ List<string> strs1 = new List<string>();
+ List<ParametrosRelatorio> restricoesColunas = await (new ConfuguracoesServico()).BuscarParametros(relatorio);
+ if (restricoesColunas == null || restricoesColunas.Count == 0)
+ {
+ strs = strs1;
+ }
+ else
+ {
+ restricoesColunas = await Funcoes.GetRestricoesColunas(restricoesColunas);
+ PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ for (int i = 0; i < (int)properties.Length; i++)
+ {
+ PropertyInfo propertyInfo = properties[i];
+ object obj = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault<object>();
+ string description = "";
+ if (obj != null)
+ {
+ description = ((TipoAttribute)obj).get_Description();
+ }
+ string descriptionAttribute = propertyInfo.GetDescriptionAttribute();
+ if (description == "INVALID")
+ {
+ strs1.Add(descriptionAttribute);
+ }
+ if (!restricoesColunas.Any<ParametrosRelatorio>((ParametrosRelatorio x) => x.get_Campo() == propertyInfo.Name) && !(propertyInfo.Name == "ValidationEvent"))
+ {
+ strs1.Add(descriptionAttribute);
+ }
+ }
+ strs = strs1;
+ }
+ strs1 = null;
+ return strs;
+ }
+
+ public static List<string> OcultarColunasDescricao(Type type, string categoria)
+ {
+ List<string> strs = new List<string>();
+ PropertyInfo[] properties = type.GetProperties();
+ for (int i = 0; i < (int)properties.Length; i++)
+ {
+ PropertyInfo propertyInfo = properties[i];
+ if (propertyInfo.Name != "ValidationEvent")
+ {
+ object obj = propertyInfo.GetCustomAttributes(typeof(CategoryAttribute), true).FirstOrDefault<object>();
+ if (obj != null && !(((CategoryAttribute)obj).Category == categoria))
+ {
+ object obj1 = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault<object>();
+ if (obj1 != null)
+ {
+ strs.Add(((DescriptionAttribute)obj1).Description);
+ }
+ }
+ }
+ }
+ return strs;
+ }
+
+ public static async Task OrganizarDocumentos(long id)
+ {
+ ApoliceServico apoliceServico = new ApoliceServico();
+ Controle controle = await apoliceServico.BuscarControleAsync(id);
+ int num = 1;
+ IList<Documento> documentos = controle.get_Documentos();
+ IEnumerable<Documento> excluido =
+ from x in documentos
+ where !x.get_Excluido()
+ select x;
+ (
+ from x in excluido
+ orderby x.get_Vigencia1()
+ select x).ToList<Documento>().ForEach((Documento x) => {
+ if (x.get_Tipo() == 0)
+ {
+ x.set_Ordem(0);
+ return;
+ }
+ x.set_Ordem(num);
+ num++;
+ });
+ await apoliceServico.UpdateRange(controle);
+ apoliceServico = null;
+ }
+
+ public static ParentescoVinculo? ParentescoInverso(ParentescoVinculo? parentesco)
+ {
+ if (parentesco.HasValue)
+ {
+ switch (parentesco.GetValueOrDefault())
+ {
+ case 0:
+ {
+ return new ParentescoVinculo?(1);
+ }
+ case 1:
+ {
+ return new ParentescoVinculo?(0);
+ }
+ case 3:
+ {
+ return new ParentescoVinculo?(4);
+ }
+ case 4:
+ {
+ return new ParentescoVinculo?(3);
+ }
+ case 5:
+ {
+ return new ParentescoVinculo?(6);
+ }
+ case 6:
+ {
+ return new ParentescoVinculo?(5);
+ }
+ case 7:
+ {
+ return new ParentescoVinculo?(8);
+ }
+ case 8:
+ {
+ return new ParentescoVinculo?(7);
+ }
+ case 10:
+ {
+ return new ParentescoVinculo?(11);
+ }
+ case 11:
+ {
+ return new ParentescoVinculo?(10);
+ }
+ case 13:
+ {
+ return new ParentescoVinculo?(14);
+ }
+ case 14:
+ {
+ return new ParentescoVinculo?(13);
+ }
+ case 19:
+ {
+ return new ParentescoVinculo?(20);
+ }
+ case 20:
+ {
+ return new ParentescoVinculo?(19);
+ }
+ case 21:
+ {
+ return new ParentescoVinculo?(22);
+ }
+ case 22:
+ {
+ return new ParentescoVinculo?(21);
+ }
+ }
+ }
+ return parentesco;
+ }
+
+ public static TipoPagamento ParseTransactionType(this OfxTransactionType type)
+ {
+ switch (type)
+ {
+ case 0:
+ {
+ return 5;
+ }
+ case 1:
+ case 4:
+ {
+ return 7;
+ }
+ case 6:
+ case 13:
+ {
+ return 8;
+ }
+ case 7:
+ case 12:
+ {
+ return 10;
+ }
+ case 10:
+ {
+ return 4;
+ }
+ case 11:
+ {
+ return 15;
+ }
+ case 14:
+ {
+ return 6;
+ }
+ default:
+ {
+ return 12;
+ }
+ }
+ }
+
+ public static string PlacaVencimento(string placa, Categoria? categoria)
+ {
+ if (string.IsNullOrEmpty(placa))
+ {
+ return "";
+ }
+ string str = placa.Substring(placa.Length - 1, 1);
+ if (str != null && str.Length == 1)
+ {
+ switch (str[0])
+ {
+ case '0':
+ {
+ return "DEZEMBRO";
+ }
+ case '1':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "SETEMBRO";
+ }
+ return "ABRIL";
+ }
+ case '2':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "SETEMBRO";
+ }
+ return "MAIO";
+ }
+ case '3':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "OUTUBRO";
+ }
+ return "JUNHO";
+ }
+ case '4':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "OUTUBRO";
+ }
+ return "JULHO";
+ }
+ case '5':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "OUTUBRO";
+ }
+ return "AGOSTO";
+ }
+ case '6':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "NOVEMBRO";
+ }
+ return "AGOSTO";
+ }
+ case '7':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "NOVEMBRO";
+ }
+ return "SETEMBRO";
+ }
+ case '8':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "NOVEMBRO";
+ }
+ return "OUTUBRO";
+ }
+ case '9':
+ {
+ if (categoria.HasValue && categoria.GetValueOrDefault() == 4)
+ {
+ return "DEZEMBRO";
+ }
+ return "NOVEMBRO";
+ }
+ }
+ }
+ return "";
+ }
+
+ public static List<FiltroPersonalizado> PopularFiltroFinanceiro()
+ {
+ List<FiltroPersonalizado> filtroPersonalizados = new List<FiltroPersonalizado>();
+ FiltroPersonalizado filtroPersonalizado = new FiltroPersonalizado();
+ filtroPersonalizado.set_Propriedade("Id");
+ filtroPersonalizado.set_Nome("ID");
+ filtroPersonalizado.set_Tipo(typeof(long));
+ filtroPersonalizados.Add(filtroPersonalizado);
+ FiltroPersonalizado filtroPersonalizado1 = new FiltroPersonalizado();
+ filtroPersonalizado1.set_Propriedade("Controle.Fornecedor.NomeSocial");
+ filtroPersonalizado1.set_Nome("FORNECEDOR");
+ filtroPersonalizado1.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado1);
+ FiltroPersonalizado filtroPersonalizado2 = new FiltroPersonalizado();
+ filtroPersonalizado2.set_Propriedade("Controle.Fornecedor.Ativo");
+ filtroPersonalizado2.set_Nome("FORNECEDOR ATIVO");
+ filtroPersonalizado2.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado2);
+ FiltroPersonalizado filtroPersonalizado3 = new FiltroPersonalizado();
+ filtroPersonalizado3.set_Propriedade("Historico");
+ filtroPersonalizado3.set_Nome("HISTÓRICO");
+ filtroPersonalizado3.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado3);
+ FiltroPersonalizado filtroPersonalizado4 = new FiltroPersonalizado();
+ filtroPersonalizado4.set_Propriedade("Parcela");
+ filtroPersonalizado4.set_Nome("PARCELA");
+ filtroPersonalizado4.set_Tipo(typeof(int));
+ filtroPersonalizados.Add(filtroPersonalizado4);
+ FiltroPersonalizado filtroPersonalizado5 = new FiltroPersonalizado();
+ filtroPersonalizado5.set_Propriedade("Documento");
+ filtroPersonalizado5.set_Nome("DOCUMENTO");
+ filtroPersonalizado5.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado5);
+ FiltroPersonalizado filtroPersonalizado6 = new FiltroPersonalizado();
+ filtroPersonalizado6.set_Propriedade("Competencia");
+ filtroPersonalizado6.set_Nome("COMPETÊNCIA");
+ filtroPersonalizado6.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado6);
+ FiltroPersonalizado filtroPersonalizado7 = new FiltroPersonalizado();
+ filtroPersonalizado7.set_Propriedade("Complemento");
+ filtroPersonalizado7.set_Nome("COMPLEMENTO");
+ filtroPersonalizado7.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado7);
+ FiltroPersonalizado filtroPersonalizado8 = new FiltroPersonalizado();
+ filtroPersonalizado8.set_Propriedade("Vencimento");
+ filtroPersonalizado8.set_Nome("VENCIMENTO");
+ filtroPersonalizado8.set_Tipo(typeof(DateTime));
+ filtroPersonalizados.Add(filtroPersonalizado8);
+ FiltroPersonalizado filtroPersonalizado9 = new FiltroPersonalizado();
+ filtroPersonalizado9.set_Propriedade("Valor");
+ filtroPersonalizado9.set_Nome("VALOR");
+ filtroPersonalizado9.set_Tipo(typeof(decimal));
+ filtroPersonalizados.Add(filtroPersonalizado9);
+ FiltroPersonalizado filtroPersonalizado10 = new FiltroPersonalizado();
+ filtroPersonalizado10.set_Propriedade("Baixa");
+ filtroPersonalizado10.set_Nome("DATA BAIXA");
+ filtroPersonalizado10.set_Tipo(typeof(DateTime));
+ filtroPersonalizados.Add(filtroPersonalizado10);
+ FiltroPersonalizado filtroPersonalizado11 = new FiltroPersonalizado();
+ filtroPersonalizado11.set_Propriedade("ValorPago");
+ filtroPersonalizado11.set_Nome("VALOR PAGO");
+ filtroPersonalizado11.set_Tipo(typeof(decimal));
+ filtroPersonalizados.Add(filtroPersonalizado11);
+ FiltroPersonalizado filtroPersonalizado12 = new FiltroPersonalizado();
+ filtroPersonalizado12.set_Propriedade("Pagamento");
+ filtroPersonalizado12.set_Nome("PAGAMENTO");
+ filtroPersonalizado12.set_Tipo(typeof(DateTime));
+ filtroPersonalizados.Add(filtroPersonalizado12);
+ FiltroPersonalizado filtroPersonalizado13 = new FiltroPersonalizado();
+ filtroPersonalizado13.set_Propriedade("Conta.Descricao");
+ filtroPersonalizado13.set_Nome("CONTA");
+ filtroPersonalizado13.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado13);
+ FiltroPersonalizado filtroPersonalizado14 = new FiltroPersonalizado();
+ filtroPersonalizado14.set_Propriedade("Controle.Plano.Descricao");
+ filtroPersonalizado14.set_Nome("PLANO DE CONTAS");
+ filtroPersonalizado14.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado14);
+ FiltroPersonalizado filtroPersonalizado15 = new FiltroPersonalizado();
+ filtroPersonalizado15.set_Propriedade("Controle.Centro.Descricao");
+ filtroPersonalizado15.set_Nome("CENTRO DE CUSTO");
+ filtroPersonalizado15.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado15);
+ FiltroPersonalizado filtroPersonalizado16 = new FiltroPersonalizado();
+ filtroPersonalizado16.set_Propriedade("Sinal");
+ filtroPersonalizado16.set_Nome("SINAL");
+ filtroPersonalizado16.set_Tipo(typeof(Enum));
+ filtroPersonalizados.Add(filtroPersonalizado16);
+ FiltroPersonalizado filtroPersonalizado17 = new FiltroPersonalizado();
+ filtroPersonalizado17.set_Propriedade("TipoPagamento");
+ filtroPersonalizado17.set_Nome("FORMA PAGAMENTO");
+ filtroPersonalizado17.set_Tipo(typeof(Enum));
+ filtroPersonalizados.Add(filtroPersonalizado17);
+ FiltroPersonalizado filtroPersonalizado18 = new FiltroPersonalizado();
+ filtroPersonalizado18.set_Propriedade("Observacao");
+ filtroPersonalizado18.set_Nome("OBSERVAÇÃO");
+ filtroPersonalizado18.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado18);
+ FiltroPersonalizado filtroPersonalizado19 = new FiltroPersonalizado();
+ filtroPersonalizado19.set_Propriedade("Controle.Plano.Nome");
+ filtroPersonalizado19.set_Nome("PLANO");
+ filtroPersonalizado19.set_Tipo(typeof(string));
+ filtroPersonalizados.Add(filtroPersonalizado19);
+ return filtroPersonalizados;
+ }
+
+ public static List<FiltroPersonalizado> PopularFiltroPersonalizado<T>()
+ {
+ List<FiltroPersonalizado> filtroPersonalizados = new List<FiltroPersonalizado>();
+ foreach (PropertyInfo propertyInfo in
+ from in (IEnumerable<PropertyInfo>)typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
+ orderby Gestor.Common.Validation.ValidationHelper.DescriptionAttribute(x)
+ select )
+ {
+ if (propertyInfo.Name == "ValidationEvent")
+ {
+ continue;
+ }
+ FiltroPersonalizado filtroPersonalizado = new FiltroPersonalizado();
+ filtroPersonalizado.set_Propriedade(propertyInfo.Name);
+ filtroPersonalizado.set_Nome(propertyInfo.GetDescriptionAttribute());
+ FiltroPersonalizado filtroPersonalizado1 = filtroPersonalizado;
+ if (propertyInfo.GetTypeAttribute() == "INVALID")
+ {
+ continue;
+ }
+ Type propertyType = propertyInfo.PropertyType;
+ if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
+ {
+ propertyType = propertyType.GetGenericArguments()[0];
+ }
+ filtroPersonalizado1.set_Tipo((propertyType.BaseType == typeof(Enum) ? propertyType.BaseType : propertyType));
+ filtroPersonalizados.Add(filtroPersonalizado1);
+ }
+ return filtroPersonalizados;
+ }
+
+ public static bool ProgramaEmExecucao(this string programName)
+ {
+ return Process.GetProcessesByName(programName).Length != 0;
+ }
+
+ public static async Task<bool> ReativarItens(List<long> ids)
+ {
+ ItemServico itemServico = new ItemServico();
+ List<Item> items = await itemServico.BuscarItems(ids);
+ List<Item> items1 = items;
+ items1.ForEach((Item x) => {
+ x.set_Substituido(null);
+ x.set_Cancelado(false);
+ x.set_Status(x.get_StatusInclusao());
+ });
+ await itemServico.SaveRange(items);
+ bool sucesso = itemServico.Sucesso;
+ itemServico = null;
+ return sucesso;
+ }
+
+ public static async Task RecusarApolice(Documento documento, string motivo, bool estorno)
+ {
+ bool flag;
+ string str;
+ NegocioCorretora negocioCorretora;
+ NegocioCorretora negocioCorretora1;
+ ApoliceServico apoliceServico = new ApoliceServico();
+ CriticaApoliceServico criticaApoliceServico = new CriticaApoliceServico();
+ if (documento.get_Tipo() != 0 || !string.IsNullOrEmpty(documento.get_Apolice()))
+ {
+ str = (documento.get_Tipo() != 0 || string.IsNullOrEmpty(documento.get_Apolice()) ? "ENDOSSO RECUSADO" : "APÓLICE RECUSADA");
+ }
+ else
+ {
+ str = "PROPOSTA RECUSADA";
+ }
+ string str1 = str;
+ if (!string.IsNullOrWhiteSpace(motivo))
+ {
+ Documento documento1 = documento;
+ object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, motivo, Environment.NewLine, Environment.NewLine, documento.get_Observacao() };
+ documento1.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}RECUSA: {4}{5}{6}{7}", nome));
+ }
+ if (documento.get_Tipo() != 0)
+ {
+ if (!documento.get_NegocioCorretora().HasValue)
+ {
+ Documento documento2 = documento;
+ negocioCorretora = (!documento.get_Negocio().HasValue || documento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1);
+ documento2.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora));
+ }
+ documento.set_Situacao(7);
+ documento.set_Apolice("RECUSADA");
+ documento.set_Endosso("RECUSADA");
+ flag = await apoliceServico.BaixarParcelasCancelamento(documento, estorno);
+ if (!flag)
+ {
+ Action<TipoTela, string> acessaTela = Gestor.Application.Actions.Actions.AcessaTela;
+ if (acessaTela != null)
+ {
+ acessaTela(21, "");
+ }
+ else
+ {
+ }
+ }
+ await apoliceServico.Save(documento, false, false);
+ if (!apoliceServico.Sucesso)
+ {
+ Action<TipoTela, string> action = Gestor.Application.Actions.Actions.AcessaTela;
+ if (action != null)
+ {
+ action(21, "");
+ }
+ else
+ {
+ }
+ }
+ if (!apoliceServico.Sucesso)
+ {
+ Action<TipoTela, string> acessaTela1 = Gestor.Application.Actions.Actions.AcessaTela;
+ if (acessaTela1 != null)
+ {
+ acessaTela1(21, "");
+ }
+ else
+ {
+ }
+ }
+ flag = await Funcoes.InativarItens(documento.get_Id(), documento.get_Controle().get_Ramo().get_Id(), false);
+ if (!flag)
+ {
+ Action<TipoTela, string> action1 = Gestor.Application.Actions.Actions.AcessaTela;
+ if (action1 != null)
+ {
+ action1(21, "");
+ }
+ else
+ {
+ }
+ }
+ }
+ else
+ {
+ await apoliceServico.Save(documento, false, false);
+ Controle controle = await apoliceServico.BuscarControleAsync(documento.get_Controle().get_Id());
+ if (controle.get_Id() != 0)
+ {
+ foreach (Documento documento3 in controle.get_Documentos())
+ {
+ if (!documento3.get_NegocioCorretora().HasValue)
+ {
+ Documento documento4 = documento3;
+ negocioCorretora1 = (!documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1);
+ documento4.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1));
+ }
+ documento3.set_Situacao(7);
+ documento3.set_Apolice("RECUSADA");
+ flag = await apoliceServico.BaixarParcelasCancelamento(documento3, estorno);
+ if (flag)
+ {
+ continue;
+ }
+ Action<TipoTela, string> acessaTela2 = Gestor.Application.Actions.Actions.AcessaTela;
+ if (acessaTela2 != null)
+ {
+ acessaTela2(21, "");
+ }
+ else
+ {
+ }
+ }
+ flag = await apoliceServico.UpdateRange(controle);
+ controle = null;
+ }
+ else
+ {
+ apoliceServico = null;
+ criticaApoliceServico = null;
+ str1 = null;
+ return;
+ }
+ }
+ if (!flag)
+ {
+ Action<TipoTela, string> action2 = Gestor.Application.Actions.Actions.AcessaTela;
+ if (action2 != null)
+ {
+ action2(21, "");
+ }
+ else
+ {
+ }
+ }
+ List<CriticaApolice> criticaApolices = await criticaApoliceServico.BuscarCritica(documento.get_Id());
+ if (criticaApolices != null)
+ {
+ foreach (CriticaApolice criticaApolouse in criticaApolices)
+ {
+ criticaApolouse.set_Critica(new bool?(true));
+ await criticaApoliceServico.Save(criticaApolouse);
+ }
+ }
+ Action<TipoTela, string> acessaTela3 = Gestor.Application.Actions.Actions.AcessaTela;
+ if (acessaTela3 != null)
+ {
+ acessaTela3(21, "");
+ }
+ else
+ {
+ }
+ Funcoes.ToggleSnackBar(string.Concat(str1, " COM SUCESSO"), true);
+ apoliceServico = null;
+ criticaApoliceServico = null;
+ str1 = null;
+ }
+
+ private static async void RegistrarLogBaixa(long id, DateTime now)
+ {
+ string str;
+ ApoliceServico apoliceServico = new ApoliceServico();
+ ParcelaServico parcelaServico = new ParcelaServico();
+ VendedorServico vendedorServico = new VendedorServico();
+ Documento documento = await apoliceServico.BuscarApoliceAsync(id, false, false);
+ Documento documento1 = documento;
+ ObservableCollection<Parcela> observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id());
+ documento1.set_Parcelas(observableCollection);
+ documento1 = null;
+ List<VendedorParcela> vendedorParcelas = await vendedorServico.BuscaRepasse(documento.get_Id());
+ foreach (Parcela parcela in documento.get_Parcelas())
+ {
+ foreach (VendedorParcela vendedorParcela in vendedorParcelas)
+ {
+ if (vendedorParcela.get_Parcela().get_Id() != parcela.get_Id())
+ {
+ continue;
+ }
+ if (parcela.get_Vendedores() == null)
+ {
+ parcela.set_Vendedores(new ObservableCollection<VendedorParcela>());
+ }
+ parcela.get_Vendedores().Add(vendedorParcela);
+ }
+ }
+ IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
+ RegistroLog registroLog = new RegistroLog();
+ registroLog.set_Acao(1);
+ registroLog.set_Usuario(Recursos.Usuario);
+ registroLog.set_DataHora(now);
+ Documento documento2 = documento;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ registroLog.set_Descricao(JsonConvert.SerializeObject(documento2, jsonSerializerSetting));
+ registroLog.set_EntidadeId(documento.get_Id());
+ registroLog.set_Tela(2);
+ registroLog.set_NomeMaquina(Environment.MachineName);
+ registroLog.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] addressList = hostEntry.AddressList;
+ IPAddress pAddress = ((IEnumerable<IPAddress>)addressList).FirstOrDefault<IPAddress>((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork);
+ if (pAddress != null)
+ {
+ str = pAddress.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ registroLog.set_Ip(str);
+ RegistroLog registroLog1 = registroLog;
+ using (UnitOfWork commited = Instancia.Commited)
+ {
+ commited.get_RegistroLogRepository().SaveOrUpdate(registroLog1);
+ commited.Commit();
+ }
+ parcelaServico = null;
+ vendedorServico = null;
+ documento = null;
+ }
+
+ public static string RemoverAcentos(string text)
+ {
+ string str = text.Normalize(NormalizationForm.FormD);
+ StringBuilder stringBuilder = new StringBuilder();
+ foreach (char chr in
+ from c in str
+ let unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c)
+ where unicodeCategory != UnicodeCategory.NonSpacingMark
+ select c)
+ {
+ stringBuilder.Append(chr);
+ }
+ return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
+ }
+
+ [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
+ private static extern bool SetForegroundWindow(IntPtr hWnd);
+
+ [DllImport("user32.dll", CharSet=CharSet.None, ExactSpelling=false)]
+ private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
+
+ public static string SubstituirVariaveis(string corpo, MalaDireta envio)
+ {
+ DateTime? vigencia2;
+ DateTime vigencia1;
+ decimal valor;
+ decimal? nullable;
+ bool controle;
+ bool flag;
+ string str;
+ string str1;
+ string str2;
+ string str3;
+ object obj;
+ string str4;
+ string str5;
+ string description;
+ decimal? nullable1;
+ string str6;
+ decimal? nullable2;
+ string str7;
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ VariaveisMalaDireta[] values = (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta));
+ for (int i = 0; i < (int)values.Length; i++)
+ {
+ VariaveisMalaDireta variaveisMalaDiretum = values[i];
+ switch (variaveisMalaDiretum)
+ {
+ case 0:
+ {
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), networkTime.ToString(new CultureInfo("pt-BR")));
+ break;
+ }
+ case 1:
+ {
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(envio.get_Cliente().get_NomeSocialRg()) ? envio.get_Cliente().get_NomeSocialRg() : envio.get_Cliente().get_Nome()));
+ break;
+ }
+ case 2:
+ {
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Cliente().get_Documento());
+ break;
+ }
+ case 3:
+ {
+ if (envio.get_Apolice() == null)
+ {
+ break;
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Proposta());
+ break;
+ }
+ case 4:
+ {
+ if (envio.get_Apolice() == null)
+ {
+ break;
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Concat(envio.get_Apolice().get_Apolice(), (envio.get_Apolice().get_Tipo() != 0 ? string.Concat(", endosso de número: ", envio.get_Apolice().get_Endosso()) : "")));
+ break;
+ }
+ case 5:
+ {
+ Documento apolice = envio.get_Apolice();
+ if (apolice != null)
+ {
+ controle = apolice.get_Controle();
+ }
+ else
+ {
+ controle = false;
+ }
+ if (!controle)
+ {
+ break;
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Controle().get_Ramo().get_Nome());
+ break;
+ }
+ case 6:
+ {
+ Documento documento = envio.get_Apolice();
+ if (documento != null)
+ {
+ flag = documento.get_Controle();
+ }
+ else
+ {
+ flag = false;
+ }
+ if (!flag)
+ {
+ break;
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Apolice().get_Controle().get_Seguradora().get_Nome());
+ break;
+ }
+ case 7:
+ {
+ if (envio.get_Apolice() == null)
+ {
+ break;
+ }
+ string entity = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ vigencia1 = envio.get_Apolice().get_Vigencia1();
+ corpo = corpo.Replace(entity, vigencia1.ToString("d"));
+ break;
+ }
+ case 8:
+ {
+ if (envio.get_Apolice() == null)
+ {
+ break;
+ }
+ string str8 = corpo;
+ string entity1 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ vigencia2 = envio.get_Apolice().get_Vigencia2();
+ if (vigencia2.HasValue)
+ {
+ vigencia1 = vigencia2.GetValueOrDefault();
+ str = vigencia1.ToString("d");
+ }
+ else
+ {
+ str = null;
+ }
+ corpo = str8.Replace(entity1, str);
+ break;
+ }
+ case 9:
+ {
+ if (envio.get_Parcela() == null)
+ {
+ break;
+ }
+ string entity2 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ vigencia1 = envio.get_Parcela().get_Vencimento();
+ corpo = corpo.Replace(entity2, vigencia1.ToString("d"));
+ break;
+ }
+ case 10:
+ {
+ if (envio.get_Parcela() == null)
+ {
+ break;
+ }
+ string entity3 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ valor = envio.get_Parcela().get_Valor();
+ corpo = corpo.Replace(entity3, valor.ToString("c2"));
+ break;
+ }
+ case 11:
+ {
+ if (envio.get_Item() == null)
+ {
+ break;
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Item().get_Descricao());
+ break;
+ }
+ case 12:
+ {
+ if (envio.get_Sinistro() == null)
+ {
+ break;
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), envio.get_Sinistro().get_Numero());
+ break;
+ }
+ case 13:
+ {
+ if (envio.get_Parcela() == null)
+ {
+ break;
+ }
+ string entity4 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ int numeroParcela = envio.get_Parcela().get_NumeroParcela();
+ corpo = corpo.Replace(entity4, numeroParcela.ToString());
+ break;
+ }
+ case 14:
+ {
+ vigencia2 = envio.get_Cliente().get_Nascimento();
+ if (!vigencia2.HasValue)
+ {
+ break;
+ }
+ string str9 = corpo;
+ string entity5 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ vigencia2 = envio.get_Cliente().get_Nascimento();
+ if (vigencia2.HasValue)
+ {
+ vigencia1 = vigencia2.GetValueOrDefault();
+ str1 = vigencia1.ToString("dd/MM");
+ }
+ else
+ {
+ str1 = null;
+ }
+ corpo = str9.Replace(entity5, str1);
+ break;
+ }
+ case 15:
+ {
+ vigencia2 = envio.get_Cliente().get_Nascimento();
+ if (!vigencia2.HasValue)
+ {
+ break;
+ }
+ string str10 = corpo;
+ string entity6 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ vigencia2 = envio.get_Cliente().get_Nascimento();
+ if (vigencia2.HasValue)
+ {
+ vigencia1 = vigencia2.GetValueOrDefault();
+ str2 = vigencia1.ToString("d");
+ }
+ else
+ {
+ str2 = null;
+ }
+ corpo = str10.Replace(entity6, str2);
+ break;
+ }
+ case 16:
+ {
+ string str11 = corpo;
+ string entity7 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ vigencia2 = envio.get_Cliente().get_VencimentoHabilitacao();
+ if (vigencia2.HasValue)
+ {
+ vigencia1 = vigencia2.GetValueOrDefault();
+ str3 = vigencia1.ToString("d");
+ }
+ else
+ {
+ str3 = null;
+ }
+ corpo = str11.Replace(entity7, str3);
+ break;
+ }
+ case 17:
+ {
+ if (envio.get_ArquivoDigital() != null)
+ {
+ if (!envio.get_ArquivoDigital().All<IndiceArquivoDigital>((IndiceArquivoDigital x) => string.IsNullOrWhiteSpace(x.get_UrlAssinatura())))
+ {
+ string str12 = "<table><thead><tr><th>ABAIXO OS DOCUMENTOS PARA ASSINATURA</th></thead><tbody>";
+ (
+ from x in envio.get_ArquivoDigital()
+ where !string.IsNullOrWhiteSpace(x.get_UrlAssinatura())
+ select x).ToList<IndiceArquivoDigital>().ForEach((IndiceArquivoDigital x) => str12 = string.Concat(new string[] { str12, "<tr><td><a href='", x.get_UrlAssinatura(), "'>", x.get_Descricao(), "</a></td></tr>" }));
+ str12 = string.Concat(str12, "</tbody></table>");
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str12);
+ break;
+ }
+ }
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Empty);
+ break;
+ }
+ case 18:
+ {
+ string str13 = string.Format("<strong>ABAIXO O LINK PARA MEU CARTÃO DE VISITA.</strong><br><a target='_blank' href='{0}{1}'>CARTÃO DE VISITA ELETRÔNICO</a>", Address.get_Card(), Recursos.Usuario.get_Id().GeraCartaoVisita());
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str13);
+ break;
+ }
+ case 19:
+ {
+ if (envio.get_Apolice() != null)
+ {
+ Uri assistance = Address.get_Assistance();
+ if (envio != null)
+ {
+ Documento apolice1 = envio.get_Apolice();
+ if (apolice1 != null)
+ {
+ obj = apolice1.get_Id().GeraAssistencia();
+ }
+ else
+ {
+ obj = null;
+ }
+ }
+ else
+ {
+ obj = null;
+ }
+ string str14 = string.Format("<strong>ABAIXO O LINK PARA O SEU CARTÃO ASSISTÊNCIA.</strong><br><a target='_blank' href='{0}{1}'>CARTÃO ASSISTÊNCIA</a>", assistance, obj);
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), str14);
+ break;
+ }
+ else
+ {
+ corpo = corpo.Replace(Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum), string.Empty);
+ break;
+ }
+ }
+ case 20:
+ {
+ string str15 = corpo;
+ string entity8 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ Documento documento1 = envio.get_Apolice();
+ if (documento1 != null)
+ {
+ str4 = documento1.get_PremioLiquido().ToString("c");
+ }
+ else
+ {
+ str4 = null;
+ }
+ corpo = str15.Replace(entity8, str4);
+ break;
+ }
+ case 21:
+ {
+ string str16 = corpo;
+ string entity9 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ Documento apolice2 = envio.get_Apolice();
+ if (apolice2 != null)
+ {
+ str5 = apolice2.get_PremioTotal().ToString("c");
+ }
+ else
+ {
+ str5 = null;
+ }
+ corpo = str16.Replace(entity9, str5);
+ break;
+ }
+ case 22:
+ {
+ string str17 = corpo;
+ string entity10 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ Documento documento2 = envio.get_Apolice();
+ if (documento2 != null)
+ {
+ FormaPagamento? formaPagamento = documento2.get_FormaPagamento();
+ if (formaPagamento.HasValue)
+ {
+ description = Gestor.Common.Validation.ValidationHelper.GetDescription(formaPagamento.GetValueOrDefault());
+ }
+ else
+ {
+ description = null;
+ }
+ }
+ else
+ {
+ description = null;
+ }
+ corpo = str17.Replace(entity10, description);
+ break;
+ }
+ case 23:
+ {
+ string str18 = corpo;
+ string entity11 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ Documento apolice3 = envio.get_Apolice();
+ if (apolice3 != null)
+ {
+ nullable1 = new decimal?(apolice3.get_NumeroParcelas());
+ }
+ else
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ if (!nullable1.HasValue || envio.get_Apolice().get_TipoRecebimento().GetValueOrDefault() == 2)
+ {
+ str6 = "Indefinido";
+ }
+ else
+ {
+ Documento documento3 = envio.get_Apolice();
+ if (documento3 != null)
+ {
+ str6 = documento3.get_NumeroParcelas().ToString();
+ }
+ else
+ {
+ str6 = null;
+ }
+ }
+ corpo = str18.Replace(entity11, str6);
+ break;
+ }
+ case 24:
+ {
+ string str19 = corpo;
+ string entity12 = Gestor.Common.Validation.ValidationHelper.GetEntity(variaveisMalaDiretum);
+ Documento apolice4 = envio.get_Apolice();
+ if (apolice4 != null)
+ {
+ nullable2 = new decimal?(apolice4.get_NumeroParcelas());
+ }
+ else
+ {
+ nullable = null;
+ nullable2 = nullable;
+ }
+ if (!nullable2.HasValue || envio.get_Apolice().get_NumeroParcelas() == decimal.Zero || envio.get_Apolice().get_TipoRecebimento().GetValueOrDefault() == 2)
+ {
+ str7 = "Verificar documento anexado";
+ }
+ else
+ {
+ valor = envio.get_Apolice().get_PremioTotal() / envio.get_Apolice().get_NumeroParcelas();
+ str7 = valor.ToString();
+ }
+ corpo = str19.Replace(entity12, str7);
+ break;
+ }
+ }
+ }
+ return corpo;
+ }
+
+ public static void ToggleSnackBar(string message, bool active = true)
+ {
+ App.SnackBar.get_Message().Content = message;
+ App.SnackBar.set_IsActive(active);
+ if (!active)
+ {
+ return;
+ }
+ Task.Factory.StartNew(new Action(Funcoes.CloseSlackBar));
+ }
+
+ public static List<ParametrosTotalizacao> TotalizacoesRelatorio<T>(Relatorio relatorio, List<ParametrosTotalizacao> parametrosAdicionados)
+ {
+ long id;
+ List<ParametrosTotalizacao> parametrosTotalizacaos = new List<ParametrosTotalizacao>();
+ List<string> strs = new List<string>();
+ switch (relatorio)
+ {
+ case 2:
+ case 3:
+ {
+ strs.Add("PremioTotal");
+ strs.Add("PremioLiquido");
+ strs.Add("MediaComissao");
+ strs.Add("ComissaoGerada");
+ strs.Add("Cancelamentos");
+ strs.Add("Novos");
+ strs.Add("NegociosProprios");
+ strs.Add("Renovacoes");
+ strs.Add("SegurosNovos");
+ strs.Add("Apolices");
+ strs.Add("Endossos");
+ strs.Add("Faturas");
+ strs.Add("TotalGeral");
+ strs.Add("MediaPonderada");
+ goto case 15;
+ }
+ case 4:
+ {
+ strs.Add("Cancelamentos");
+ strs.Add("Novos");
+ strs.Add("Renovacoes");
+ strs.Add("Apolices");
+ strs.Add("Endossos");
+ strs.Add("Faturas");
+ strs.Add("TotalProspeccao");
+ strs.Add("TotalGeral");
+ strs.Add("PremioTotal");
+ strs.Add("PremioLiquido");
+ strs.Add("ComissaoGerada");
+ goto case 15;
+ }
+ case 5:
+ {
+ strs.Add("ComissaoRecebidaBruta");
+ strs.Add("ComissaoRecebidaLiquida");
+ strs.Add("ComissaoPrevista");
+ strs.Add("Repasse");
+ strs.Add("Impostos");
+ strs.Add("PremioTotal");
+ strs.Add("PremioLiquido");
+ goto case 15;
+ }
+ case 6:
+ case 16:
+ {
+ strs.Add("ComissaoPrevista");
+ strs.Add("TotalPrevista");
+ strs.Add("TotalGeral");
+ strs.Add("TotalParcela");
+ goto case 15;
+ }
+ case 7:
+ case 11:
+ case 12:
+ case 13:
+ case 14:
+ case 15:
+ {
+ PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
+ foreach (PropertyInfo propertyInfo in
+ from in (IEnumerable<PropertyInfo>)properties
+ orderby x.GetDescriptionAttribute()
+ select )
+ {
+ if (propertyInfo.Name == "ValidationEvent" || propertyInfo.GetTypeAttribute() == "INVALID" || !strs.Contains(propertyInfo.Name) || propertyInfo.Name == "Agrupamento" || parametrosAdicionados.Any<ParametrosTotalizacao>((ParametrosTotalizacao x) => x.get_Campo() == propertyInfo.Name))
+ {
+ continue;
+ }
+ ParametrosTotalizacao parametrosTotalizacao = new ParametrosTotalizacao();
+ ParametrosTotalizacao parametrosTotalizacao1 = parametrosAdicionados.FirstOrDefault<ParametrosTotalizacao>((ParametrosTotalizacao x) => {
+ if (x.get_IdUsuario() == 0)
+ {
+ return false;
+ }
+ return x.get_Campo() == propertyInfo.Name;
+ });
+ if (parametrosTotalizacao1 != null)
+ {
+ id = parametrosTotalizacao1.get_Id();
+ }
+ else
+ {
+ id = (long)0;
+ }
+ parametrosTotalizacao.set_Id(id);
+ parametrosTotalizacao.set_Campo(propertyInfo.Name);
+ parametrosTotalizacao.set_Header(propertyInfo.GetDescriptionAttribute());
+ parametrosTotalizacao.set_IdUsuario(Recursos.Usuario.get_Id());
+ parametrosTotalizacao.set_Relatorio(relatorio);
+ parametrosTotalizacaos.Add(parametrosTotalizacao);
+ }
+ return parametrosTotalizacaos;
+ }
+ case 8:
+ {
+ strs.Add("PremioTotal");
+ strs.Add("PremioLiquido");
+ strs.Add("ComissaoRecebidaBruta");
+ strs.Add("MediaComissao");
+ strs.Add("TotalPrevista");
+ strs.Add("ComissaoGerada");
+ strs.Add("Cancelamentos");
+ strs.Add("Novos");
+ strs.Add("Renovacoes");
+ strs.Add("Apolices");
+ strs.Add("Endossos");
+ strs.Add("Faturas");
+ strs.Add("TotalGeral");
+ goto case 15;
+ }
+ case 9:
+ case 10:
+ {
+ strs.Add("Liquidado");
+ strs.Add("ValorLiquidado");
+ strs.Add("Pendente");
+ strs.Add("TotalGeral");
+ strs.Add("TotalClientes");
+ strs.Add("TotalTerceiros");
+ goto case 15;
+ }
+ default:
+ {
+ goto case 15;
+ }
+ }
+ }
+
+ public static long UnixTimeStamp()
+ {
+ DateTime utcNow = DateTime.UtcNow;
+ TimeSpan timeSpan = utcNow.Subtract(new DateTime(1970, 1, 1));
+ return (long)timeSpan.TotalSeconds;
+ }
+
+ public static string ValidaNomePlanilha(this string nome, string agrupamento = "", int index = 0)
+ {
+ if (string.IsNullOrWhiteSpace(nome))
+ {
+ nome = agrupamento;
+ }
+ nome = nome.Replace("/", "_").Replace(":", " ").Replace("*", " ").Replace("?", "").Trim();
+ if (index > 0)
+ {
+ nome = string.Format("{0} {1}", index, nome);
+ }
+ if (nome.Length > 30)
+ {
+ nome = nome.Substring(0, 30);
+ }
+ return nome;
+ }
+
+ public static async Task<bool[]> VerificarPagamento(long id)
+ {
+ bool[] flagArray = new bool[2];
+ List<Parcela> parcelas = await (new ParcelaServico()).BuscarParcelas(id);
+ if (parcelas.Any<Parcela>((Parcela x) => x.get_DataRecebimento().HasValue))
+ {
+ flagArray[0] = true;
+ }
+ List<VendedorParcela> vendedorParcelas = await (new VendedorServico()).BuscaRepasse(id);
+ if (vendedorParcelas.Any<VendedorParcela>((VendedorParcela x) => x.get_DataPagamento().HasValue))
+ {
+ flagArray[1] = true;
+ }
+ bool[] flagArray1 = flagArray;
+ flagArray = null;
+ return flagArray1;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/HttpHelper.cs b/Codemerx/Gestor.Application/Helpers/HttpHelper.cs new file mode 100644 index 0000000..e042d1b --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/HttpHelper.cs @@ -0,0 +1,103 @@ +using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Linq;
+using System.Net.Http;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public static class HttpHelper
+ {
+ public static Uri AddQuery<T>(this Uri uri, string name, T value)
+ {
+ //
+ // Current member / type: System.Uri Gestor.Application.Helpers.HttpHelper::AddQuery(System.Uri,System.String,T)
+ // File path: C:\AggerSeguros\Gestor.Application.exe
+ //
+ // Product version: 0.0.0.0
+ // Exception in: System.Uri AddQuery(System.Uri,System.String,T)
+ //
+ // Managed pointer usage not in SSA
+ // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.CheckForAssignment(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 100
+ // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitBinaryExpression(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 80
+ // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351
+ // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.VisitExpressions() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 41
+ // at Telerik.JustDecompiler.Steps.ManagedPointersRemovalStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\ManagedPointersRemovalStep.cs:line 29
+ // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100
+ // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72
+ // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61
+ // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133
+ //
+ // mailto: JustDecompilePublicFeedback@telerik.com
+
+ }
+
+ public static Dictionary<string, string> ParseQueryString(this Uri uri)
+ {
+ int num = uri.Query.IndexOf('?') + 1;
+ return (
+ from o in uri.Query.Substring(num).Split(new char[] { '&' })
+ select o.Split(new char[] { '=' }) into items
+ where (int)items.Length == 2
+ select items).ToDictionary<string[], string, string>((string[] pair) => pair[0], (string[] pair) => pair[1]);
+ }
+
+ public static Uri SetQuery(this Uri uri, string name, string value, bool escapeValue = true)
+ {
+ UriBuilder uriBuilder = new UriBuilder(uri);
+ Dictionary<string, string> strs = uri.ParseQueryString();
+ string str = (escapeValue ? Uri.EscapeDataString(value) : value);
+ if (strs.ContainsKey(name))
+ {
+ strs.Remove(name);
+ }
+ strs.Add(name, str);
+ List<string> list = (
+ from x in strs
+ select string.Concat(x.Key, "=", x.Value)).ToList<string>();
+ uriBuilder.Query = string.Join("&", list);
+ return uriBuilder.Uri;
+ }
+
+ public static string ToBase64BasicEncode(this string value)
+ {
+ return string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(value)));
+ }
+
+ public static StringContent ToHttpContent<T>(this T content, Encoding encoding = null, string mediaType = "application/json")
+ {
+ return new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, mediaType);
+ }
+
+ public static JObject ToJObject(this string jsonString)
+ {
+ JObject jObject;
+ try
+ {
+ jObject = JObject.Parse(jsonString);
+ }
+ catch (Exception exception)
+ {
+ jObject = null;
+ }
+ return jObject;
+ }
+
+ public static JObject ToJObject(this HttpContent content)
+ {
+ return content.ReadAsStringAsync().Result.ToJObject();
+ }
+
+ public static Uri ToUri(this string uri)
+ {
+ Uri uri1;
+ Uri.TryCreate(uri, UriKind.Absolute, out uri1);
+ return uri1;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Instancia.cs b/Codemerx/Gestor.Application/Helpers/Instancia.cs new file mode 100644 index 0000000..5c68db1 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Instancia.cs @@ -0,0 +1,75 @@ +using Gestor.Application;
+using Gestor.Common.Helpers;
+using Gestor.Infrastructure.UnitOfWork.Generic;
+using Gestor.Infrastructure.UnitOfWork.Logic;
+using System;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public class Instancia
+ {
+ public static string Conexao;
+
+ public static Gestor.Application.App App
+ {
+ get;
+ set;
+ }
+
+ public static UnitOfWork Commited
+ {
+ get
+ {
+ return Instancia.UnitOfWork(true);
+ }
+ }
+
+ public static UnitOfWork Read
+ {
+ get
+ {
+ return Instancia.UnitOfWork(false);
+ }
+ }
+
+ public Instancia()
+ {
+ }
+
+ public static void DeleteCfg()
+ {
+ string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
+ string str1 = string.Concat(Connection.Catalog, ".cfg");
+ if (File.Exists(string.Concat(str, str1)))
+ {
+ File.Delete(string.Concat(str, str1));
+ }
+ }
+
+ public static void ExcluirCfg()
+ {
+ File.Delete(string.Concat("Data_", Connection.Catalog, ".cfg"));
+ File.Delete(string.Concat("File_", Connection.Catalog, ".cfg"));
+ File.Delete(string.Concat("Sign_", Connection.Catalog, ".cfg"));
+ }
+
+ private static UnitOfWork UnitOfWork(bool withTransaction = true)
+ {
+ DataBaseParameters.set_NovoGestor(true);
+ Instancia.Conexao = Instancia.Conexao ?? Connection.GetConnection(true);
+ if (Instancia.Conexao == null)
+ {
+ return Instancia.App.ConnectionRetry().Result;
+ }
+ UnitOfWork unitOfWork = new UnitOfWork(Instancia.Conexao, withTransaction);
+ if (unitOfWork.get_HasSession())
+ {
+ return unitOfWork;
+ }
+ return Instancia.App.ConnectionRetry().Result;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs b/Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs new file mode 100644 index 0000000..6241ae1 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/InstanciaAssinador.cs @@ -0,0 +1,44 @@ +using Assinador.Infrastructure.UnitOfWork.Logic;
+using Gestor.Application;
+using System;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+ public class InstanciaAssinador
+ {
+ public static string EnderecoConexao;
+
+ public static Gestor.Application.App App
+ {
+ get;
+ set;
+ }
+
+ public static UnitOfWork Commited
+ {
+ get
+ {
+ return InstanciaAssinador.UnitOfWork(true);
+ }
+ }
+
+ public static UnitOfWork Read
+ {
+ get
+ {
+ return InstanciaAssinador.UnitOfWork(false);
+ }
+ }
+
+ public InstanciaAssinador()
+ {
+ }
+
+ private static UnitOfWork UnitOfWork(bool withTransaction = true)
+ {
+ InstanciaAssinador.EnderecoConexao = InstanciaAssinador.EnderecoConexao ?? Connection.GetConnection(true);
+ return new UnitOfWork(InstanciaAssinador.EnderecoConexao, withTransaction);
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/LicenseHelper.cs b/Codemerx/Gestor.Application/Helpers/LicenseHelper.cs new file mode 100644 index 0000000..e82c145 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/LicenseHelper.cs @@ -0,0 +1,572 @@ +using Agger.Registro;
+using Gestor.Common.Helpers;
+using Gestor.Common.Validation;
+using Gestor.Model.API;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Seguros;
+using Gestor.Model.License;
+using Microsoft.Win32;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public class LicenseHelper
+ {
+ private string _guid
+ {
+ get;
+ set;
+ }
+
+ public static DateTime DataAtual
+ {
+ get;
+ private set;
+ }
+
+ public static int? DiasRestantes
+ {
+ get;
+ set;
+ }
+
+ public static Gestor.Model.License.Instalacao Instalacao
+ {
+ get;
+ set;
+ }
+
+ public static List<Licenca> Produtos
+ {
+ get;
+ set;
+ }
+
+ public static StatusLicenca Status
+ {
+ get;
+ set;
+ }
+
+ static LicenseHelper()
+ {
+ LicenseHelper.Status = 1;
+ }
+
+ public LicenseHelper()
+ {
+ }
+
+ public async Task<string> FindKey()
+ {
+ string str;
+ string str1 = EncryptionHelper.Decrypt((new RegistryHelper(ApplicationHelper.Subkey)).ForceRead("MACHINEID", false));
+ str = (string.IsNullOrEmpty(str1) ? string.Concat(this.GetMacAddress(), this.GetMachineSerial()) : str1);
+ string str2 = str;
+ string str3 = await Gestor.Application.Helpers.Connection.Get<string>(string.Concat("Installation/Serial/", str2), false, false);
+ return str3;
+ }
+
+ public NetworkInterface FindMacAddress(string macToSearch)
+ {
+ string[] strArrays = macToSearch.Split(new char[] { '|' });
+ return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault<NetworkInterface>((NetworkInterface ni) => strArrays.Contains<string>(ni.GetPhysicalAddress().ToString()));
+ }
+
+ private string GetFrameworkVersion()
+ {
+ try
+ {
+ using (RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
+ {
+ if (registryKey != null && registryKey.GetValue("Version") != null)
+ {
+ return registryKey.GetValue("Version").ToString();
+ }
+ }
+ }
+ catch
+ {
+ }
+ return "<4.5";
+ }
+
+ public async Task<List<Gestor.Model.License.Instalacao>> GetInstalacoes()
+ {
+ List<Gestor.Model.License.Instalacao> instalacaos = await Gestor.Application.Helpers.Connection.Get<List<Gestor.Model.License.Instalacao>>(string.Format("Installation/Machine/{0}", ApplicationHelper.IdFornecedor), true, false);
+ return instalacaos;
+ }
+
+ public string GetMacAddress()
+ {
+ IEnumerable<string> strs = ((IEnumerable<NetworkInterface>)NetworkInterface.GetAllNetworkInterfaces()).Where<NetworkInterface>((NetworkInterface ni) => {
+ if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
+ {
+ return true;
+ }
+ return ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211;
+ }).OrderByDescending<NetworkInterface, string>((NetworkInterface ni) => ni.Id).Select<NetworkInterface, string>((NetworkInterface x) => x.GetPhysicalAddress().ToString());
+ return string.Join("", strs);
+ }
+
+ private string GetMachineSerial()
+ {
+ if (string.IsNullOrEmpty(this._guid))
+ {
+ this._guid = Guid.NewGuid().ToString();
+ }
+ return this._guid;
+ }
+
+ public async Task<string> Registrar(string chave)
+ {
+ string str3 = await Task.Run<string>(() => {
+ IEnumerable<string> strs;
+ if (string.IsNullOrEmpty(chave))
+ {
+ return "false";
+ }
+ RegistryHelper registryHelper = new RegistryHelper("");
+ string[] strArrays = EncryptionHelper.Decrypt(chave).Split(new char[] { ' ' });
+ if ((int)strArrays.Length < 2)
+ {
+ return "false";
+ }
+ string str = registryHelper.Verificar(strArrays[0], EncryptionHelper.Encrypt(strArrays[0]));
+ if (str != "false")
+ {
+ if (str == "root")
+ {
+ return "root";
+ }
+ ApplicationHelper.NumeroSerial = strArrays[0];
+ ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get<string>("Maintenance/Customer", true, false).Result);
+ Instancia.Conexao = null;
+ ApplicationHelper.Subkey = strArrays[0];
+ return "true";
+ }
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ string result = Gestor.Application.Helpers.Connection.Get<string>("Installation/Time", false, true).Result ?? networkTime.ToString("d");
+ if (!ApplicationHelper.Conectado)
+ {
+ return "false";
+ }
+ LicenseHelper.DataAtual = DateTime.Parse(string.Format("{0} {1}:{2}:{3}", new object[] { result, networkTime.Hour, networkTime.Minute, networkTime.Second }));
+ DateTime dateTime = DateTime.Parse(strArrays[1]);
+ if (Math.Abs((LicenseHelper.DataAtual - dateTime).TotalDays) > 1)
+ {
+ return "false";
+ }
+ string str1 = EncryptionHelper.Decrypt(registryHelper.Read("NS", true));
+ string str2 = registryHelper.Read("SERIALS", false);
+ if (string.IsNullOrWhiteSpace(str2) && !string.IsNullOrWhiteSpace(str1))
+ {
+ registryHelper.Write<string>("SERIALS", EncryptionHelper.Encrypt(str1), false);
+ str2 = registryHelper.Read("SERIALS", false);
+ }
+ strs = (str2 != null ? EncryptionHelper.Decrypt(str2).Split(new char[] { ':' }).ToList<string>() : new List<string>());
+ List<string> strs1 = new List<string>();
+ strs.Distinct<string>().ToList<string>().ForEach((string x) => {
+ if (registryHelper.Verificar(x, EncryptionHelper.Encrypt(x)) == "false")
+ {
+ return;
+ }
+ strs1.Add(x);
+ });
+ strs1.Add(strArrays[0]);
+ registryHelper.Write<string>("SERIALS", EncryptionHelper.Encrypt(string.Join(":", strs1.Distinct<string>())), false);
+ registryHelper.set_Serial((strs1.Count > 1 ? string.Concat("\\", strArrays[0]) : ""));
+ ApplicationHelper.Subkey = (strs1.Count > 1 ? strArrays[0] : "");
+ ApplicationHelper.NumeroSerial = strArrays[0];
+ registryHelper.Write<string>("PERFIL", Gestor.Application.Helpers.Connection.Get<string>(string.Concat("Customer/Name/", strArrays[0]), true, false).Result, true);
+ registryHelper.Write<string>("CURRENTDATE", EncryptionHelper.Encrypt(result), true);
+ registryHelper.Write<string>("DATE", result, true);
+ registryHelper.Write<string>("NS", EncryptionHelper.Encrypt(strArrays[0]), true);
+ registryHelper.Write<string>("INSTALL", EncryptionHelper.Encrypt(strArrays[0]), true);
+ ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get<string>("Maintenance/Customer", true, false).Result);
+ registryHelper.Write<string>("CUSTOMER", EncryptionHelper.Encrypt(ApplicationHelper.IdFornecedor.ToString()), true);
+ Instancia.Conexao = null;
+ return "true";
+ });
+ return str3;
+ }
+
+ public async Task<bool> RegistrarMaquina()
+ {
+ bool flag = await Task.Run<bool>(() => {
+ int quantidade;
+ string str;
+ if (!ApplicationHelper.Conectado)
+ {
+ return false;
+ }
+ List<Gestor.Model.License.Instalacao> result = this.GetInstalacoes().Result;
+ Licenca licenca = LicenseHelper.Produtos.FirstOrDefault<Licenca>((Licenca x) => x.get_Produto() == 1);
+ quantidade = (licenca != null ? licenca.get_Quantidade() : 0);
+ if (quantidade <= result.Count<Gestor.Model.License.Instalacao>((Gestor.Model.License.Instalacao x) => x.get_Gerenciador() != null))
+ {
+ return false;
+ }
+ string str1 = "";
+ RegistryHelper registryHelper = new RegistryHelper("");
+ if (LicenseHelper.Instalacao == null)
+ {
+ string machineSerial = this.GetMachineSerial();
+ str1 = EncryptionHelper.Encrypt(string.Concat(this.GetMacAddress(), " ", machineSerial));
+ Gestor.Model.License.Instalacao instalacao = new Gestor.Model.License.Instalacao();
+ instalacao.set_IdFornecedor(ApplicationHelper.IdFornecedor);
+ instalacao.set_Data(LicenseHelper.DataAtual);
+ instalacao.set_Gerenciador(machineSerial);
+ instalacao.set_NomeMaquina(Environment.MachineName);
+ instalacao.set_UsuarioMaquina(Environment.UserName);
+ instalacao.set_UsuarioId(Recursos.Usuario.get_Id());
+ instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome());
+ instalacao.set_UltimoAcesso(DateTime.Now);
+ Gestor.Model.License.Instalacao instalacao1 = instalacao;
+ IPAddress pAddress = ((IEnumerable<IPAddress>)Recursos.Host.AddressList).FirstOrDefault<IPAddress>((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork);
+ if (pAddress != null)
+ {
+ str = pAddress.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ instalacao1.set_Ip(str);
+ instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() }));
+ LicenseHelper.Instalacao = instalacao;
+ }
+ registryHelper.Write<string>("MACHINEID", str1, false);
+ LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put<Gestor.Model.License.Instalacao>("Installation/Machine", LicenseHelper.Instalacao).Result;
+ return true;
+ });
+ return flag;
+ }
+
+ public async Task<Tuple<bool, string>> VerificarAcesso()
+ {
+ Tuple<bool, string> tuple = await Task.Run<Tuple<bool, string>>(() => {
+ DateTime dateTime;
+ TimeSpan timeSpan;
+ DateTime liberacao;
+ RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey);
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ DateTime date = networkTime.Date;
+ if (!ApplicationHelper.Conectado)
+ {
+ if ((date - LicenseHelper.DataAtual).TotalDays > 2)
+ {
+ return new Tuple<bool, string>(true, "DATA INVÁLIDA");
+ }
+ dateTime = DateTime.Parse(EncryptionHelper.Decrypt(registryHelper.Read("EXPIRATION", true)));
+ timeSpan = dateTime.AddDays(5) - LicenseHelper.DataAtual;
+ LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays);
+ int? diasRestantes = LicenseHelper.DiasRestantes;
+ if (diasRestantes.GetValueOrDefault() < 1 & diasRestantes.HasValue)
+ {
+ return new Tuple<bool, string>(true, "SISTEMA BLOQUEADO");
+ }
+ if (EncryptionHelper.Decrypt(registryHelper.Read("BLOCK", true)) == "TRUE")
+ {
+ return new Tuple<bool, string>(true, "SISTEMA BLOQUEADO");
+ }
+ if (EncryptionHelper.Decrypt(registryHelper.Read("CONSULTA", true)) == "TRUE")
+ {
+ LicenseHelper.Status = 2;
+ }
+ string str = EncryptionHelper.Decrypt(registryHelper.Read("PRODUTOS", true));
+ if (string.IsNullOrEmpty(str))
+ {
+ LicenseHelper.Status = 3;
+ return new Tuple<bool, string>(false, "SISTEMA CANCELADO");
+ }
+ LicenseHelper.Produtos = JsonConvert.DeserializeObject<List<Licenca>>(str);
+ LicenseHelper.Status = (LicenseHelper.Status != 2 ? 0 : LicenseHelper.Status);
+ return new Tuple<bool, string>(true, EnumHelper.GetDescription<StatusLicenca>(LicenseHelper.Status));
+ }
+ List<Access> result = Gestor.Application.Helpers.Connection.Get<List<Access>>(string.Format("Access/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result;
+ List<long> nums = new List<long>()
+ {
+ (long)2,
+ (long)3,
+ (long)4,
+ (long)5,
+ (long)24,
+ (long)10024
+ };
+ LicenseHelper.Produtos = (
+ from x in result
+ group x by new { ProductId = x.get_ProductId(), Status = x.get_Status() }).Select((x) => {
+ DateTime expiration;
+ Licenca licenca = new Licenca();
+ licenca.set_Produto((int)x.Key.ProductId.GetValueOrDefault());
+ var collection1 = x;
+ Func<Access, IEnumerable<AccessControl>> u003cu003e9_2110 = LicenseHelper.u003cu003ec.u003cu003e9__21_10;
+ if (u003cu003e9_2110 == null)
+ {
+ u003cu003e9_2110 = (Access c) => c.get_Control();
+ LicenseHelper.u003cu003ec.u003cu003e9__21_10 = u003cu003e9_2110;
+ }
+ IEnumerable<AccessControl> accessControls1 = collection1.SelectMany<Access, AccessControl>(u003cu003e9_2110);
+ Func<AccessControl, DateTime> u003cu003e9_2111 = LicenseHelper.u003cu003ec.u003cu003e9__21_11;
+ if (u003cu003e9_2111 == null)
+ {
+ u003cu003e9_2111 = (AccessControl l) => l.get_Expiration();
+ LicenseHelper.u003cu003ec.u003cu003e9__21_11 = u003cu003e9_2111;
+ }
+ AccessControl accessControl1 = accessControls1.OrderByDescending<AccessControl, DateTime>(u003cu003e9_2111).FirstOrDefault<AccessControl>();
+ expiration = (accessControl1 != null ? accessControl1.get_Expiration() : networkTime.AddDays(-1));
+ licenca.set_Liberacao(expiration);
+ licenca.set_AcessoLiberado(x.All<Access>((Access l) => {
+ if (l.get_AgreementId().HasValue && nums.Contains(l.get_AgreementId().Value))
+ {
+ return true;
+ }
+ var collection = x;
+ Func<Access, IEnumerable<AccessControl>> u003cu003e9_2114 = LicenseHelper.u003cu003ec.u003cu003e9__21_14;
+ if (u003cu003e9_2114 == null)
+ {
+ u003cu003e9_2114 = (Access c) => c.get_Control();
+ LicenseHelper.u003cu003ec.u003cu003e9__21_14 = u003cu003e9_2114;
+ }
+ IEnumerable<AccessControl> accessControls = collection.SelectMany<Access, AccessControl>(u003cu003e9_2114);
+ Func<AccessControl, DateTime> u003cu003e9_2115 = LicenseHelper.u003cu003ec.u003cu003e9__21_15;
+ if (u003cu003e9_2115 == null)
+ {
+ u003cu003e9_2115 = (AccessControl d) => d.get_Expiration();
+ LicenseHelper.u003cu003ec.u003cu003e9__21_15 = u003cu003e9_2115;
+ }
+ AccessControl accessControl = accessControls.OrderByDescending<AccessControl, DateTime>(u003cu003e9_2115).FirstOrDefault<AccessControl>();
+ if (accessControl == null)
+ {
+ return false;
+ }
+ return accessControl.get_Expiration() >= date;
+ }));
+ var collection2 = x;
+ Func<Access, decimal> u003cu003e9_2113 = LicenseHelper.u003cu003ec.u003cu003e9__21_13;
+ if (u003cu003e9_2113 == null)
+ {
+ u003cu003e9_2113 = (Access l) => l.get_Ammount().GetValueOrDefault();
+ LicenseHelper.u003cu003ec.u003cu003e9__21_13 = u003cu003e9_2113;
+ }
+ licenca.set_Quantidade((int)collection2.Sum<Access>(u003cu003e9_2113));
+ licenca.set_Status(int.Parse(x.Key.Status ?? "1"));
+ return licenca;
+ }).ToList<Licenca>();
+ if (LicenseHelper.Produtos != null && LicenseHelper.Produtos.Count != 0)
+ {
+ if (!LicenseHelper.Produtos.All<Licenca>((Licenca x) => x.get_Status() == 3))
+ {
+ Licenca licenca1 = (
+ from x in LicenseHelper.Produtos
+ orderby x.get_Liberacao()
+ select x).FirstOrDefault<Licenca>((Licenca x) => {
+ if (x.get_AcessoLiberado())
+ {
+ return false;
+ }
+ return x.get_Status() == 1;
+ });
+ liberacao = (licenca1 != null ? licenca1.get_Liberacao() : networkTime);
+ DateTime dateTime1 = liberacao;
+ timeSpan = dateTime1 - date;
+ LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays);
+ registryHelper.Write<string>("EXPIRATION", EncryptionHelper.Encrypt(dateTime1.ToString("d")), true);
+ registryHelper.Write<string>("BLOCK", (dateTime1 >= date ? EncryptionHelper.Encrypt("FALSE") : EncryptionHelper.Encrypt("TRUE")), true);
+ bool flag = LicenseHelper.Produtos.Any<Licenca>((Licenca x) => {
+ if (x.get_Produto() != 1)
+ {
+ return false;
+ }
+ return x.get_Status() == 4;
+ });
+ registryHelper.Write<string>("CONSULTA", EncryptionHelper.Encrypt(flag.ToString().ToUpper()), true);
+ if (flag)
+ {
+ LicenseHelper.Status = 2;
+ }
+ LicenseHelper.Status = (dateTime1 < date ? 1 : 0);
+ if (LicenseHelper.Produtos.Any<Licenca>((Licenca x) => x.get_Produto() == 1) && LicenseHelper.Status == null)
+ {
+ registryHelper.Write<string>("P1", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true);
+ registryHelper.Write<string>("P5", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true);
+ registryHelper.Write<string>("M1", EncryptionHelper.Encrypt("TRUE"), true);
+ }
+ IEnumerable<Licenca> produtos =
+ from x in LicenseHelper.Produtos
+ where x.get_Status() == 1
+ select x;
+ JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
+ jsonSerializerSetting.set_ReferenceLoopHandling(1);
+ registryHelper.Write<string>("PRODUTOS", EncryptionHelper.Encrypt(JsonConvert.SerializeObject(produtos, 1, jsonSerializerSetting)), true);
+ if (LicenseHelper.Produtos.Find((Licenca p) => p.get_Produto() == 86) != null)
+ {
+ return new Tuple<bool, string>(true, EnumHelper.GetDescription<StatusLicenca>(LicenseHelper.Status));
+ }
+ if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(AssinadorHelper.Key().Result))
+ {
+ List<Licenca> licencas = LicenseHelper.Produtos;
+ Licenca licenca2 = new Licenca();
+ licenca2.set_AcessoLiberado(true);
+ licenca2.set_Liberacao(date);
+ licenca2.set_Produto(86);
+ licenca2.set_Quantidade(0);
+ licenca2.set_Status(1);
+ licencas.Add(licenca2);
+ }
+ return new Tuple<bool, string>(true, EnumHelper.GetDescription<StatusLicenca>(LicenseHelper.Status));
+ }
+ }
+ dateTime = networkTime.AddDays(-1);
+ registryHelper.Write<string>("EXPIRATION", EncryptionHelper.Encrypt(dateTime.ToString("d")), true);
+ registryHelper.Write<string>("BLOCK", EncryptionHelper.Encrypt("TRUE"), true);
+ LicenseHelper.Status = 3;
+ return new Tuple<bool, string>(false, "");
+ });
+ return tuple;
+ }
+
+ public async Task<bool> VerificarMaquina()
+ {
+ bool flag = await Task.Run<bool>(() => {
+ Guid guid;
+ string str;
+ Gestor.Model.License.Instalacao instalacao;
+ string str1;
+ RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey);
+ string macAddress = this.GetMacAddress();
+ if (string.IsNullOrEmpty(registryHelper.Read("MACHINEID", false)))
+ {
+ registryHelper.Write<string>("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", this.GetMachineSerial())), false);
+ }
+ string[] strArrays = EncryptionHelper.Decrypt(registryHelper.Read("MACHINEID", false)).Split(new char[] { ' ' });
+ string machineSerial = ((int)strArrays.Length > 1 ? strArrays[1] : strArrays[0]);
+ if (ApplicationHelper.Conectado)
+ {
+ List<Gestor.Model.License.Instalacao> result = Gestor.Application.Helpers.Connection.Get<List<Gestor.Model.License.Instalacao>>(string.Concat("Installation/Machine/", machineSerial, "/GerenciadorList"), true, false).Result;
+ if (!Guid.TryParse(machineSerial, out guid))
+ {
+ machineSerial = this.GetMachineSerial();
+ }
+ this._guid = machineSerial;
+ if (result != null)
+ {
+ instalacao = result.FirstOrDefault<Gestor.Model.License.Instalacao>((Gestor.Model.License.Instalacao x) => x.get_IdFornecedor() == ApplicationHelper.IdFornecedor);
+ }
+ else
+ {
+ instalacao = null;
+ }
+ LicenseHelper.Instalacao = instalacao;
+ if (LicenseHelper.Instalacao != null && LicenseHelper.Instalacao.get_IdFornecedor() != ApplicationHelper.IdFornecedor)
+ {
+ LicenseHelper.Instalacao = null;
+ }
+ if (LicenseHelper.Instalacao != null)
+ {
+ LicenseHelper.Instalacao.set_Gerenciador(machineSerial);
+ LicenseHelper.Instalacao.set_UsuarioId(Recursos.Usuario.get_Id());
+ LicenseHelper.Instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome());
+ Gestor.Model.License.Instalacao instalacao1 = LicenseHelper.Instalacao;
+ IPAddress pAddress = ((IEnumerable<IPAddress>)Recursos.Host.AddressList).FirstOrDefault<IPAddress>((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork);
+ if (pAddress != null)
+ {
+ str1 = pAddress.ToString();
+ }
+ else
+ {
+ str1 = null;
+ }
+ instalacao1.set_Ip(str1);
+ LicenseHelper.Instalacao.set_UltimoAcesso(DateTime.Now);
+ LicenseHelper.Instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() }));
+ LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put<Gestor.Model.License.Instalacao>("Installation/Machine", LicenseHelper.Instalacao).Result;
+ registryHelper.Write<string>("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", LicenseHelper.Instalacao.get_Gerenciador())), false);
+ }
+ registryHelper.Write<string>("ACCESS", (LicenseHelper.Instalacao != null || this.RegistrarMaquina().Result ? EncryptionHelper.Encrypt("TRUE") : EncryptionHelper.Encrypt("FALSE")), false);
+ }
+ else if (EncryptionHelper.Decrypt(registryHelper.Read("ACCESS", false)) == "TRUE")
+ {
+ Gestor.Model.License.Instalacao instalacao2 = new Gestor.Model.License.Instalacao();
+ instalacao2.set_IdFornecedor(ApplicationHelper.IdFornecedor);
+ instalacao2.set_Data(LicenseHelper.DataAtual);
+ instalacao2.set_Gerenciador(machineSerial);
+ instalacao2.set_NomeMaquina(Environment.MachineName);
+ instalacao2.set_UsuarioMaquina(Environment.UserName);
+ instalacao2.set_UsuarioId(Recursos.Usuario.get_Id());
+ instalacao2.set_UsuarioSistema(Recursos.Usuario.get_Nome());
+ instalacao2.set_UltimoAcesso(DateTime.Now);
+ IPAddress pAddress1 = ((IEnumerable<IPAddress>)Recursos.Host.AddressList).FirstOrDefault<IPAddress>((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork);
+ if (pAddress1 != null)
+ {
+ str = pAddress1.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ instalacao2.set_Ip(str);
+ LicenseHelper.Instalacao = instalacao2;
+ }
+ if (!LicenseHelper.Produtos.Any<Licenca>((Licenca x) => x.get_Produto() == 1))
+ {
+ return false;
+ }
+ if (LicenseHelper.Instalacao != null)
+ {
+ return true;
+ }
+ return this.RegistrarMaquina().Result;
+ });
+ return flag;
+ }
+
+ public async Task<bool> VerificarRegistro()
+ {
+ bool flag = await Task.Run<bool>(() => {
+ long idFornecedor;
+ RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey);
+ if (string.IsNullOrEmpty(registryHelper.Read("NS", true)))
+ {
+ return false;
+ }
+ string str = EncryptionHelper.Decrypt(registryHelper.Read("CUSTOMER", true));
+ if (long.TryParse(str, out idFornecedor))
+ {
+ ApplicationHelper.IdFornecedor = long.Parse(str);
+ }
+ else
+ {
+ ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get<string>("Configuration/Customer", true, false).Result);
+ idFornecedor = ApplicationHelper.IdFornecedor;
+ registryHelper.Write<string>("CUSTOMER", EncryptionHelper.Encrypt(idFornecedor.ToString()), true);
+ }
+ string result = Gestor.Application.Helpers.Connection.Get<string>("Installation/Time", false, false).Result ?? Funcoes.GetNetworkTime().ToString("d");
+ LicenseHelper.DataAtual = DateTime.Parse(result);
+ registryHelper.Write<string>("CURRENTDATE", EncryptionHelper.Encrypt(result), true);
+ registryHelper.Write<string>("DATE", result, true);
+ List<object> objs = Gestor.Application.Helpers.Connection.Get<List<object>>(string.Format("Configuration/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result;
+ ApplicationHelper.Beta = (objs == null ? false : objs.Any<object>((object x) => x.ToString().Contains("\"Tipo\": 45")));
+ Address.set_Beta(ApplicationHelper.Beta);
+ return true;
+ });
+ return flag;
+ }
+
+ public async Task<Tuple<bool, string>> VerificarVersao()
+ {
+ Tuple<bool, string> tuple = new Tuple<bool, string>(bool.Parse(await Gestor.Application.Helpers.Connection.Get<string>(string.Format("Installation/Version/{0}", ApplicationHelper.IdFornecedor), true, false)), "VERSÃO INDISPONÍVEL");
+ return tuple;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/MailHelper.cs b/Codemerx/Gestor.Application/Helpers/MailHelper.cs new file mode 100644 index 0000000..e9f2cde --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/MailHelper.cs @@ -0,0 +1,745 @@ +using CsQuery.ExtensionMethods.Internal;
+using Gestor.Application.ViewModels;
+using Gestor.Common.Helpers;
+using Gestor.Common.Validation;
+using Gestor.Infrastructure.Repository.Interface;
+using Gestor.Infrastructure.UnitOfWork.Generic;
+using Gestor.Infrastructure.UnitOfWork.Logic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Ferramentas;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.MalaDireta;
+using Gestor.Model.Domain.Seguros;
+using Gestor.Model.Helper;
+using Google.Apis.Auth.OAuth2;
+using Google.Apis.Gmail.v1;
+using Google.Apis.Gmail.v1.Data;
+using Google.Apis.Requests;
+using Google.Apis.Services;
+using Microsoft.Identity.Client;
+using MimeKit;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Mail;
+using System.Net.Mime;
+using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Gestor.Application.Helpers
+{
+ public class MailHelper
+ {
+ public MailHelper()
+ {
+ }
+
+ private static StringContent ConverteMailMessageParaStringContent(MailMessage message)
+ {
+ StringContent stringContent;
+ MimeMessage mimeMessage = (MimeMessage)message;
+ using (MemoryStream memoryStream = new MemoryStream())
+ {
+ mimeMessage.WriteTo(memoryStream, new CancellationToken());
+ memoryStream.Position = (long)0;
+ using (StreamReader streamReader = new StreamReader(memoryStream))
+ {
+ string end = streamReader.ReadToEnd();
+ stringContent = new StringContent(Convert.ToBase64String(Encoding.ASCII.GetBytes(end)), Encoding.UTF8, "text/plain");
+ }
+ }
+ return stringContent;
+ }
+
+ public static AlternateView CreateAlternateView(string mailBody)
+ {
+ int i;
+ List<LinkedResource> linkedResources = new List<LinkedResource>();
+ string[] array = (
+ from Match m in Regex.Matches(mailBody, "<img(.*?)src=\"file:(///).*?>", RegexOptions.IgnoreCase)
+ select m.Groups[0].Value).ToArray<string>();
+ for (i = 0; i < (int)array.Length; i++)
+ {
+ string value = Regex.Match(array[i], "(?<=src=\")(.*?)(?=\")", RegexOptions.IgnoreCase).Value;
+ string str = Regex.Match(value, "file:(///).*\\.(.*)", RegexOptions.IgnoreCase).Groups[2].Value;
+ if (str == "jpg")
+ {
+ str = "jpeg";
+ }
+ if (Uri.IsWellFormedUriString(value, UriKind.Absolute))
+ {
+ Uri uri = new Uri(value);
+ if (File.Exists(uri.LocalPath))
+ {
+ mailBody = mailBody.Replace(value, string.Concat("data:image/", str, ";base64,", Convert.ToBase64String(File.ReadAllBytes(uri.LocalPath))));
+ }
+ }
+ }
+ array = (
+ from Match m in Regex.Matches(mailBody, "<img.*?>", RegexOptions.IgnoreCase)
+ select m.Groups[0].Value).ToArray<string>();
+ for (i = 0; i < (int)array.Length; i++)
+ {
+ string str1 = array[i];
+ string value1 = Regex.Match(str1, "(?<=src=\").*(?=\")", RegexOptions.IgnoreCase).Value;
+ string value2 = Regex.Match(value1, "(?<=data:).*(?=;)", RegexOptions.IgnoreCase).Value;
+ if (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(value2) || Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(value1))
+ {
+ mailBody = mailBody.Replace(str1, string.Empty);
+ }
+ else
+ {
+ byte[] numArray = Convert.FromBase64String(Regex.Match(value1, "(?<=base64,)[^\"]*", RegexOptions.IgnoreCase).Value);
+ string str2 = Guid.NewGuid().ToString();
+ linkedResources.Add(new LinkedResource(new MemoryStream(numArray), value2)
+ {
+ ContentId = str2,
+ TransferEncoding = TransferEncoding.Base64
+ });
+ string str3 = string.Concat("cid:", str2);
+ mailBody = mailBody.Replace(value1, str3);
+ }
+ }
+ AlternateView alternateView = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
+ ExtensionMethods.AddRange<LinkedResource>(alternateView.LinkedResources, linkedResources);
+ return alternateView;
+ }
+
+ public static string Encode(string text)
+ {
+ return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).Replace('+', '-').Replace('/', '\u005F').Replace("=", "");
+ }
+
+ public List<LogEnvio> Send(Credencial credencial, List<Destinatario> destinatarios, TipoTela tela, long id)
+ {
+ List<LogEnvio> logEnvios1 = new List<LogEnvio>();
+ int num = 100;
+ destinatarios.ForEach(async (Destinatario i) => {
+ if (num == 0)
+ {
+ num = 100;
+ await Task.Delay(1000);
+ }
+ List<LogEnvio> logEnvios = logEnvios1;
+ logEnvios.Add(await this.SendAsync(credencial, i, null, null, 0, false));
+ logEnvios = null;
+ num--;
+ });
+ return logEnvios1;
+ }
+
+ public async Task<LogEnvio> SendAsync(Credencial credencial, Destinatario destinatario, FiltroArquivoDigital filtro = null, List<MalaDireta> maladireta = null, TipoTela tela = 0, bool confirmarLeitura = false)
+ {
+ TipoTela tipoTela = new TipoTela();
+ IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
+ LogEnvio logEnvio2 = await Task.Run<LogEnvio>(() => {
+ AuthenticationResult result;
+ List<string> strs;
+ string str;
+ long id;
+ string str1;
+ string str2;
+ string str3;
+ string str4;
+ string str5;
+ string str6;
+ Action<string> action2 = null;
+ Action<string> action3 = null;
+ LogEnvio logEnvio = new LogEnvio();
+ logEnvio.set_Credencial(credencial);
+ logEnvio.set_Destinatario(destinatario);
+ LogEnvio logEnvio1 = logEnvio;
+ AlternateView alternateView = MailHelper.CreateAlternateView(destinatario.get_Corpo());
+ try
+ {
+ MailMessage mailMessage = new MailMessage()
+ {
+ From = new MailAddress(credencial.get_Email(), (string.IsNullOrWhiteSpace(credencial.get_Header()) ? Recursos.Empresa.get_Nome() : credencial.get_Header())),
+ BodyEncoding = Encoding.UTF8,
+ Subject = destinatario.get_Assunto()
+ };
+ mailMessage.AlternateViews.Add(alternateView);
+ mailMessage.ReplyToList.Add(new MailAddress((string.IsNullOrWhiteSpace(credencial.get_Replyto()) ? credencial.get_Email() : credencial.get_Replyto())));
+ mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
+ mailMessage.IsBodyHtml = true;
+ MailMessage mailMessage1 = mailMessage;
+ if (confirmarLeitura)
+ {
+ mailMessage1.Headers.Add("Disposition-Notification-To", credencial.get_Email());
+ }
+ destinatario.get_Email().Split(new char[] { ';' }).ToList<string>().ForEach((string s) => {
+ if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s))
+ {
+ return;
+ }
+ mailMessage1.To.Add(new MailAddress(s));
+ });
+ List<string> strs1 = new List<string>();
+ List<string> encaminharOculto = destinatario.get_EncaminharOculto();
+ if (encaminharOculto != null)
+ {
+ encaminharOculto.ForEach((string x) => {
+ if (string.IsNullOrEmpty(x))
+ {
+ return;
+ }
+ if (!x.Contains(";"))
+ {
+ if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(x))
+ {
+ return;
+ }
+ strs1.Add(x);
+ return;
+ }
+ List<string> list = x.Split(new char[] { ';' }).ToList<string>();
+ Action<string> u003cu003e9_6 = action2;
+ if (u003cu003e9_6 == null)
+ {
+ Action<string> action = (string s) => {
+ if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s))
+ {
+ return;
+ }
+ strs1.Add(s);
+ };
+ Action<string> action1 = action;
+ action2 = action;
+ u003cu003e9_6 = action1;
+ }
+ list.ForEach(u003cu003e9_6);
+ });
+ }
+ else
+ {
+ }
+ List<string> encaminhar = destinatario.get_Encaminhar();
+ if (encaminhar != null)
+ {
+ encaminhar.ForEach((string x) => {
+ if (string.IsNullOrEmpty(x))
+ {
+ return;
+ }
+ if (!x.Contains(";"))
+ {
+ if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(x))
+ {
+ return;
+ }
+ strs1.Add(x);
+ return;
+ }
+ List<string> list = x.Split(new char[] { ';' }).ToList<string>();
+ Action<string> u003cu003e9_7 = action3;
+ if (u003cu003e9_7 == null)
+ {
+ Action<string> action = (string s) => {
+ if (!Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(s))
+ {
+ return;
+ }
+ strs1.Add(s);
+ };
+ Action<string> action1 = action;
+ action3 = action;
+ u003cu003e9_7 = action1;
+ }
+ list.ForEach(u003cu003e9_7);
+ });
+ }
+ else
+ {
+ }
+ strs1.ForEach((string x) => mailMessage1.Bcc.Add(new MailAddress(x)));
+ List<Gestor.Model.Domain.Common.ArquivoDigital> anexos = destinatario.get_Anexos();
+ if (anexos != null)
+ {
+ anexos.ForEach((Gestor.Model.Domain.Common.ArquivoDigital x) => {
+ Attachment attachment = new Attachment(new MemoryStream(x.get_Arquivo()), string.Concat(x.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(x.get_Extensao())));
+ mailMessage1.Attachments.Add(attachment);
+ });
+ }
+ else
+ {
+ }
+ if (credencial.get_Email().Contains("@gmail.com"))
+ {
+ credencial.set_Tipo(1);
+ }
+ TipoEmail tipo = credencial.get_Tipo();
+ if (tipo == 1)
+ {
+ ClientSecrets clientSecret = new ClientSecrets();
+ clientSecret.set_ClientId("378618252089-fm92uqgnk2jivf25mk2tv9s735n4nf6u.apps.googleusercontent.com");
+ clientSecret.set_ClientSecret("kUiTfSuwZLLfteqwX7x6glsu");
+ UserCredential userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecret, new string[] { GmailService.Scope.GmailSend }, credencial.get_Email(), CancellationToken.None, null, null).Result;
+ Google.Apis.Gmail.v1.Data.Message message = new Google.Apis.Gmail.v1.Data.Message();
+ message.set_Raw(MailHelper.Encode(MimeMessage.CreateFromMailMessage(mailMessage1).ToString()));
+ Google.Apis.Gmail.v1.Data.Message message1 = message;
+ BaseClientService.Initializer initializer = new BaseClientService.Initializer();
+ initializer.set_HttpClientInitializer(userCredential);
+ initializer.set_ApplicationName("AGGER GESTOR");
+ UsersResource.MessagesResource.SendRequest sendRequest = (new GmailService(initializer)).get_Users().get_Messages().Send(message1, credencial.get_Email());
+ logEnvio1.set_Enviado(false);
+ if (sendRequest.Execute().get_LabelIds().Contains("SENT"))
+ {
+ logEnvio1.set_Enviado(true);
+ }
+ }
+ else if (tipo == 2)
+ {
+ StringContent stringContent = new StringContent("");
+ PublicClientApplicationBuilder publicClientApplicationBuilder = PublicClientApplicationBuilder.Create("8d1c32fe-4c17-4d5b-a21b-55b5529c3e12").WithDefaultRedirectUri();
+ CacheOptions cacheOption = new CacheOptions();
+ cacheOption.set_UseSharedCache(true);
+ IPublicClientApplication publicClientApplication = publicClientApplicationBuilder.WithCacheOptions(cacheOption).Build();
+ string[] strArrays = new string[] { "user.read", "https://graph.microsoft.com/Mail.Send" };
+ try
+ {
+ stringContent = MailHelper.ConverteMailMessageParaStringContent(mailMessage1);
+ IEnumerable<IAccount> accounts = publicClientApplication.GetAccountsAsync().Result;
+ result = (accounts == null || accounts.Count<IAccount>() == 0 ? publicClientApplication.AcquireTokenInteractive(strArrays).ExecuteAsync().Result : publicClientApplication.AcquireTokenSilent(strArrays, (accounts != null ? accounts.FirstOrDefault<IAccount>() : null)).ExecuteAsync().Result);
+ }
+ catch
+ {
+ result = publicClientApplication.AcquireTokenInteractive(strArrays).ExecuteAsync().Result;
+ }
+ using (HttpClient httpClient = new HttpClient())
+ {
+ httpClient.get_DefaultRequestHeaders().Clear();
+ httpClient.get_DefaultRequestHeaders().Add("Authorization", string.Concat("Bearer ", (result != null ? result.get_AccessToken() : null)));
+ logEnvio1.set_Enviado(httpClient.PostAsync("https://graph.microsoft.com/v1.0/me/sendMail", stringContent).Result.get_IsSuccessStatusCode());
+ }
+ }
+ else
+ {
+ NetworkCredential networkCredential = new NetworkCredential()
+ {
+ Password = EncryptionHelper.Decrypt(credencial.get_Senha()),
+ UserName = credencial.get_Usuario() ?? credencial.get_Email()
+ };
+ SmtpClient smtpClient = new SmtpClient()
+ {
+ EnableSsl = credencial.get_Seguro(),
+ Host = credencial.get_Dominio(),
+ Port = credencial.get_Porta().GetValueOrDefault(587),
+ UseDefaultCredentials = false,
+ Credentials = networkCredential
+ };
+ smtpClient.SendCompleted += new SendCompletedEventHandler((object sender, AsyncCompletedEventArgs args) => {
+ logEnvio1.set_Enviado((!args.Cancelled ? true : args.Error != null));
+ if (args.Error != null)
+ {
+ logEnvio1.set_Erro(args.Error.ToString());
+ }
+ });
+ smtpClient.Send(mailMessage1);
+ logEnvio1.set_Enviado(true);
+ }
+ }
+ catch (Exception exception1)
+ {
+ Exception exception = exception1;
+ logEnvio1.set_Enviado(false);
+ logEnvio1.set_Erro((exception.InnerException == null ? exception.Message : string.Concat(exception.Message, " | ", exception.InnerException.Message)));
+ }
+ if (tela == 40)
+ {
+ return logEnvio1;
+ }
+ using (UnitOfWork commited = Instancia.Commited)
+ {
+ List<string> strs2 = new List<string>()
+ {
+ destinatario.get_Email()
+ };
+ if (destinatario.get_Encaminhar() != null)
+ {
+ strs2.AddRange(destinatario.get_Encaminhar());
+ }
+ List<string> strs3 = new List<string>();
+ if (destinatario.get_EncaminharOculto() != null)
+ {
+ strs3.AddRange(destinatario.get_EncaminharOculto());
+ }
+ List<Gestor.Model.Domain.Common.ArquivoDigital> arquivoDigitals = destinatario.get_Anexos();
+ if (arquivoDigitals != null)
+ {
+ Func<Gestor.Model.Domain.Common.ArquivoDigital, string> u003cu003e9_09 = MailHelper.u003cu003ec.u003cu003e9__0_9;
+ if (u003cu003e9_09 == null)
+ {
+ u003cu003e9_09 = (Gestor.Model.Domain.Common.ArquivoDigital x) => string.Concat(x.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(x.get_Extensao()));
+ MailHelper.u003cu003ec.u003cu003e9__0_9 = u003cu003e9_09;
+ }
+ strs = arquivoDigitals.Select<Gestor.Model.Domain.Common.ArquivoDigital, string>(u003cu003e9_09).ToList<string>();
+ }
+ else
+ {
+ strs = null;
+ }
+ List<string> strs4 = strs;
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ if (filtro != null)
+ {
+ switch (filtro.get_Tipo())
+ {
+ case 1:
+ {
+ tipoTela = 1;
+ break;
+ }
+ case 2:
+ {
+ tipoTela = 2;
+ break;
+ }
+ case 3:
+ {
+ tipoTela = 5;
+ break;
+ }
+ case 4:
+ {
+ tipoTela = 3;
+ break;
+ }
+ case 5:
+ {
+ tipoTela = 7;
+ break;
+ }
+ case 6:
+ {
+ tipoTela = 15;
+ break;
+ }
+ case 7:
+ {
+ tipoTela = 23;
+ break;
+ }
+ case 8:
+ {
+ tipoTela = 13;
+ break;
+ }
+ case 9:
+ {
+ tipoTela = 25;
+ break;
+ }
+ case 10:
+ {
+ tipoTela = 24;
+ break;
+ }
+ case 11:
+ {
+ tipoTela = 33;
+ break;
+ }
+ case 12:
+ {
+ tipoTela = 16;
+ break;
+ }
+ case 13:
+ {
+ tipoTela = 18;
+ break;
+ }
+ default:
+ {
+ tipoTela = 0;
+ break;
+ }
+ }
+ if (strs4 != null && logEnvio1.get_Enviado())
+ {
+ LogEmail logEmail = new LogEmail();
+ logEmail.set_Credencial(credencial);
+ logEmail.set_EntityId(filtro.get_Id());
+ logEmail.set_Usuario(Recursos.Usuario);
+ logEmail.set_Data(networkTime);
+ logEmail.set_Tela(tipoTela);
+ logEmail.set_Destinatarios(string.Join(";", strs2));
+ logEmail.set_Cco(string.Join(";", strs3));
+ logEmail.set_Assunto(destinatario.get_Assunto());
+ logEmail.set_Corpo(destinatario.get_Corpo());
+ logEmail.set_Anexos(string.Join(";", strs4));
+ logEmail.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail.set_NomeMaquina(Environment.MachineName);
+ logEmail.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] addressList = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_010 = MailHelper.u003cu003ec.u003cu003e9__0_10;
+ if (u003cu003e9_010 == null)
+ {
+ u003cu003e9_010 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_10 = u003cu003e9_010;
+ }
+ IPAddress pAddress = ((IEnumerable<IPAddress>)addressList).FirstOrDefault<IPAddress>(u003cu003e9_010);
+ if (pAddress != null)
+ {
+ str6 = pAddress.ToString();
+ }
+ else
+ {
+ str6 = null;
+ }
+ logEmail.set_Ip(str6);
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail);
+ }
+ commited.Commit();
+ }
+ else if (maladireta == null)
+ {
+ if (strs4 != null)
+ {
+ LogEmail logEmail1 = new LogEmail();
+ logEmail1.set_Credencial(credencial);
+ logEmail1.set_Usuario(Recursos.Usuario);
+ logEmail1.set_Data(networkTime);
+ logEmail1.set_Tela(tela);
+ logEmail1.set_Destinatarios(string.Join(";", strs2));
+ logEmail1.set_Cco(string.Join(";", strs3));
+ logEmail1.set_Assunto(destinatario.get_Assunto());
+ logEmail1.set_Corpo(destinatario.get_Corpo());
+ logEmail1.set_Anexos(string.Join(";", strs4));
+ logEmail1.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail1.set_NomeMaquina(Environment.MachineName);
+ logEmail1.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] pAddressArray = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_016 = MailHelper.u003cu003ec.u003cu003e9__0_16;
+ if (u003cu003e9_016 == null)
+ {
+ u003cu003e9_016 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_16 = u003cu003e9_016;
+ }
+ IPAddress pAddress1 = ((IEnumerable<IPAddress>)pAddressArray).FirstOrDefault<IPAddress>(u003cu003e9_016);
+ if (pAddress1 != null)
+ {
+ str = pAddress1.ToString();
+ }
+ else
+ {
+ str = null;
+ }
+ logEmail1.set_Ip(str);
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail1);
+ }
+ commited.Commit();
+ }
+ else
+ {
+ foreach (MalaDireta maladiretum in maladireta)
+ {
+ if (maladiretum.get_Tela() == 1)
+ {
+ LogEmail logEmail2 = new LogEmail();
+ logEmail2.set_Credencial(credencial);
+ logEmail2.set_Usuario(Recursos.Usuario);
+ logEmail2.set_EntityId(maladiretum.get_Cliente().get_Id());
+ logEmail2.set_Data(networkTime);
+ logEmail2.set_Tela(maladiretum.get_Tela());
+ logEmail2.set_Destinatarios(string.Join(";", strs2));
+ logEmail2.set_Cco(string.Join(";", strs3));
+ logEmail2.set_Assunto(destinatario.get_Assunto());
+ logEmail2.set_Corpo(destinatario.get_Corpo());
+ logEmail2.set_Anexos(string.Join(";", strs4));
+ logEmail2.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail2.set_NomeMaquina(Environment.MachineName);
+ logEmail2.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] addressList1 = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_011 = MailHelper.u003cu003ec.u003cu003e9__0_11;
+ if (u003cu003e9_011 == null)
+ {
+ u003cu003e9_011 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_11 = u003cu003e9_011;
+ }
+ IPAddress pAddress2 = ((IEnumerable<IPAddress>)addressList1).FirstOrDefault<IPAddress>(u003cu003e9_011);
+ if (pAddress2 != null)
+ {
+ str5 = pAddress2.ToString();
+ }
+ else
+ {
+ str5 = null;
+ }
+ logEmail2.set_Ip(str5);
+ logEmail2.set_Relatorio(maladiretum.get_Relatorio());
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail2);
+ }
+ else if (maladiretum.get_Tela() == 2)
+ {
+ LogEmail logEmail3 = new LogEmail();
+ logEmail3.set_Credencial(credencial);
+ logEmail3.set_Usuario(Recursos.Usuario);
+ logEmail3.set_EntityId(maladiretum.get_Apolice().get_Id());
+ logEmail3.set_Data(networkTime);
+ logEmail3.set_Tela(maladiretum.get_Tela());
+ logEmail3.set_Destinatarios(string.Join(";", strs2));
+ logEmail3.set_Cco(string.Join(";", strs3));
+ logEmail3.set_Assunto(destinatario.get_Assunto());
+ logEmail3.set_Corpo(destinatario.get_Corpo());
+ logEmail3.set_Anexos(string.Join(";", strs4));
+ logEmail3.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail3.set_NomeMaquina(Environment.MachineName);
+ logEmail3.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] pAddressArray1 = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_012 = MailHelper.u003cu003ec.u003cu003e9__0_12;
+ if (u003cu003e9_012 == null)
+ {
+ u003cu003e9_012 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_12 = u003cu003e9_012;
+ }
+ IPAddress pAddress3 = ((IEnumerable<IPAddress>)pAddressArray1).FirstOrDefault<IPAddress>(u003cu003e9_012);
+ if (pAddress3 != null)
+ {
+ str4 = pAddress3.ToString();
+ }
+ else
+ {
+ str4 = null;
+ }
+ logEmail3.set_Ip(str4);
+ logEmail3.set_Relatorio(maladiretum.get_Relatorio());
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail3);
+ }
+ else if (maladiretum.get_Tela() == 5)
+ {
+ LogEmail logEmail4 = new LogEmail();
+ logEmail4.set_Credencial(credencial);
+ logEmail4.set_Usuario(Recursos.Usuario);
+ logEmail4.set_EntityId(maladiretum.get_Parcela().get_Id());
+ logEmail4.set_Data(networkTime);
+ logEmail4.set_Tela(maladiretum.get_Tela());
+ logEmail4.set_Destinatarios(string.Join(";", strs2));
+ logEmail4.set_Cco(string.Join(";", strs3));
+ logEmail4.set_Assunto(destinatario.get_Assunto());
+ logEmail4.set_Corpo(destinatario.get_Corpo());
+ logEmail4.set_Anexos(string.Join(";", strs4));
+ logEmail4.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail4.set_NomeMaquina(Environment.MachineName);
+ logEmail4.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] addressList2 = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_013 = MailHelper.u003cu003ec.u003cu003e9__0_13;
+ if (u003cu003e9_013 == null)
+ {
+ u003cu003e9_013 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_13 = u003cu003e9_013;
+ }
+ IPAddress pAddress4 = ((IEnumerable<IPAddress>)addressList2).FirstOrDefault<IPAddress>(u003cu003e9_013);
+ if (pAddress4 != null)
+ {
+ str3 = pAddress4.ToString();
+ }
+ else
+ {
+ str3 = null;
+ }
+ logEmail4.set_Ip(str3);
+ logEmail4.set_Relatorio(maladiretum.get_Relatorio());
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail4);
+ }
+ else if (maladiretum.get_Tela() != 7)
+ {
+ if (maladiretum.get_Tela() != null)
+ {
+ continue;
+ }
+ LogEmail logEmail5 = new LogEmail();
+ logEmail5.set_Credencial(credencial);
+ logEmail5.set_Usuario(Recursos.Usuario);
+ Documento apolice = maladiretum.get_Apolice();
+ id = (apolice != null ? apolice.get_Id() : (long)0);
+ logEmail5.set_EntityId(id);
+ logEmail5.set_Data(networkTime);
+ logEmail5.set_Tela(2);
+ logEmail5.set_Destinatarios(string.Join(";", strs2));
+ logEmail5.set_Cco(string.Join(";", strs3));
+ logEmail5.set_Assunto(destinatario.get_Assunto());
+ logEmail5.set_Corpo(destinatario.get_Corpo());
+ logEmail5.set_Anexos(string.Join(";", strs4));
+ logEmail5.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail5.set_NomeMaquina(Environment.MachineName);
+ logEmail5.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] pAddressArray2 = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_015 = MailHelper.u003cu003ec.u003cu003e9__0_15;
+ if (u003cu003e9_015 == null)
+ {
+ u003cu003e9_015 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_15 = u003cu003e9_015;
+ }
+ IPAddress pAddress5 = ((IEnumerable<IPAddress>)pAddressArray2).FirstOrDefault<IPAddress>(u003cu003e9_015);
+ if (pAddress5 != null)
+ {
+ str1 = pAddress5.ToString();
+ }
+ else
+ {
+ str1 = null;
+ }
+ logEmail5.set_Ip(str1);
+ logEmail5.set_Relatorio(maladiretum.get_Relatorio());
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail5);
+ }
+ else
+ {
+ LogEmail logEmail6 = new LogEmail();
+ logEmail6.set_Credencial(credencial);
+ logEmail6.set_Usuario(Recursos.Usuario);
+ logEmail6.set_EntityId(maladiretum.get_Sinistro().get_Id());
+ logEmail6.set_Data(networkTime);
+ logEmail6.set_Tela(maladiretum.get_Tela());
+ logEmail6.set_Destinatarios(string.Join(";", strs2));
+ logEmail6.set_Cco(string.Join(";", strs3));
+ logEmail6.set_Assunto(destinatario.get_Assunto());
+ logEmail6.set_Corpo(destinatario.get_Corpo());
+ logEmail6.set_Anexos(string.Join(";", strs4));
+ logEmail6.set_Versao(LoginViewModel.VersaoAtual);
+ logEmail6.set_NomeMaquina(Environment.MachineName);
+ logEmail6.set_UsuarioMaquina(Environment.UserName);
+ IPAddress[] addressList3 = hostEntry.AddressList;
+ Func<IPAddress, bool> u003cu003e9_014 = MailHelper.u003cu003ec.u003cu003e9__0_14;
+ if (u003cu003e9_014 == null)
+ {
+ u003cu003e9_014 = (IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork;
+ MailHelper.u003cu003ec.u003cu003e9__0_14 = u003cu003e9_014;
+ }
+ IPAddress pAddress6 = ((IEnumerable<IPAddress>)addressList3).FirstOrDefault<IPAddress>(u003cu003e9_014);
+ if (pAddress6 != null)
+ {
+ str2 = pAddress6.ToString();
+ }
+ else
+ {
+ str2 = null;
+ }
+ logEmail6.set_Ip(str2);
+ logEmail6.set_Relatorio(maladiretum.get_Relatorio());
+ commited.get_RegistroLogRepository().SaveOrUpdate(logEmail6);
+ }
+ }
+ commited.Commit();
+ }
+ }
+ return logEnvio1;
+ });
+ return logEnvio2;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs b/Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs new file mode 100644 index 0000000..955e38b --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/NotifyPropertyChangedExtension.cs @@ -0,0 +1,23 @@ +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))
+ {
+ return;
+ }
+ field = newValue;
+ if (raise != null)
+ {
+ raise(new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs b/Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs new file mode 100644 index 0000000..ff5dc58 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ObrigatorioValidationRule.cs @@ -0,0 +1,34 @@ +using System;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Windows.Controls;
+
+namespace Gestor.Application.Helpers
+{
+ public class ObrigatorioValidationRule : ValidationRule
+ {
+ public bool IsRequired
+ {
+ get;
+ set;
+ }
+
+ public ObrigatorioValidationRule()
+ {
+ }
+
+ public override ValidationResult Validate(object value, CultureInfo cultureInfo)
+ {
+ string str = value as string;
+ if (str == null)
+ {
+ return new ValidationResult(false, "OBRIGATÓRIO");
+ }
+ if (str == null || !this.IsRequired || !string.IsNullOrWhiteSpace(str))
+ {
+ return ValidationResult.ValidResult;
+ }
+ return new ValidationResult(false, "OBRIGATÓRIO");
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs b/Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs new file mode 100644 index 0000000..8944bc7 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/PasswordBoxAssistant.cs @@ -0,0 +1,95 @@ +using System;
+using System.Windows;
+using System.Windows.Controls;
+
+namespace Gestor.Application.Helpers
+{
+ public static class PasswordBoxAssistant
+ {
+ public readonly static DependencyProperty BoundPassword;
+
+ public readonly static DependencyProperty BindPassword;
+
+ private readonly static DependencyProperty UpdatingPassword;
+
+ static PasswordBoxAssistant()
+ {
+ PasswordBoxAssistant.BoundPassword = DependencyProperty.RegisterAttached("BoundPassword", typeof(string), typeof(PasswordBoxAssistant), new PropertyMetadata(string.Empty, new PropertyChangedCallback(PasswordBoxAssistant.OnBoundPasswordChanged)));
+ PasswordBoxAssistant.BindPassword = DependencyProperty.RegisterAttached("BindPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false, new PropertyChangedCallback(PasswordBoxAssistant.OnBindPasswordChanged)));
+ PasswordBoxAssistant.UpdatingPassword = DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordBoxAssistant), new PropertyMetadata(false));
+ }
+
+ public static bool GetBindPassword(DependencyObject dp)
+ {
+ return (bool)dp.GetValue(PasswordBoxAssistant.BindPassword);
+ }
+
+ public static string GetBoundPassword(DependencyObject dp)
+ {
+ return (string)dp.GetValue(PasswordBoxAssistant.BoundPassword);
+ }
+
+ private static bool GetUpdatingPassword(DependencyObject dp)
+ {
+ return (bool)dp.GetValue(PasswordBoxAssistant.UpdatingPassword);
+ }
+
+ private static void HandlePasswordChanged(object sender, RoutedEventArgs e)
+ {
+ PasswordBox passwordBox = sender as PasswordBox;
+ PasswordBoxAssistant.SetUpdatingPassword(passwordBox, true);
+ PasswordBoxAssistant.SetBoundPassword(passwordBox, passwordBox.Password);
+ PasswordBoxAssistant.SetUpdatingPassword(passwordBox, false);
+ }
+
+ private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+ {
+ PasswordBox passwordBox = dp as PasswordBox;
+ if (passwordBox == null)
+ {
+ return;
+ }
+ bool oldValue = (bool)e.OldValue;
+ bool newValue = (bool)e.NewValue;
+ if (oldValue)
+ {
+ passwordBox.PasswordChanged -= new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged);
+ }
+ if (newValue)
+ {
+ passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged);
+ }
+ }
+
+ private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ PasswordBox passwordBox = d as PasswordBox;
+ if (d == null || !PasswordBoxAssistant.GetBindPassword(d))
+ {
+ return;
+ }
+ passwordBox.PasswordChanged -= new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged);
+ string newValue = (string)e.NewValue;
+ if (!PasswordBoxAssistant.GetUpdatingPassword(passwordBox))
+ {
+ passwordBox.Password = newValue;
+ }
+ passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBoxAssistant.HandlePasswordChanged);
+ }
+
+ public static void SetBindPassword(DependencyObject dp, bool value)
+ {
+ dp.SetValue(PasswordBoxAssistant.BindPassword, value);
+ }
+
+ public static void SetBoundPassword(DependencyObject dp, string value)
+ {
+ dp.SetValue(PasswordBoxAssistant.BoundPassword, value);
+ }
+
+ private static void SetUpdatingPassword(DependencyObject dp, bool value)
+ {
+ dp.SetValue(PasswordBoxAssistant.UpdatingPassword, value);
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/PipeClient.cs b/Codemerx/Gestor.Application/Helpers/PipeClient.cs new file mode 100644 index 0000000..5e8d841 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/PipeClient.cs @@ -0,0 +1,52 @@ +using System;
+using System.IO;
+using System.IO.Pipes;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+ public class PipeClient
+ {
+ private string _pipeName;
+
+ private NamedPipeClientStream Pipe
+ {
+ get;
+ set;
+ }
+
+ public PipeClient(string pipeName)
+ {
+ this._pipeName = pipeName;
+ }
+
+ public bool Send(dynamic message)
+ {
+ bool flag;
+ try
+ {
+ this.Pipe = new NamedPipeClientStream(".", this._pipeName, PipeDirection.Out, PipeOptions.Asynchronous);
+ this.Pipe.Connect(1000);
+ if (this.Pipe.IsConnected)
+ {
+ using (StreamWriter streamWriter = new StreamWriter(this.Pipe))
+ {
+ streamWriter.AutoFlush = true;
+ streamWriter.WriteLine(JsonConvert.SerializeObject(message));
+ this.Pipe.WaitForPipeDrain();
+ }
+ return true;
+ }
+ else
+ {
+ flag = false;
+ }
+ }
+ catch (TimeoutException timeoutException)
+ {
+ flag = false;
+ }
+ return flag;
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/PipeServer.cs b/Codemerx/Gestor.Application/Helpers/PipeServer.cs new file mode 100644 index 0000000..fa42e03 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/PipeServer.cs @@ -0,0 +1,115 @@ +using Assinador.Model.Common;
+using Gestor.Application.Actions;
+using Newtonsoft.Json;
+using System;
+using System.IO;
+using System.IO.Pipes;
+using System.Runtime.CompilerServices;
+using System.Security.AccessControl;
+using System.Security.Principal;
+
+namespace Gestor.Application.Helpers
+{
+ public class PipeServer : IDisposable
+ {
+ private string _pipeName;
+
+ private NamedPipeServerStream Pipe
+ {
+ get;
+ set;
+ }
+
+ public PipeServer()
+ {
+ }
+
+ private bool Create()
+ {
+ bool flag;
+ bool flag1 = true;
+ try
+ {
+ (new NamedPipeClientStream(".", this._pipeName, PipeDirection.Out, PipeOptions.Asynchronous)).Connect(1000);
+ }
+ catch (TimeoutException timeoutException)
+ {
+ flag1 = false;
+ }
+ catch (Exception exception)
+ {
+ flag = false;
+ return flag;
+ }
+ if (flag1)
+ {
+ return true;
+ }
+ try
+ {
+ PipeSecurity pipeSecurity = new PipeSecurity();
+ SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
+ securityIdentifier.Translate(typeof(NTAccount));
+ pipeSecurity.SetAccessRule(new PipeAccessRule(securityIdentifier, PipeAccessRights.ReadWrite, AccessControlType.Allow));
+ this.Pipe = new NamedPipeServerStream(this._pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, pipeSecurity);
+ this.Pipe.BeginWaitForConnection(new AsyncCallback(this.WaitForConnectionCallBack), this.Pipe);
+ return true;
+ }
+ catch (Exception exception1)
+ {
+ flag = false;
+ }
+ return flag;
+ }
+
+ public bool CreateServer(string name)
+ {
+ this._pipeName = name;
+ return this.Create();
+ }
+
+ public void Dispose()
+ {
+ this.Pipe.Dispose();
+ }
+
+ private void Handle(string message)
+ {
+ if (message == null)
+ {
+ return;
+ }
+ PipeMessageResult pipeMessageResult = JsonConvert.DeserializeObject<PipeMessageResult>(message);
+ Action<PipeMessageResult> acessarHoster = Gestor.Application.Actions.Actions.AcessarHoster;
+ if (acessarHoster == null)
+ {
+ return;
+ }
+ acessarHoster(pipeMessageResult);
+ }
+
+ private void WaitForConnectionCallBack(IAsyncResult iar)
+ {
+ try
+ {
+ NamedPipeServerStream asyncState = (NamedPipeServerStream)iar.AsyncState;
+ asyncState.EndWaitForConnection(iar);
+ using (StreamReader streamReader = new StreamReader(this.Pipe))
+ {
+ string str = streamReader.ReadLine();
+ if ((str == null ? false : str.IndexOf("exit", StringComparison.InvariantCultureIgnoreCase) > -1))
+ {
+ this.Dispose();
+ }
+ this.Handle(str);
+ }
+ asyncState.Close();
+ asyncState = null;
+ this.Create();
+ }
+ catch
+ {
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/QueryableHelper.cs b/Codemerx/Gestor.Application/Helpers/QueryableHelper.cs new file mode 100644 index 0000000..5670bf2 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/QueryableHelper.cs @@ -0,0 +1,26 @@ +using System;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+ public static class QueryableHelper
+ {
+ public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
+ {
+ return source.OrderBy<T, object>(QueryableHelper.ToLambda<T>(propertyName));
+ }
+
+ public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
+ {
+ return source.OrderByDescending<T, object>(QueryableHelper.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[] { parameterExpression });
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/Recursos.cs b/Codemerx/Gestor.Application/Helpers/Recursos.cs new file mode 100644 index 0000000..8800d53 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/Recursos.cs @@ -0,0 +1,170 @@ +using Agger.Registro;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Configuracoes;
+using Gestor.Model.Domain.Ferramentas;
+using Gestor.Model.Domain.Financeiro;
+using Gestor.Model.Domain.Seguros;
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Runtime.CompilerServices;
+
+namespace Gestor.Application.Helpers
+{
+ public static class Recursos
+ {
+ public const string AppStore = "https://apps.apple.com/br/app/agger-mobile/id1463091598";
+
+ public const string PlayStore = "https://play.google.com/store/apps/details?id=br.com.aggermobile&hl=pt&gl=US";
+
+ public const int DefaultMaxSize = 14336;
+
+ public static Uri ApiArquivo
+ {
+ get;
+ }
+
+ public static List<Gestor.Model.Domain.Financeiro.BancosContas> BancosContas
+ {
+ get;
+ set;
+ }
+
+ public static List<CoberturaPadrao> Coberturas
+ {
+ get;
+ set;
+ }
+
+ public static List<ConfiguracaoSistema> Configuracoes
+ {
+ get;
+ set;
+ }
+
+ public static List<ConfigExtratoImport> Descricao
+ {
+ get;
+ set;
+ }
+
+ public static Gestor.Model.Domain.Common.Empresa Empresa
+ {
+ get;
+ set;
+ }
+
+ public static List<Gestor.Model.Domain.Common.Empresa> Empresas
+ {
+ get;
+ set;
+ }
+
+ public static List<Estipulante> Estipulantes
+ {
+ get;
+ set;
+ }
+
+ public static List<Fabricante> Fabricantes
+ {
+ get;
+ set;
+ }
+
+ public static IPHostEntry Host
+ {
+ get;
+ set;
+ }
+
+ public static List<string> Parametros
+ {
+ get;
+ set;
+ }
+
+ public static List<Parceiro> Parceiros
+ {
+ get;
+ set;
+ }
+
+ public static List<Produto> Produtos
+ {
+ get;
+ set;
+ }
+
+ public static List<Ramo> Ramos
+ {
+ get;
+ set;
+ }
+
+ public static string Registrar
+ {
+ get;
+ set;
+ }
+
+ public static List<Seguradora> Seguradoras
+ {
+ get;
+ set;
+ }
+
+ public static List<Gestor.Model.Domain.Seguros.Status> Status
+ {
+ get;
+ set;
+ }
+
+ public static List<StatusDeProspeccao> StatusProspeccao
+ {
+ get;
+ set;
+ }
+
+ public static List<TipoDeTarefa> TiposTarefa
+ {
+ get;
+ set;
+ }
+
+ public static List<Gestor.Model.Domain.Seguros.TipoVendedor> TipoVendedor
+ {
+ get;
+ set;
+ }
+
+ public static Gestor.Model.Domain.Seguros.Usuario Usuario
+ {
+ get;
+ set;
+ }
+
+ public static List<Gestor.Model.Domain.Seguros.Usuario> Usuarios
+ {
+ get;
+ set;
+ }
+
+ public static List<Vendedor> Vendedores
+ {
+ get;
+ set;
+ }
+
+ public static Uri WhatsAppLink
+ {
+ get;
+ }
+
+ static Recursos()
+ {
+ Recursos.WhatsAppLink = new Uri("https://api.whatsapp.com/send?");
+ Recursos.ApiArquivo = Address.get_ApiArquivo();
+ }
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/TipoToggle.cs b/Codemerx/Gestor.Application/Helpers/TipoToggle.cs new file mode 100644 index 0000000..294a15d --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/TipoToggle.cs @@ -0,0 +1,14 @@ +using System;
+
+namespace Gestor.Application.Helpers
+{
+ [Flags]
+ public enum TipoToggle
+ {
+ None = 0,
+ Consultar = 1,
+ Incluir = 2,
+ Alterar = 4,
+ Excluir = 8
+ }
+}
\ No newline at end of file diff --git a/Codemerx/Gestor.Application/Helpers/ViewHelper.cs b/Codemerx/Gestor.Application/Helpers/ViewHelper.cs new file mode 100644 index 0000000..9c17374 --- /dev/null +++ b/Codemerx/Gestor.Application/Helpers/ViewHelper.cs @@ -0,0 +1,462 @@ +using CurrencyTextBoxControl;
+using Gestor.Application.Componentes;
+using Gestor.Model.Helper;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Dynamic;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Media;
+using Xceed.Wpf.Toolkit;
+using Xceed.Wpf.Toolkit.Primitives;
+
+namespace Gestor.Application.Helpers
+{
+ public static class ViewHelper
+ {
+ internal static void BindData<T>(this CheckComboBox comboBox, bool withSelect = true, bool enumDefault = true, string defaultValue = "", bool orderByLabel = false)
+ {
+ ViewHelper.DefaultBinding<T>(comboBox, withSelect, enumDefault, defaultValue, string.Empty, orderByLabel);
+ }
+
+ public static void ClearInvalid(this DependencyObject dependencyObject)
+ {
+ foreach (Control control in ViewHelper.FindChildren<Control>(dependencyObject))
+ {
+ control.SetInvalid(null, null);
+ }
+ }
+
+ private static bool Compare(Control currentControl)
+ {
+ object resolvedSource;
+ DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(currentControl);
+ if (dependencyProperty == null)
+ {
+ return false;
+ }
+ BindingExpression bindingExpression = currentControl.GetBindingExpression(dependencyProperty);
+ if (bindingExpression != null)
+ {
+ resolvedSource = bindingExpression.ResolvedSource;
+ }
+ else
+ {
+ resolvedSource = null;
+ }
+ dynamic obj = resolvedSource;
+ dynamic obj1 = obj != (dynamic)null;
+ return (bool)((!obj1 ? obj1 : obj1 & (bool)obj.HasChange()));
+ }
+
+ public static void ControlLostFocus(object sender, RoutedEventArgs e)
+ {
+ dynamic obj;
+ Control control;
+ Control control1 = null;
+ if (sender is CustomItemValidation)
+ {
+ control1 = ViewHelper.FindChildren<Control>(sender as CustomItemValidation).FirstOrDefault<Control>((Control currentControl) => {
+ if (currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox || currentControl is Button)
+ {
+ return true;
+ }
+ return currentControl is CustomPasswordBox;
+ });
+ }
+ if (sender is CustomIsReadOnlyControl)
+ {
+ CustomIsReadOnlyControl customIsReadOnlyControl = sender as CustomIsReadOnlyControl;
+ if (!customIsReadOnlyControl.HasValidation)
+ {
+ control = null;
+ }
+ else
+ {
+ control = ViewHelper.FindChildren<Control>(customIsReadOnlyControl).LastOrDefault<Control>((Control currentControl) => {
+ if (currentControl is PasswordBox || currentControl is TextBox || currentControl is ToggleButton || currentControl is DatePicker || currentControl is ComboBox || currentControl is AutoCompleteBox || currentControl is CheckComboBox)
+ {
+ return true;
+ }
+ return currentControl is Button;
+ });
+ }
+ control1 = control;
+ }
+ if (control1 == null)
+ {
+ return;
+ }
+ ComboBox comboBox = control1 as ComboBox;
+ if (comboBox != null && comboBox.IsDropDownOpen)
+ {
+ return;
+ }
+ if (control1 is TextBox && ((TextBox)control1).IsReadOnly)
+ {
+ return;
+ }
+ DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(control1);
+ if (dependencyProperty == null)
+ {
+ return;
+ }
+ BindingExpression bindingExpression = control1.GetBindingExpression(dependencyProperty);
+ if (bindingExpression == null)
+ {
+ return;
+ }
+ Validation.ClearInvalid(bindingExpression);
+ List<string> list = bindingExpression.ParentBinding.Path.Path.Split(new char[] { '.' }).ToList<string>();
+ Type type = bindingExpression.DataItem.GetType();
+ if (!list.Any<string>())
+ {
+ return;
+ }
+ PropertyInfo property = type.GetProperty(list.First<string>());
+ if (property == null)
+ {
+ return;
+ }
+ dynamic value = property.GetValue(bindingExpression.DataItem, null);
+ List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>();
+ if ((dynamic)(!ViewHelper.HasMethod(value, "ValidationEvent")))
+ {
+ dynamic resolvedSource = bindingExpression.ResolvedSource;
+ if (resolvedSource is Control)
+ {
+ return;
+ }
+ if ((dynamic)(!ViewHelper.HasMethod(resolvedSource, "ValidationEvent")))
+ {
+ return;
+ }
+ obj = resolvedSource;
+ if ((obj != null ? obj.ValidationEvent : null) == (dynamic)null)
+ {
+ return;
+ }
+ Func<List<KeyValuePair<string, string>>> func = resolvedSource.ValidationEvent as Func<List<KeyValuePair<string, string>>>;
+ if (func != null)
+ {
+ keyValuePairs = func();
+ }
+ if (keyValuePairs.Count == 0)
+ {
+ return;
+ }
+ }
+ if (keyValuePairs.Count == 0)
+ {
+ obj = value;
+ if ((obj != null ? obj.ValidationEvent : null) == (dynamic)null)
+ {
+ return;
+ }
+ Func<List<KeyValuePair<string, string>>> func1 = value.ValidationEvent as Func<List<KeyValuePair<string, string>>>;
+ if (func1 != null)
+ {
+ keyValuePairs = func1();
+ }
+ }
+ if (keyValuePairs == null || !keyValuePairs.Any<KeyValuePair<string, string>>())
+ {
+ return;
+ }
+ string str = (list.Last<string>() == "Id" ? list[list.Count - 2] : list.Last<string>());
+ string valueExact = ValidationHelper.GetValueExact(keyValuePairs, str);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ valueExact = ValidationHelper.GetValueExact(keyValuePairs, str);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ return;
+ }
+ }
+ Validation.MarkInvalid(bindingExpression, new ValidationError(new ExceptionValidationRule(), bindingExpression)
+ {
+ ErrorContent = valueExact
+ });
+ }
+
+ private static void DefaultBinding<T>(CheckComboBox comboBox, bool withSelect, bool enumDefault, string defaultValue = "", string defaultText = "", bool orderByLabel = false)
+ {
+ List<KeyValuePair<string, string>> keyValuePairs = BindingHelper.BindingData<T>(withSelect, enumDefault, defaultValue, defaultText, orderByLabel, false, false);
+ comboBox.ItemsSource = keyValuePairs;
+ comboBox.set_ValueMemberPath("Key");
+ comboBox.DisplayMemberPath = "Value";
+ comboBox.set_SelectedItem(keyValuePairs.First<KeyValuePair<string, string>>());
+ }
+
+ public static IEnumerable<T> FindAncestor<T>(DependencyObject dependencyObject)
+ where T : DependencyObject
+ {
+ for (DependencyObject i = VisualTreeHelper.GetParent(dependencyObject); i != null; i = VisualTreeHelper.GetParent(i))
+ {
+ T t = (T)(i as T);
+ if (t != null)
+ {
+ yield return t;
+ }
+ }
+ }
+
+ public static IEnumerable<T> FindChildren<T>(DependencyObject depObj)
+ where T : DependencyObject
+ {
+ if (depObj != null)
+ {
+ IEnumerator enumerator = LogicalTreeHelper.GetChildren(depObj).GetEnumerator();
+ while (enumerator.MoveNext())
+ {
+ object current = enumerator.Current;
+ T t = (T)(current as T);
+ if (t != null)
+ {
+ ContentControl contentControl = (object)t as ContentControl;
+ if (contentControl == null || (object)t as UserControl != null)
+ {
+ yield return t;
+ }
+ }
+ foreach (T t1 in ViewHelper.FindChildren<T>(current as DependencyObject))
+ {
+ yield return t1;
+ }
+ current = null;
+ }
+ enumerator = null;
+ }
+ else
+ {
+ }
+ }
+
+ public static IEnumerable<T> FindParent<T>(DependencyObject depObj)
+ where T : DependencyObject
+ {
+ if (depObj != null)
+ {
+ DependencyObject parent = LogicalTreeHelper.GetParent(depObj);
+ T t = (T)(parent as T);
+ if (t != null)
+ {
+ yield return t;
+ }
+ foreach (T t1 in ViewHelper.FindParent<T>(parent))
+ {
+ yield return t1;
+ }
+ }
+ else
+ {
+ }
+ }
+
+ private static DependencyProperty GetDependencyProperty(Control currentControl)
+ {
+ DependencyProperty selectedValueProperty = null;
+ if (currentControl is CheckComboBox)
+ {
+ selectedValueProperty = Xceed.Wpf.Toolkit.Primitives.Selector.SelectedValueProperty;
+ }
+ if (currentControl is DatePicker)
+ {
+ selectedValueProperty = DatePicker.SelectedDateProperty;
+ }
+ if (currentControl is AutoCompleteBox)
+ {
+ selectedValueProperty = AutoCompleteBox.SelectedItemProperty;
+ }
+ if (currentControl is TextBox)
+ {
+ selectedValueProperty = TextBox.TextProperty;
+ }
+ if (currentControl is MaskedTextBox)
+ {
+ selectedValueProperty = TextBox.TextProperty;
+ }
+ if (currentControl is ComboBox)
+ {
+ selectedValueProperty = System.Windows.Controls.Primitives.Selector.SelectedValueProperty;
+ }
+ if (currentControl is CurrencyTextBox)
+ {
+ selectedValueProperty = CurrencyTextBox.NumberProperty;
+ }
+ if (currentControl is ToggleButton)
+ {
+ selectedValueProperty = ToggleButton.IsCheckedProperty;
+ }
+ if (currentControl is CustomPasswordBox)
+ {
+ selectedValueProperty = CustomPasswordBox.TextProperty;
+ }
+ return selectedValueProperty;
+ }
+
+ public static bool HasMethod(object objectToCheck, string methodName)
+ {
+ if (objectToCheck == null)
+ {
+ return false;
+ }
+ return objectToCheck.GetType().GetProperty(methodName) != null;
+ }
+
+ public static bool IsPropertyExist(dynamic settings, string name)
+ {
+ if (settings is ExpandoObject)
+ {
+ return ((IDictionary<string, object>)settings).ContainsKey(name);
+ }
+ return (bool)(settings.GetType().GetProperty(name) != (dynamic)null);
+ }
+
+ public static bool IsValid(this DependencyObject obj)
+ {
+ if (Validation.GetHasError(obj))
+ {
+ return false;
+ }
+ return LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All<DependencyObject>(new Func<DependencyObject, bool>(ViewHelper.IsValid));
+ }
+
+ public static bool IsWindowOpen<T>(string name = "")
+ where T : Window
+ {
+ if (string.IsNullOrEmpty(name))
+ {
+ return System.Windows.Application.Current.Windows.OfType<T>().Any<T>();
+ }
+ return System.Windows.Application.Current.Windows.OfType<T>().Any<T>((T w) => w.Name.Equals(name));
+ }
+
+ public static Control SetInvalid(this Control currentControl, List<KeyValuePair<string, string>> errorMessages = null, string specificKey = null)
+ {
+ DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(currentControl);
+ if (dependencyProperty == null)
+ {
+ return null;
+ }
+ BindingExpression bindingExpression = currentControl.GetBindingExpression(dependencyProperty);
+ if (errorMessages == null)
+ {
+ dynamic obj = (bindingExpression != null ? bindingExpression.ResolvedSource : null);
+ if (obj is Control)
+ {
+ return null;
+ }
+ if ((dynamic)(!ViewHelper.HasMethod(obj, "ValidationEvent")))
+ {
+ return null;
+ }
+ dynamic obj1 = obj;
+ if ((obj1 != null ? obj1.ValidationEvent : null) == (dynamic)null)
+ {
+ return null;
+ }
+ Func<List<KeyValuePair<string, string>>> func = obj.ValidationEvent as Func<List<KeyValuePair<string, string>>>;
+ if (func != null)
+ {
+ errorMessages = func();
+ }
+ }
+ if (bindingExpression == null)
+ {
+ return null;
+ }
+ BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(currentControl, dependencyProperty);
+ if (bindingExpressionBase == null)
+ {
+ return null;
+ }
+ Validation.ClearInvalid(bindingExpressionBase);
+ if (errorMessages == null || !errorMessages.Any<KeyValuePair<string, string>>())
+ {
+ return null;
+ }
+ string[] strArrays = bindingExpression.ParentBinding.Path.Path.Split(new char[] { '.' });
+ string str = specificKey ?? (strArrays.Last<string>() == "Id" ? strArrays[(int)strArrays.Length - 2] : strArrays.Last<string>());
+ string valueExact = ValidationHelper.GetValueExact(errorMessages, str);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ valueExact = ValidationHelper.GetValueExact(errorMessages, str);
+ if (string.IsNullOrEmpty(valueExact))
+ {
+ return null;
+ }
+ }
+ Validation.MarkInvalid(bindingExpressionBase, new ValidationError(new ExceptionValidationRule(), bindingExpression)
+ {
+ ErrorContent = valueExact
+ });
+ return currentControl;
+ }
+
+ public static void SetInvalid(Control control, string error, bool valid)
+ {
+ DependencyProperty dependencyProperty = ViewHelper.GetDependencyProperty(control);
+ if (dependencyProperty == null)
+ {
+ return;
+ }
+ BindingExpression bindingExpression = control.GetBindingExpression(dependencyProperty);
+ if (bindingExpression == null)
+ {
+ return;
+ }
+ ValidationError validationError = new ValidationError(new ExceptionValidationRule(), bindingExpression)
+ {
+ ErrorContent = error
+ };
+ BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(control, dependencyProperty);
+ if (bindingExpressionBase == null)
+ {
+ return;
+ }
+ Validation.ClearInvalid(bindingExpressionBase);
+ if (valid)
+ {
+ return;
+ }
+ Validation.MarkInvalid(bindingExpressionBase, validationError);
+ }
+
+ public static void ValidateFields(this DependencyObject dependencyObject, List<KeyValuePair<string, string>> errorMessages, bool focusField = true)
+ {
+ if ((errorMessages == null ? true : !errorMessages.Any<KeyValuePair<string, string>>()))
+ {
+ dependencyObject.ClearInvalid();
+ return;
+ }
+ Control control = null;
+ foreach (Control control1 in ViewHelper.FindChildren<Control>(dependencyObject))
+ {
+ Control control2 = control1.SetInvalid(errorMessages, null);
+ if (control != null || control2 == null)
+ {
+ continue;
+ }
+ control = control2;
+ }
+ if (focusField && control != null)
+ {
+ control.Focus();
+ }
+ }
+
+ public static T Window<T>()
+ where T : Window
+ {
+ return System.Windows.Application.Current.Windows.OfType<T>().FirstOrDefault<T>();
+ }
+ }
+}
\ No newline at end of file |