using Gestor.Common.Helpers; using Gestor.Model.Attributes; using Gestor.Model.Helper; using Microsoft.Win32; 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.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace Gestor.Common.Validation { public static class ValidationHelper { public static void AddSorted(this ObservableCollection list, T item, IComparer comparer = null) { if (comparer == null) { comparer = Comparer.Default; } int num = 0; while (num < list.Count && comparer.Compare(list[num], item) < 0) { num++; } list.Insert(num, item); } public static int Age(this DateTime birthDate) { DateTime date = Functions.GetNetworkTime().Date; int year = date.Year - birthDate.Year; if (birthDate > date.AddYears(-year)) { year--; } return year; } 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 Captalize(this string text) { return (new CultureInfo("pt-Br", false)).TextInfo.ToTitleCase(text.ToLower()); } public static string Clear(this string stringToClean) { if (stringToClean == null) { return null; } return Regex.Replace(stringToClean, "[^\\d]", string.Empty); } public static string ClearCurrency(this string stringToClean) { if (string.IsNullOrEmpty(stringToClean)) { return string.Empty; } return Regex.Replace(stringToClean, "[^\\d\\,\\.]", string.Empty); } public static bool ContainsAny(this string stringToCheck, params string[] stringArray) { return stringArray.Any(new Func(stringToCheck.Contains)); } public static bool ContainsEquals(this T @this, params T[] possibles) { return possibles.Contains(@this); } public static string DescriptionAttribute(this PropertyInfo pi) { object obj = pi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); if (obj == null) { return ""; } return ((DescriptionAttribute)obj).Description; } public static string FormatarTelefone(this string number) { string str; int? nullable; if (number != null) { str = number.OnlyNumber(); } else { str = null; } number = str; if (number != null) { nullable = new int?(number.Length); } else { nullable = null; } int? nullable1 = nullable; if (nullable1.HasValue) { switch (nullable1.GetValueOrDefault()) { case 8: { return Convert.ToUInt64(number).ToString("0000\\-0000"); } case 9: { return Convert.ToUInt64(number).ToString("00000\\-0000"); } case 11: { return Convert.ToUInt64(number).ToString("0000 000 0000"); } } } return number.Clear(); } public static string FormatCi(this string value) { long num; string str = value.OnlyNumber().Trim(); if (string.IsNullOrEmpty(str)) { return string.Empty; } if (!long.TryParse(str, out num)) { return str; } return Convert.ToUInt64(str).ToString("00\\.000\\.000\\.000\\.000"); } public static string FormatCompetencia(this string date) { if (string.IsNullOrEmpty(date)) { return ""; } date = date.OnlyNumber(); switch (date.Length) { case 2: { int year = Functions.GetNetworkTime().Date.Year; date = string.Concat(date, year.ToString()); return Convert.ToUInt64(date).ToString("00\\/0000"); } case 3: case 5: { return date; } case 4: { return Convert.ToUInt64(date).ToString("00\\/00"); } case 6: { return Convert.ToUInt64(date).ToString("00\\/0000"); } default: { return date; } } } public static string FormatCurrency(this string value) { if (string.IsNullOrEmpty(value)) { return ""; } return value.ToCurrency("pt-BR").ToString("c"); } public static string FormatDate(this string date) { if (string.IsNullOrEmpty(date)) { return ""; } date = date.OnlyNumber(); switch (date.Length) { case 4: { int year = Functions.GetNetworkTime().Date.Year; date = string.Concat(date, year.ToString()); return Convert.ToUInt64(date).ToString("00\\/00\\/0000"); } case 5: case 7: { return date; } 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 FormatDocument(this string number) { number = number.OnlyNumber(); int length = number.Length; if (length == 11) { return Convert.ToUInt64(number).ToString("000\\.000\\.000\\-00"); } if (length != 14) { return number; } return Convert.ToUInt64(number).ToString("00\\.000\\.000\\/0000\\-00"); } public static string FormatFipe(this string value) { if (string.IsNullOrEmpty(value)) { return ""; } ulong num = Convert.ToUInt64(value.OnlyNumber()); return num.ToString("000000\\-0"); } public static string FormatPostCode(this string postCode) { if (string.IsNullOrEmpty(postCode)) { return ""; } return postCode.FormataCep(); } public static string FormatRegiao(this string str) { if (Regex.Match(str, "[^0-9-.]").Success) { return str; } if (string.IsNullOrEmpty(str)) { return ""; } ulong num = Convert.ToUInt64(str.OnlyNumber()); return num.ToString("00\\.000\\-000"); } public static string FormatRenavam(this string value) { long num; if (string.IsNullOrEmpty(value)) { return string.Empty; } if (!long.TryParse(value.OnlyNumber(), out num)) { return string.Empty; } return num.ToString("00\\.000\\.000\\.000"); } public static string FormatTime(this string time) { if (string.IsNullOrEmpty(time)) { return null; } time = time.OnlyNumber(); int length = time.Length; if (length == 3) { return Convert.ToUInt64(time).ToString("00:00"); } if (length != 4) { return null; } return Convert.ToUInt64(time).ToString("00:00"); } 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), false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((CategoryAttribute)customAttributes.ElementAt(0)).Category; } public static string GetDefaultExtension(this string mimeType) { object value; RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(string.Concat("MIME\\Database\\Content Type\\", mimeType), false); if (registryKey != null) { value = registryKey.GetValue("Extension", null); } else { value = null; } object obj = value; if (obj != null) { return obj.ToString(); } return string.Join(string.Empty, mimeType.Split(Path.GetInvalidPathChars())).Replace("/", "."); } 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), false); if (!customAttributes.Any()) { return genericEnum.ToString().Trim(); } return ((DescriptionAttribute)customAttributes.ElementAt(0)).Description.Trim(); } public static string GetEntity(this Enum genericEnum) { MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(EntityAttribute), false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((EntityAttribute)customAttributes.ElementAt(0)).Description; } public static T GetEnumFromDescription(string description) { Type type = typeof(T); if (!type.IsEnum) { throw new InvalidOperationException(); } FieldInfo[] fields = type.GetFields(); for (int i = 0; i < (int)fields.Length; i++) { FieldInfo fieldInfo = fields[i]; DescriptionAttribute customAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute; if (customAttribute != null) { if (customAttribute.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) { T t; Type type = typeof(T); if (!type.IsEnum) { t = default(T); return t; } FieldInfo[] fields = type.GetFields(); for (int i = 0; i < (int)fields.Length; i++) { FieldInfo fieldInfo = fields[i]; EntityAttribute customAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(EntityAttribute)) as EntityAttribute; if (customAttribute != null) { if (customAttribute.Description == entityName) { return (T)fieldInfo.GetValue(null); } } else if (fieldInfo.Name == entityName) { return (T)fieldInfo.GetValue(null); } } t = default(T); return t; } public static string GetHelp(this Enum genericEnum) { MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(HelpAttribute), false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((HelpAttribute)customAttributes.ElementAt(0)).Description; } public static string GetTipo(this Enum genericEnum) { MemberInfo[] member = genericEnum.GetType().GetMember(genericEnum.ToString()); if (member.Length == 0) { return genericEnum.ToString(); } object[] customAttributes = member[0].GetCustomAttributes(typeof(TipoAttribute), false); if (!customAttributes.Any()) { return genericEnum.ToString(); } return ((TipoAttribute)customAttributes.ElementAt(0)).Description; } public static bool IsNotNullOrEmpty(this string stringToVerify) { return !string.IsNullOrEmpty(stringToVerify); } public static bool IsNullOrEmpty(this string stringToVerify) { return string.IsNullOrEmpty(stringToVerify); } public static string Join(this IEnumerable stringValues, string separator) { return string.Join(separator, stringValues); } public static string Length(this string stringValue, int maxLength) { if (stringValue.Length <= maxLength) { return stringValue; } return stringValue.Substring(0, maxLength); } 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 empty = string.Empty; int num1 = 0; int num2 = 0; for (int i = 0; i < mask.Length; i++) { if (mask[i] != '#') { empty = string.Concat(empty, string.Format("{0}{1}", value.Substring(num1, i - num1 - num2), mask[i])); num1 = i - num2; num2++; } } empty = string.Concat(empty, value.Substring(num1, mask.Length - num1 - num2)); return empty; } 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 NormalizePath(this string fullFilename) { int i; char[] invalidPathChars = Path.GetInvalidPathChars(); char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); fullFilename = fullFilename.Replace("/", string.Empty); string fileName = Path.GetFileName(fullFilename); string directoryName = Path.GetDirectoryName(fullFilename); char[] chrArray = invalidPathChars; for (i = 0; i < (int)chrArray.Length; i++) { char chr = chrArray[i]; directoryName = directoryName.Replace(chr.ToString(), string.Empty); } chrArray = invalidFileNameChars; for (i = 0; i < (int)chrArray.Length; i++) { char chr1 = chrArray[i]; fileName = fileName.Replace(chr1.ToString(), string.Empty); } return string.Concat(directoryName, "\\", fileName); } public static bool NotEquals(this string obj, string value) { return !obj.Equals(value); } public static string OnlyNumber(this string sentence) { if (sentence == null) { return null; } return (new Regex("[^\\d]")).Replace(sentence, ""); } 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 StringValue(this decimal decimalValue) { return decimalValue.ToString("F", new CultureInfo("en-US")); } 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 num; decimal.TryParse(currencyString.ClearCurrency(), NumberStyles.Any, new CultureInfo(currentCulture), out num); return num; } public static string ToCurrencyWithSymbol(this T currencyDecimal, string currentCulture = "pt-BR") { return string.Format(new CultureInfo(currentCulture), "R$ {0:N2}", currencyDecimal); } public static DateTime ToDateTime(this string dateString) { DateTime dateTime; DateTime.TryParse(dateString.Trim(), out dateTime); return dateTime; } public static DateTime? ToDateTimeNullable(this string dateString) { DateTime dateTime; DateTime? nullable; if (dateString == null) { nullable = null; return nullable; } DateTime.TryParse(dateString.Trim(), out dateTime); if (dateTime != DateTime.MinValue) { return new DateTime?(dateTime); } nullable = null; return nullable; } public static string ToFloating(this T currencyDecimal, string currentCulture = "pt-BR") { return string.Format(new CultureInfo(currentCulture), "{0:F}", currencyDecimal); } public static int ToInt(this string stringValue) { int num; int.TryParse(stringValue, out num); return num; } public static int? ToIntNullable(this string stringValue) { int num; if (int.TryParse(stringValue, out num)) { return new int?(num); } return null; } public static long ToLong(this string stringValue) { long num; long.TryParse(stringValue, out num); return num; } public static long? ToLongNullable(this string stringValue) { long num; if (long.TryParse(stringValue, out num)) { return new long?(num); } return null; } public static string ToTitleCase(this string stringValue) { return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(stringValue.ToLower()); } public static string ToToken(this string postCode) { return Functions.GetNetworkTime().ToFileTime().ToString(); } public static bool ValidaCep(this string cep) { if (!string.IsNullOrWhiteSpace(cep)) { return false; } return Regex.IsMatch(cep, "^\\d{5}-?\\d{3}$"); } public static bool ValidateAno(this string ano) { int num; if (!int.TryParse(ano, out num)) { return false; } return ano.Length == 4; } public static bool ValidateAttendanceNumber(this string number) { if (number == null) { return false; } return Regex.Match(number, "^[0-9]").Success; } public static bool ValidateCaepf(this string caepf) { return !string.IsNullOrEmpty(caepf); } 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 num1 = Convert.ToInt32("74185216374".Substring(i - 1, 1)); int num2 = Convert.ToInt32(cei.Substring(i - 1, 1)); num = num + num1 * num2; } int num3 = num / 10; int num4 = num - num / 10 * 10; num = num3 + num4; num4 = num - num / 10 * 10; int num5 = 10 - num4; return Convert.ToInt32(cei.Substring(11, 1)) == num5; } public static bool ValidateChassi(this string chassiNumber) { string upper; if (chassiNumber != null) { upper = chassiNumber.ToUpper(); } else { upper = null; } chassiNumber = upper; if (string.IsNullOrEmpty(chassiNumber)) { return true; } if (chassiNumber.Length != 17 || Regex.IsMatch(chassiNumber, "^0| |^.{4,}([0-9A-Z])\\1{5,}|[iIoOqQ]")) { return false; } return Regex.IsMatch(chassiNumber, "[0-9]{4}$"); } public static bool ValidateDate(this string birthday) { DateTime dateTime; return DateTime.TryParse(birthday, out dateTime); } public static bool ValidateDecimal(this string value) { decimal num; return decimal.TryParse(value, out num); } public static bool ValidateDocument(this string cpfCnpj) { int j; int i; int num; if (string.IsNullOrEmpty(cpfCnpj)) { return false; } string str = cpfCnpj.Clear(); int[] numArray = new int[14]; int[] numArray1 = new int[2]; if (str == string.Empty || new string(str[0], str.Length) == str) { return false; } if (str.Length == 11) { for (i = 0; i <= 10; i++) { numArray[i] = Convert.ToInt32(str.Substring(i, 1)); } for (i = 0; i <= 1; i++) { num = 0; for (j = 0; j <= 8 + i; j++) { num = num + numArray[j] * (10 + i - j); } numArray1[i] = num * 10 % 11; if (numArray1[i] == 10) { numArray1[i] = 0; } } return numArray1[0] == numArray[9] & numArray1[1] == numArray[10]; } if (str.Length != 14) { return false; } for (i = 0; i <= 13; i++) { numArray[i] = Convert.ToInt32(str.Substring(i, 1)); } for (i = 0; i <= 1; i++) { num = 0; for (j = 0; j <= 11 + i; j++) { num = num + numArray[j] * Convert.ToInt32("6543298765432".Substring(j + 1 - i, 1)); } numArray1[i] = num * 10 % 11; if (numArray1[i] == 10) { numArray1[i] = 0; } } return numArray1[0] == numArray[12] & numArray1[1] == numArray[13]; } public static bool ValidateDouble(this string number) { double num; return double.TryParse(number, out num); } public static bool ValidateFipe(this string value) { if ((new Regex("^\\d{6}\\-\\d{1}$")).IsMatch(value)) { return true; } return false; } public static bool ValidateFutureDate(this string birthday) { DateTime dateTime; if (!DateTime.TryParse(birthday, out dateTime)) { return false; } return dateTime > Functions.GetNetworkTime().Date; } public static bool ValidateInt(this string value) { int num; return int.TryParse(value, out num); } public static bool ValidateLong(this string value) { long num; return long.TryParse(value, out num); } 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 ValidateOrgao(this string orgao) { if (string.IsNullOrEmpty(orgao)) { return false; } return (new string[] { "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()); } public static bool ValidatePastDate(this string birthday) { DateTime dateTime; if (!DateTime.TryParse(birthday, out dateTime)) { return false; } return dateTime < Functions.GetNetworkTime().Date; } public static bool ValidatePhone(this string number) { if (number == null) { return false; } return Regex.Match(number, "^([2-9][0-9]{3,4})\\-([0-9]{4})$").Success; } public static bool ValidatePlate(this string plateNumber) { string str; if (plateNumber != null) { str = plateNumber.Alphanumeric(""); } else { str = null; } if (string.IsNullOrEmpty(str)) { return true; } return Regex.IsMatch(plateNumber, "^[a-zA-Z]{3}-?[0-9]{4}$"); } public static bool ValidatePostCode(this string postCode) { if (postCode == null) { return false; } return Regex.Match(postCode, "^[0-9]{2}.?[0-9]{3}-[0-9]{3}$").Success; } public static bool ValidatePrefix(this string prefix) { int num; if (!int.TryParse(prefix, out num)) { return false; } if (num != 20 && num != 23 && num != 25 && num != 26 && num != 29 && num != 30 && num != 36 && num != 39 && num != 40 && num != 50 && num != 52 && num != 56 && num != 57 && num != 58 && num != 59 && num != 60 && num != 70 && num != 72 && num != 76 && num != 78 && num != 80 && num != 90 && num >= 11 && num <= 99) { return true; } return false; } public static bool ValidateRne(this string rne) { if (string.IsNullOrEmpty(rne)) { return false; } return true; } public static bool ValidateState(this string state) { if (string.IsNullOrEmpty(state)) { return false; } return (new string[] { "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()); } public static bool ValidateValor(this string value) { string[] strArrays = value.Split(new char[] { '.' }); if ((int)strArrays.Length < 2) { return true; } if ((int)strArrays.Length != 2) { return false; } return strArrays[1].Length <= 2; } } }