using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Gestor.Common.Helpers; using Gestor.Model.Attributes; using Gestor.Model.Helper; using Microsoft.Win32; namespace Gestor.Common.Validation; public static class ValidationHelper { public static T GetEnumFromDescription(string description) { Type typeFromHandle = typeof(T); if (!typeFromHandle.IsEnum) { throw new InvalidOperationException(); } FieldInfo[] fields = typeFromHandle.GetFields(); foreach (FieldInfo fieldInfo in fields) { if (Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) is DescriptionAttribute descriptionAttribute) { if (descriptionAttribute.Description == description) { return (T)fieldInfo.GetValue(null); } } else if (fieldInfo.Name == description) { return (T)fieldInfo.GetValue(null); } } throw new ArgumentException("Not found.", "description"); } public static T GetEnumFromEntity(this string entityName) { Type typeFromHandle = typeof(T); if (!typeFromHandle.IsEnum) { return default(T); } FieldInfo[] fields = typeFromHandle.GetFields(); foreach (FieldInfo fieldInfo in fields) { Attribute? customAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(EntityAttribute)); EntityAttribute val = (EntityAttribute)(object)((customAttribute is EntityAttribute) ? customAttribute : null); if (val != null) { if (val.Description == entityName) { return (T)fieldInfo.GetValue(null); } } else if (fieldInfo.Name == entityName) { return (T)fieldInfo.GetValue(null); } } return default(T); } public static string DescriptionAttribute(this PropertyInfo pi) { object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true).FirstOrDefault(); if (obj == null) { return ""; } return ((DescriptionAttribute)obj).Description; } public static string GetCategory(this Enum genericEnum) { MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(CategoryAttribute), inherit: false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((CategoryAttribute)customAttributes.ElementAt(0)).Category; } public static string GetEntity(this Enum genericEnum) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(EntityAttribute), inherit: false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((EntityAttribute)customAttributes.ElementAt(0)).Description; } public static string GetDescription(this Enum genericEnum) { if (genericEnum == null) { return ""; } MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), inherit: false); if (!customAttributes.Any()) { return genericEnum.ToString().Trim(); } return ((DescriptionAttribute)customAttributes.ElementAt(0)).Description.Trim(); } public static string GetTipo(this Enum genericEnum) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(TipoAttribute), inherit: false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((TipoAttribute)customAttributes.ElementAt(0)).Description; } public static string GetHelp(this Enum genericEnum) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(HelpAttribute), inherit: false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((HelpAttribute)customAttributes.ElementAt(0)).Description; } public static string Mask(this string value, string mask) { int num = mask.Count((char x) => x == '#'); if (string.IsNullOrEmpty(value) || num != value.Length) { return string.Empty; } string text = string.Empty; int num2 = 0; int num3 = 0; for (int i = 0; i < mask.Length; i++) { if (mask[i] != '#') { text += $"{value.Substring(num2, i - num2 - num3)}{mask[i]}"; num2 = i - num3; num3++; } } return text + value.Substring(num2, mask.Length - num2 - num3); } public static string Length(this string stringValue, int maxLength) { if (stringValue.Length > maxLength) { return stringValue.Substring(0, maxLength); } return stringValue; } public static string StringValue(this decimal decimalValue) { return decimalValue.ToString("F", new CultureInfo("en-US")); } public static int ToInt(this string stringValue) { int.TryParse(stringValue, out var result); return result; } public static long ToLong(this string stringValue) { long.TryParse(stringValue, out var result); return result; } public static int? ToIntNullable(this string stringValue) { if (int.TryParse(stringValue, out var result)) { return result; } return null; } public static long? ToLongNullable(this string stringValue) { if (long.TryParse(stringValue, out var result)) { return result; } return null; } public static string ToTitleCase(this string stringValue) { return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(stringValue.ToLower()); } public static string Join(this IEnumerable stringValues, string separator) { return string.Join(separator, stringValues); } public static string ToCurrencyWithSymbol(this T currencyDecimal, string currentCulture = "pt-BR") { return string.Format(new CultureInfo(currentCulture), "R$ {0:N2}", currencyDecimal); } public static string ToCurrency(this T currencyDecimal, string currentCulture = "pt-BR") { return string.Format(new CultureInfo(currentCulture), "{0:N2}", currencyDecimal); } public static decimal ToCurrency(this string currencyString, string currentCulture = "pt-BR") { decimal.TryParse(currencyString.ClearCurrency(), NumberStyles.Any, new CultureInfo(currentCulture), out var result); return result; } public static string ToFloating(this T currencyDecimal, string currentCulture = "pt-BR") { return string.Format(new CultureInfo(currentCulture), "{0:F}", currencyDecimal); } public static string Alphanumeric(this string stringToClean, string replaceWith = "") { return Regex.Replace(stringToClean, "[^a-zA-Z0-9]", replaceWith); } public static string AlphanumericAndSpace(this string stringToClean) { return Regex.Replace(stringToClean, "[^a-zA-Z0-9 ]", string.Empty); } public static string RemoveDiacritics(this string stringWithAccents) { if (stringWithAccents == null) { return ""; } return Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(stringWithAccents)); } public static string RemoverAcentos(this string text) { if (string.IsNullOrEmpty(text)) { return string.Empty; } return new string((from c in text.Normalize(NormalizationForm.FormD) where char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark select c).ToArray()); } public static string RemoveTag(this string stringWithTag) { return Regex.Replace(stringWithTag, "<(.|\\n)*?>", string.Empty); } public static string Clear(this string stringToClean) { if (stringToClean != null) { return Regex.Replace(stringToClean, "[^\\d]", string.Empty); } return null; } public static bool IsNullOrEmpty(this string stringToVerify) { return string.IsNullOrEmpty(stringToVerify); } public static bool NotEquals(this string obj, string value) { return !obj.Equals(value); } public static DateTime ToDateTime(this string dateString) { DateTime.TryParse(dateString.Trim(), out var result); return result; } public static string ToToken(this string postCode) { return Functions.GetNetworkTime().ToFileTime().ToString(); } public static DateTime? ToDateTimeNullable(this string dateString) { if (dateString == null) { return null; } DateTime.TryParse(dateString.Trim(), out var result); if (!(result == DateTime.MinValue)) { return result; } return null; } public static string ClearCurrency(this string stringToClean) { if (!string.IsNullOrEmpty(stringToClean)) { return Regex.Replace(stringToClean, "[^\\d\\,\\.]", string.Empty); } return string.Empty; } public static bool ContainsEquals(this T @this, params T[] possibles) { return possibles.Contains(@this); } public static bool ContainsAny(this string stringToCheck, params string[] stringArray) { return stringArray.Any(stringToCheck.Contains); } public static int Age(this DateTime birthDate) { DateTime date = Functions.GetNetworkTime().Date; int num = date.Year - birthDate.Year; if (birthDate > date.AddYears(-num)) { num--; } return num; } public static bool ValidateDocument(this string cpfCnpj) { if (string.IsNullOrEmpty(cpfCnpj)) { return false; } string text = cpfCnpj.Clear(); int[] array = new int[14]; int[] array2 = new int[2]; if (text == string.Empty || new string(text[0], text.Length) == text) { return false; } if (text.Length == 11) { for (int i = 0; i <= 10; i++) { array[i] = Convert.ToInt32(text.Substring(i, 1)); } for (int i = 0; i <= 1; i++) { int num = 0; for (int j = 0; j <= 8 + i; j++) { num += array[j] * (10 + i - j); } array2[i] = num * 10 % 11; if (array2[i] == 10) { array2[i] = 0; } } return (array2[0] == array[9]) & (array2[1] == array[10]); } if (text.Length != 14) { return false; } for (int i = 0; i <= 13; i++) { array[i] = Convert.ToInt32(text.Substring(i, 1)); } for (int i = 0; i <= 1; i++) { int num = 0; for (int j = 0; j <= 11 + i; j++) { num += array[j] * Convert.ToInt32("6543298765432".Substring(j + 1 - i, 1)); } array2[i] = num * 10 % 11; if (array2[i] == 10) { array2[i] = 0; } } return (array2[0] == array[12]) & (array2[1] == array[13]); } public static bool ValidateChassi(this string chassiNumber) { chassiNumber = chassiNumber?.ToUpper(); if (!string.IsNullOrEmpty(chassiNumber)) { if (chassiNumber.Length == 17 && !Regex.IsMatch(chassiNumber, "^0| |^.{4,}([0-9A-Z])\\1{5,}|[iIoOqQ]")) { return Regex.IsMatch(chassiNumber, "[0-9]{4}$"); } return false; } return true; } public static bool ValidatePlate(this string plateNumber) { if (!string.IsNullOrEmpty(plateNumber?.Alphanumeric())) { return Regex.IsMatch(plateNumber, "^[a-zA-Z]{3}-?[0-9]{4}$"); } return true; } public static bool ValidateMail(this string mail) { if (mail == null) { return false; } return new Regex("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$").IsMatch(mail); } public static bool ValidatePhone(this string number) { if (number != null) { return Regex.Match(number, "^([2-9][0-9]{3,4})\\-([0-9]{4})$").Success; } return false; } public static bool ValidateInt(this string value) { int result; return int.TryParse(value, out result); } public static bool ValidateLong(this string value) { long result; return long.TryParse(value, out result); } public static bool ValidateDecimal(this string value) { decimal result; return decimal.TryParse(value, out result); } public static bool ValidateValor(this string value) { string[] array = value.Split(new char[1] { '.' }); if (array.Length < 2) { return true; } if (array.Length == 2) { return array[1].Length <= 2; } return false; } public static bool ValidatePrefix(this string prefix) { if (!int.TryParse(prefix, out var result)) { return false; } if (result == 20 || result == 23 || result == 25 || result == 26 || result == 29 || result == 30 || result == 36 || result == 39 || result == 40 || result == 50 || result == 52 || result == 56 || result == 57 || result == 58 || result == 59 || result == 60 || result == 70 || result == 72 || result == 76 || result == 78 || result == 80 || result == 90 || result < 11 || result > 99) { return false; } return true; } public static bool ValidatePostCode(this string postCode) { if (postCode != null) { return Regex.Match(postCode, "^[0-9]{2}.?[0-9]{3}-[0-9]{3}$").Success; } return false; } public static bool ValidateDouble(this string number) { double result; return double.TryParse(number, out result); } public static bool ValidateDate(this string birthday) { DateTime result; return DateTime.TryParse(birthday, out result); } public static bool ValidateAno(this string ano) { if (int.TryParse(ano, out var _)) { return ano.Length == 4; } return false; } public static bool ValidatePastDate(this string birthday) { if (DateTime.TryParse(birthday, out var result)) { return result < Functions.GetNetworkTime().Date; } return false; } public static bool ValidateFutureDate(this string birthday) { if (DateTime.TryParse(birthday, out var result)) { return result > Functions.GetNetworkTime().Date; } return false; } public static bool ValidateAttendanceNumber(this string number) { if (number != null) { return Regex.Match(number, "^[0-9]").Success; } return false; } public static string Normalized(this string word) { if (string.IsNullOrEmpty(word)) { return string.Empty; } return Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(word)).ToUpper().Trim(); } public static string GetDefaultExtension(this string mimeType) { object obj = Registry.ClassesRoot.OpenSubKey("MIME\\Database\\Content Type\\" + mimeType, writable: false)?.GetValue("Extension", null); if (obj == null) { return string.Join(string.Empty, mimeType.Split(Path.GetInvalidPathChars())).Replace("/", "."); } return obj.ToString(); } public static string NormalizePath(this string fullFilename) { char[] invalidPathChars = Path.GetInvalidPathChars(); char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); fullFilename = fullFilename.Replace("/", string.Empty); string text = Path.GetFileName(fullFilename); string text2 = Path.GetDirectoryName(fullFilename); char[] array = invalidPathChars; foreach (char c in array) { text2 = text2.Replace(c.ToString(), string.Empty); } array = invalidFileNameChars; foreach (char c2 in array) { text = text.Replace(c2.ToString(), string.Empty); } return text2 + "\\" + text; } public static string OnlyNumber(this string sentence) { if (sentence == null) { return null; } return new Regex("[^\\d]").Replace(sentence, ""); } public static string FormatarTelefone(this string number) { number = number?.OnlyNumber(); return number?.Length switch { 8 => Convert.ToUInt64(number).ToString("0000\\-0000"), 9 => Convert.ToUInt64(number).ToString("00000\\-0000"), 11 => Convert.ToUInt64(number).ToString("0000 000 0000"), _ => number.Clear(), }; } public static string FormatPostCode(this string postCode) { if (!string.IsNullOrEmpty(postCode)) { return Convert.ToUInt64(postCode.OnlyNumber()).ToString("00000\\-000"); } return ""; } public static string FormatRegiao(this string str) { if (Regex.Match(str, "[^0-9-.]").Success) { return str; } if (!string.IsNullOrEmpty(str)) { return Convert.ToUInt64(str.OnlyNumber()).ToString("00\\.000\\-000"); } return ""; } public static string FormatFipe(this string value) { if (!string.IsNullOrEmpty(value)) { return Convert.ToUInt64(value.OnlyNumber()).ToString("000000\\-0"); } return ""; } public static bool IsNotNullOrEmpty(this string stringToVerify) { return !string.IsNullOrEmpty(stringToVerify); } public static string FormatRenavam(this string value) { if (!string.IsNullOrEmpty(value)) { if (!long.TryParse(value.OnlyNumber(), out var result)) { return string.Empty; } return result.ToString("00\\.000\\.000\\.000"); } return string.Empty; } public static string FormatCi(this string value) { string text = value.OnlyNumber().Trim(); if (string.IsNullOrEmpty(text)) { return string.Empty; } if (long.TryParse(text, out var _)) { return Convert.ToUInt64(text).ToString("00\\.000\\.000\\.000\\.000"); } return text; } public static bool ValidateState(this string state) { if (!string.IsNullOrEmpty(state)) { return new string[27] { "AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO" }.Contains(state.ToUpper()); } return false; } public static bool ValidateOrgao(this string orgao) { if (!string.IsNullOrEmpty(orgao)) { return new string[70] { "SSP", "DETRAN", "ABNC", "CGPI", "DUREX", "DPF", "CGPI", "CGPMAF", "CNIG", "CNT", "COREN", "CORECON", "CRA", "CRAS", "CRB", "CRC", "CRE", "CREA", "CRECI", "CREFIT", "CRESS", "CRF", "CRM", "CRN", "CRO", "CRP", "CRPRE", "CRQ", "CRRC", "CRMV", "CSC", "CTPS", "DIC", "DIREX", "DPMAF", "DPT", "DST", "FGTS", "FIPE", "FLS", "GOVGO", "I CLA", "IFP", "IGP", "IICCECF/RO", "IIMG", "IML", "IPC", "IPF", "MAE", "MEX", "MMA", "OAB", "OMB", "PCMG", "PMMG", "POM", "SDS", "SNJ", "SECC", "SEJUSP", "SES", "EST", "SESP", "SJS", "SJTC", "SJTS", "SPTC", "DGPC", "" }.Contains(orgao.ToUpper()); } return false; } public static bool ValidateFipe(this string value) { if (new Regex("^\\d{6}\\-\\d{1}$").IsMatch(value)) { return true; } return false; } public static string FormatDocument(this string number) { number = number.OnlyNumber(); return number.Length switch { 11 => Convert.ToUInt64(number).ToString("000\\.000\\.000\\-00"), 14 => Convert.ToUInt64(number).ToString("00\\.000\\.000\\/0000\\-00"), _ => number, }; } public static string FormatCurrency(this string value) { if (string.IsNullOrEmpty(value)) { return ""; } return value.ToCurrency().ToString("c"); } public static string FormatDate(this string date) { if (string.IsNullOrEmpty(date)) { return ""; } date = date.OnlyNumber(); switch (date.Length) { case 4: date += Functions.GetNetworkTime().Date.Year; return Convert.ToUInt64(date).ToString("00\\/00\\/0000"); case 6: return Convert.ToUInt64(date).ToString("00\\/00\\/00"); case 8: return Convert.ToUInt64(date).ToString("00\\/00\\/0000"); default: return date; } } public static string FormatCompetencia(this string date) { if (string.IsNullOrEmpty(date)) { return ""; } date = date.OnlyNumber(); switch (date.Length) { case 2: date += Functions.GetNetworkTime().Date.Year; return Convert.ToUInt64(date).ToString("00\\/0000"); case 4: return Convert.ToUInt64(date).ToString("00\\/00"); case 6: return Convert.ToUInt64(date).ToString("00\\/0000"); default: return date; } } public static string FormatTime(this string time) { if (string.IsNullOrEmpty(time)) { return null; } time = time.OnlyNumber(); return time.Length switch { 4 => Convert.ToUInt64(time).ToString("00:00"), 3 => Convert.ToUInt64(time).ToString("00:00"), _ => null, }; } public static void AddSorted(this ObservableCollection list, T item, IComparer comparer = null) { if (comparer == null) { comparer = Comparer.Default; } int i; for (i = 0; i < list.Count && comparer.Compare(list[i], item) < 0; i++) { } list.Insert(i, item); } public static bool ValidateCei(this string cei) { if (string.IsNullOrEmpty(cei)) { return false; } cei = cei.Trim(); cei = Regex.Replace(cei, "[^\\d]", ""); if (cei.Length != 12) { return false; } int num = 0; for (int i = 1; i < 12; i++) { int num2 = Convert.ToInt32("74185216374".Substring(i - 1, 1)); int num3 = Convert.ToInt32(cei.Substring(i - 1, 1)); num += num2 * num3; } int num4 = num / 10; int num5 = num - num / 10 * 10; num = num4 + num5; num5 = num - num / 10 * 10; int num6 = Convert.ToInt32(cei.Substring(11, 1)); int num7 = 10 - num5; return num6 == num7; } public static bool ValidateRne(this string rne) { if (string.IsNullOrEmpty(rne)) { return false; } return true; } public static bool ValidateCaepf(this string caepf) { return !string.IsNullOrEmpty(caepf); } public static string Captalize(this string text) { return new CultureInfo("pt-Br", useUserOverride: false).TextInfo.ToTitleCase(text.ToLower()); } public static bool ValidaCep(this string cep) { if (string.IsNullOrWhiteSpace(cep)) { return Regex.IsMatch(cep, "^\\d{5}-?\\d{3}$"); } return false; } }