using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using Microsoft.VisualBasic; using Microsoft.VisualBasic.CompilerServices; namespace tsUtilidades { public enum FormatoFechasEnum : int { FECHA_HORA = 0, FECHA_SEPARADO_POR_BARRAS = 1, FECHA_ESPACIADO_GRANDE = 2, FECHA_ESPACIADO_PEQUEÑO = 3 } public class Utilidades { public static string CodificarBase64(string texto) { byte[] stringbytes = Encoding.ASCII.GetBytes(texto); return Convert.ToBase64String(stringbytes).TrimEnd('=').Replace("+", "-").Replace("/", "_"); } public static string DecodificarBase64(string texto) { byte[] bytes = Convert.FromBase64String(texto); return Encoding.ASCII.GetString(bytes); } public static void EliminaDirectorioTemporal(string Subdirectorio) { string sDir = Path.GetTempPath() + @"\" + Subdirectorio + @"\"; if (Directory.Exists(sDir)) { try { Directory.Delete(sDir, true); } catch (Exception ex) { } } } public static string ObtieneMensajeExcepcionCompleto(Exception ex) { string sMensaje = "Tipo excepción: " + ex.ToString() + Constants.vbCrLf; var exError = ex; do { sMensaje += exError.StackTrace + Constants.vbCrLf; exError = exError.InnerException; } while (exError != null); return sMensaje; } public static bool IntervalosFechasCoincidentes(DateTime FechaInicio1, DateTime FechaFin1, DateTime FechaInicio2, DateTime FechaFin2) { return FechaInicio1 <= FechaInicio2 & FechaInicio2 < FechaFin1 || FechaInicio2 <= FechaInicio1 & FechaFin2 > FechaInicio1; } public static bool IntervalosFechasCoincidentes(DateOnly FechaInicio1, DateOnly FechaFin1, DateOnly FechaInicio2, DateOnly FechaFin2) { return FechaInicio1 <= FechaInicio2 & FechaInicio2 < FechaFin1 || FechaInicio2 <= FechaInicio1 & FechaFin2 > FechaInicio1; } public static void CreaEstructuraDirectorio(string Ruta) { string[] sDirectorios = Ruta.Split(@"\"); string sDirectorio = ""; int i; var loopTo = sDirectorios.Length - 1; for (i = 0; i <= loopTo; i++) { try { sDirectorio += sDirectorios[i] + @"\"; if (!Directory.Exists(sDirectorio)) Directory.CreateDirectory(sDirectorio); } catch (Exception ex) { } } } public static object DeserializarSinErrores(string cadena, Type tipo) { return deserializar(cadena, tipo, true); } public static object deserializar(string cadena, Type tipo, bool SinErrores = true) { var xs = new XmlSerializer(tipo); if (SinErrores) { xs.UnknownElement += ElementoDesconocido; xs.UnknownNode += NodoDesconocido; xs.UnknownAttribute += AtributoDesconocido; xs.UnreferencedObject += ObjetoNoReferenciado; } var sr = new StringReader(cadena); var xr = new XmlTextReader(sr); var obj = xs.Deserialize(xr); xr.Close(); sr.Close(); return obj; } private static void ObjetoNoReferenciado(object sender, UnreferencedObjectEventArgs e) { } private static void AtributoDesconocido(object sender, XmlAttributeEventArgs e) { } private static void NodoDesconocido(object sender, XmlNodeEventArgs e) { } private static void ElementoDesconocido(object sender, XmlElementEventArgs e) { } public static object Deserializa(byte[] BA, Type tipo) { var xs = new XmlSerializer(tipo); // Dim fs As New FileStream(Fichero, FileMode.Open, FileAccess.Read) var ms = new MemoryStream(BA); var obj = xs.Deserialize(ms); // .Close() return obj; } public static object DeserializaFichero(string Fichero, Type tipo) { var xs = new XmlSerializer(tipo); var fs = new FileStream(Fichero, FileMode.Open, FileAccess.Read); var obj = xs.Deserialize(fs); fs.Close(); return obj; } public static string serializar(object obj) { var se = new XmlSerializer(obj.GetType()); var sw = new StringWriter(); se.Serialize(sw, obj); return sw.ToString(); } public static void serializar(object obj, string FicheroDestino) { var se = new XmlSerializer(obj.GetType()); if (File.Exists(FicheroDestino)) File.Delete(FicheroDestino); var fs = new FileStream(FicheroDestino, FileMode.CreateNew); se.Serialize(fs, obj); fs.Close(); } public static string serializarsindeclaracion(object obj) { var ms = new MemoryStream(); var settings = new XmlWriterSettings(); var utf8 = new UTF8Encoding(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.Encoding = utf8; var xw = XmlWriter.Create(ms, settings); var ns = new XmlSerializerNamespaces(); ns.Add("", ""); var se = new XmlSerializer(obj.GetType()); se.Serialize(xw, obj, ns); return utf8.GetString(ms.ToArray()); } public static void ByteArrayAFichero(byte[] Datos, string NombreFichero, bool Sobreescribir = false) { if (!Directory.Exists(Path.GetDirectoryName(NombreFichero))) CreaEstructuraDirectorio(Path.GetDirectoryName(NombreFichero)); if (File.Exists(NombreFichero) & Sobreescribir) File.Delete(NombreFichero); FileStream oFileStream; oFileStream = new FileStream(NombreFichero, FileMode.Create); oFileStream.Write(Datos, 0, Datos.Length); oFileStream.Close(); } public static object deserializar(string cadena, Type tipo) { var xs = new XmlSerializer(tipo); var sr = new StringReader(cadena); var xr = new XmlTextReader(sr); var obj = xs.Deserialize(xr); xr.Close(); sr.Close(); return obj; } public static string ObtieneFicheroNoExistente(string DirectorioInicial, string Nombre, string Extension) { if (!Directory.Exists(DirectorioInicial)) Directory.CreateDirectory(DirectorioInicial); string sFichero = DirectorioInicial + Nombre + "." + Extension; int i = 0; while (File.Exists(sFichero)) { i += 1; sFichero = DirectorioInicial + Nombre + "_" + i.ToString() + "." + Extension; } return sFichero; } public static string ObtieneFicheroAleatorio(string DirectorioInicial, string Extension) { if (!Directory.Exists(DirectorioInicial)) Directory.CreateDirectory(DirectorioInicial); string sFichero = DirectorioInicial + Path.GetRandomFileName() + "." + Extension; while (File.Exists(sFichero)) // Try // IO.File.Delete(sFichero) // Catch ex As Exception // End Try sFichero = DirectorioInicial + Path.GetRandomFileName() + "." + Extension; return sFichero; } public static string ObtieneFicheroAleatorio(string Extension) { string sFichero = Path.GetTempPath() + Path.GetRandomFileName() + "." + Extension; while (File.Exists(sFichero)) // Try // IO.File.Delete(sFichero) // Catch ex As Exception // End Try sFichero = Path.GetTempPath() + @"\" + Path.GetRandomFileName() + "." + Extension; return sFichero; } public static string ObtieneDirectorioAleatorio() { string sDir = Path.GetTempPath() + Path.GetRandomFileName(); while (Directory.Exists(sDir)) sDir = Path.GetTempPath() + @"\" + Path.GetRandomFileName(); Directory.CreateDirectory(sDir); return sDir; } public static string ObtieneDirectorioAleatorio(string Subdirectorio) { if (!Directory.Exists(Path.GetTempPath() + @"\" + Subdirectorio + @"\")) Directory.CreateDirectory(Path.GetTempPath() + @"\" + Subdirectorio + @"\"); string sDir = Path.GetTempPath() + @"\" + Subdirectorio + @"\" + Path.GetRandomFileName(); while (Directory.Exists(sDir) | File.Exists(sDir)) sDir = Path.GetTempPath() + @"\" + Path.GetRandomFileName(); Directory.CreateDirectory(sDir); return sDir; } public static int ObtieneNumeroFicheros(string Directory) { int FileCount = 0; string[] SubDirectory; int i; FileCount = System.IO.Directory.GetFiles(Directory).Length; SubDirectory = System.IO.Directory.GetDirectories(Directory); var loopTo = SubDirectory.Length - 1; for (i = 0; i <= loopTo; i++) FileCount = ObtieneNumeroFicheros(SubDirectory[i]) + FileCount; return FileCount; } public static void ObtieneFicherosRecursivo(string Ruta, ref string[] Ficheros) { string[] sFicheros = Directory.GetFiles(Ruta); var iNumeroFicheros = default(int); if (!(Ficheros == null)) iNumeroFicheros = Ficheros.Length; Array.Resize(ref Ficheros, sFicheros.Length - 1 + iNumeroFicheros + 1); sFicheros.CopyTo(Ficheros, iNumeroFicheros); string[] sDirectorios; sDirectorios = Directory.GetDirectories(Ruta); foreach (var sDirectorio in sDirectorios) ObtieneFicherosRecursivo(sDirectorio, ref Ficheros); } public static string FechaEnCastellano(DateTime Fecha, FormatoFechasEnum Formato) { string FechaEnCastellanoRet = default; var sMeses = new string[12]; sMeses[0] = "Enero"; sMeses[1] = "Febrero"; sMeses[2] = "Marzo"; sMeses[3] = "Abril"; sMeses[4] = "Mayo"; sMeses[5] = "Junio"; sMeses[6] = "Julio"; sMeses[7] = "Agosto"; sMeses[8] = "Septiembre"; sMeses[9] = "Octubre"; sMeses[10] = "Noviembre"; sMeses[11] = "Diciembre"; string sDia; string sMes; string sAño; sDia = Fecha.Day.ToString(); sMes = sMeses[Fecha.Month - 1]; sAño = Fecha.Year.ToString(); switch (Formato) { case FormatoFechasEnum.FECHA_ESPACIADO_GRANDE: { FechaEnCastellanoRet = sDia + " de " + sMes + " de " + sAño; break; } case FormatoFechasEnum.FECHA_HORA: { FechaEnCastellanoRet = Fecha.Day.ToString().PadLeft(2, '0') + "/" + Fecha.Month.ToString().PadLeft(2, '0') + "/" + Fecha.Year.ToString() + " " + Fecha.Hour.ToString().PadLeft(2, '0') + ":" + Fecha.Minute.ToString().PadLeft(2, '0') + ":" + Fecha.Second.ToString().PadLeft(2, '0'); break; } case FormatoFechasEnum.FECHA_ESPACIADO_PEQUEÑO: { FechaEnCastellanoRet = sDia + " de " + sMes + " de " + sAño; break; } case FormatoFechasEnum.FECHA_SEPARADO_POR_BARRAS: { FechaEnCastellanoRet = Fecha.Day.ToString().PadLeft(2, '0') + "/" + Fecha.Month.ToString().PadLeft(2, '0') + "/" + Fecha.Year.ToString(); break; } default: { throw new Exception("Formato no reconocido"); } } return FechaEnCastellanoRet; } public static string MesCastellano(int Mes) { var sMeses = new string[12]; sMeses[0] = "Enero"; sMeses[1] = "Febrero"; sMeses[2] = "Marzo"; sMeses[3] = "Abril"; sMeses[4] = "Mayo"; sMeses[5] = "Junio"; sMeses[6] = "Julio"; sMeses[7] = "Agosto"; sMeses[8] = "Septiembre"; sMeses[9] = "Octubre"; sMeses[10] = "Noviembre"; sMeses[11] = "Diciembre"; return sMeses[Mes - 1]; } public static string ObtenerRutaDelEnsamblado() { return Path.GetDirectoryName(Path.GetFullPath(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).AbsolutePath)); } public class MesType { public int NumeroMes { get; set; } public string Mes { get; set; } } public static List Meses() { var listadoMeses = new List(); MesType m; m = new MesType(); m.NumeroMes = 1; m.Mes = "Enero"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 2; m.Mes = "Febrero"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 3; m.Mes = "Marzo"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 4; m.Mes = "Abril"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 5; m.Mes = "Mayo"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 6; m.Mes = "Junio"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 7; m.Mes = "Julio"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 8; m.Mes = "Agosto"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 9; m.Mes = "Septiembre"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 10; m.Mes = "Octubre"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 11; m.Mes = "Noviembre"; listadoMeses.Add(m); m = new MesType(); m.NumeroMes = 12; m.Mes = "Diciembre"; listadoMeses.Add(m); return listadoMeses; } public static string CalculoLetraCif(string DNI) { // Dim sResultado As String = "", iTamanoDNI As Integer, sLetrasNif As String, i As Integer, Cdd0 As Integer, V1 As String = "" string sResultado = ""; int iTamanoDNI; string sLetrasNif; int i; string V1 = ""; sLetrasNif = "TRWAGMYFPDXBNJZSQVHLCKE"; iTamanoDNI = Strings.Len(DNI); if (iTamanoDNI == 0 | iTamanoDNI > 10) return DNI; DNI = DNI.ToUpper(); var loopTo = iTamanoDNI; for (i = 1; i <= loopTo; i++) { if (Strings.Asc(Strings.Mid(DNI, i, 1)) >= 48 & Strings.Asc(Strings.Mid(DNI, i, 1)) <= 57 | Strings.Asc(Strings.Mid(DNI, i, 1)) >= 65 & Strings.Asc(Strings.Mid(DNI, i, 1)) <= 90) sResultado = sResultado + Strings.Mid(DNI, i, 1); } iTamanoDNI = Strings.Len(sResultado); if (iTamanoDNI == 0) { return sResultado; } if (Strings.Asc(Strings.Mid(sResultado, 1, 1)) < 48 | Strings.Asc(Strings.Mid(sResultado, 1, 1)) > 57 | Strings.Asc(Strings.Mid(sResultado, iTamanoDNI, 1)) < 48 | Strings.Asc(Strings.Mid(sResultado, iTamanoDNI, 1)) > 57) { return sResultado; } // Cdd0 = 0 var loopTo1 = iTamanoDNI; for (i = 1; i <= loopTo1; i++) { // If Cdd0 Or (Asc(Mid(sResultado, i, 1)) <> 48) Then if (Strings.Asc(Strings.Mid(sResultado, i, 1)) >= 48 & Strings.Asc(Strings.Mid(sResultado, i, 1)) <= 57) V1 = V1 + Strings.Mid(sResultado, i, 1); // Cdd0 = 1 // End If } if (string.IsNullOrEmpty(Strings.Trim(V1))) return V1; if (V1.Length < 9) V1 = V1.PadLeft(8, '0'); return V1 + Strings.Mid(sLetrasNif, (int)Math.Round(Conversion.Val(V1) % 23d + 1d), 1); } public static bool ValidateNif(ref string nif) { // ******************************************************************* // Nombre: ValidateNif // por Enrique Martínez Montejo // // Finalidad: Validar el NIF/NIE pasado a la función. // // Entradas: // NIF: String. El NIF/NIE que se desea verificar. El número // será devuelto formateado y con el NIF/NIE correcto. // Resultados: // Boolean: True/False // // ******************************************************************* nif = nif.Trim(); string nifTemp = nif.Trim().ToUpper(); if (nifTemp.Length > 9) return false; // Guardamos el dígito de control. char dcTemp = nifTemp[nif.Length - 1]; // Compruebo si el dígito de control es un número. if (char.IsDigit(dcTemp)) return default; // Nos quedamos con los caracteres, sin el dígito de control. nifTemp = nifTemp.Substring(0, nif.Length - 1); if (nifTemp.Length < 8) { string paddingChar = new string('0', 8 - nifTemp.Length); nifTemp = nifTemp.Insert(nifTemp.Length, paddingChar); } // Obtengo el dígito de control correspondiente, utilizando // para ello una llamada a la función GetDcNif. // char dc = GetDcNif(nif); if (dc != default) { nif = nifTemp + dc; } return dc == dcTemp; } public static char GetDcNif(string nif) { // ******************************************************************* // Nombre: GetDcNif // por Enrique Martínez Montejo // // Finalidad: Devuelve la letra correspondiente al NIF o al NIE // (Número de Identificación de Extranjero) // // Entradas: // NIF: String. La cadena del NIF cuya letra final se desea // obtener. // // Resultados: // String: La letra del NIF/NIE. // // ******************************************************************* // Pasamos el NIF a mayúscula a la vez que eliminamos los // espacios en blanco al comienzo y al final de la cadena. // nif = nif.Trim().ToUpper(); // El NIF está formado de uno a nueve números seguido de una letra. // // El NIF de otros colectivos de personas físicas, está // formato por una letra (K, L, M), seguido de 7 números // y de una letra final. // // El NIE está formado de una letra inicial (X, Y, Z), // seguido de 7 números y de una letra final. // // En el patrón de la expresión regular, defino cuatro grupos en el // siguiente orden: // // 1º) 1 a 8 dígitos. // 2º) 1 a 8 dígitos + 1 letra. // 3º) 1 letra + 1 a 7 dígitos. // 4º) 1 letra + 1 a 7 dígitos + 1 letra. // try { var re = new Regex(@"(^\d{1,8}$)|(^\d{1,8}[A-Z]$)|(^[K-MX-Z]\d{1,7}$)|(^[K-MX-Z]\d{1,7}[A-Z]$)", RegexOptions.IgnoreCase); if (!re.IsMatch(nif)) return default; // Nos quedamos únicamente con los números del NIF, y // los formateamos con ceros a la izquierda si su // longitud es inferior a siete caracteres. // re = new Regex(@"(\d{1,8})"); string numeros = re.Match(nif).Value.PadLeft(7, '0'); // Primer carácter del NIF. // char firstChar = nif[0]; // Si procede, reemplazamos la letra del NIE por el peso que le corresponde. // if (firstChar == 'X') { numeros = "0" + numeros; } else if (firstChar == 'Y') { numeros = "1" + numeros; } else if (firstChar == 'Z') { numeros = "2" + numeros; } // Tabla del NIF // // 0T 1R 2W 3A 4G 5M 6Y 7F 8P 9D // 10X 11B 12N 13J 14Z 15S 16Q 17V 18H 19L // 20C 21K 22E 23T // // Procedo a calcular el NIF/NIE // int dni = Conversions.ToInteger(numeros); // La operación consiste en calcular el resto de dividir el DNI // entre 23 (sin decimales). Dicho resto (que estará entre 0 y 22), // se busca en la tabla y nos da la letra del NIF. // // Obtenemos el resto de la división. // int r = dni % 23; // Obtenemos el dígito de control del NIF // char dc = Conversions.ToChar("TRWAGMYFPDXBNJZSQVHLCKE".Substring(r, 1)); return dc; } catch { // Cualquier excepción producida, devolverá el valor Nothing. // return default; } } public static char RecalculaNIF(string nif) { // ******************************************************************* // Nombre: GetDcNif // por Enrique Martínez Montejo // // Finalidad: Devuelve la letra correspondiente al NIF o al NIE // (Número de Identificación de Extranjero) // // Entradas: // NIF: String. La cadena del NIF cuya letra final se desea // obtener. // // Resultados: // String: La letra del NIF/NIE. // // ******************************************************************* // Pasamos el NIF a mayúscula a la vez que eliminamos los // espacios en blanco al comienzo y al final de la cadena. // nif = nif.Trim().ToUpper(); // El NIF está formado de uno a nueve números seguido de una letra. // // El NIF de otros colectivos de personas físicas, está // formato por una letra (K, L, M), seguido de 7 números // y de una letra final. // // El NIE está formado de una letra inicial (X, Y, Z), // seguido de 7 números y de una letra final. // // En el patrón de la expresión regular, defino cuatro grupos en el // siguiente orden: // // 1º) 1 a 8 dígitos. // 2º) 1 a 8 dígitos + 1 letra. // 3º) 1 letra + 1 a 7 dígitos. // 4º) 1 letra + 1 a 7 dígitos + 1 letra. // try { var re = new Regex(@"(^\d{1,8}$)|(^\d{1,8}[A-Z]$)|(^[K-MX-Z]\d{1,7}$)|(^[K-MX-Z]\d{1,7}[A-Z]$)", RegexOptions.IgnoreCase); if (!re.IsMatch(nif)) return default; // Nos quedamos únicamente con los números del NIF, y // los formateamos con ceros a la izquierda si su // longitud es inferior a siete caracteres. // re = new Regex(@"(\d{1,8})"); string numeros = re.Match(nif).Value.PadLeft(7, '0'); // Primer carácter del NIF. // char firstChar = nif[0]; // Si procede, reemplazamos la letra del NIE por el peso que le corresponde. // if (firstChar == 'X') { numeros = "0" + numeros; } else if (firstChar == 'Y') { numeros = "1" + numeros; } else if (firstChar == 'Z') { numeros = "2" + numeros; } // Tabla del NIF // // 0T 1R 2W 3A 4G 5M 6Y 7F 8P 9D // 10X 11B 12N 13J 14Z 15S 16Q 17V 18H 19L // 20C 21K 22E 23T // // Procedo a calcular el NIF/NIE // int dni = Conversions.ToInteger(numeros); // La operación consiste en calcular el resto de dividir el DNI // entre 23 (sin decimales). Dicho resto (que estará entre 0 y 22), // se busca en la tabla y nos da la letra del NIF. // // Obtenemos el resto de la división. // int r = dni % 23; // Obtenemos el dígito de control del NIF // char dc = Conversions.ToChar("TRWAGMYFPDXBNJZSQVHLCKE".Substring(r, 1)); string NifCorregido = numeros + dc; return Conversions.ToChar(NifCorregido); } catch { // Cualquier excepción producida, devolverá el valor Nothing. // return default; } } public static object ConvertirTiempoUnixADateTime(long tiempoUnix) { var fecha = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); Debug.WriteLine(fecha.AddSeconds(tiempoUnix).ToLocalTime().ToString()); Debug.WriteLine(fecha.AddSeconds(tiempoUnix).ToLocalTime().ToUniversalTime()); return fecha.AddSeconds(tiempoUnix).ToUniversalTime(); } public static S UpCast(B baseObj) where S : B, new() { var superObj = new S(); System.Reflection.PropertyInfo superProp = null; foreach (System.Reflection.PropertyInfo baseProp in baseObj.GetType().GetProperties()) { superProp = superObj.GetType().GetProperty(baseProp.Name); superProp.SetValue(superObj, baseProp.GetValue(baseObj, (object[])null), (object[])null); } return superObj; } public static string StringToHex(string text) { string shex = ""; for (int i = 0, loopTo = text.Length - 1; i <= loopTo; i++) shex += Strings.Asc(text.Substring(i, 1)).ToString("x").ToUpper(); return shex; } public static string HexToString(string hex) { var text = new StringBuilder(hex.Length / 2); for (int i = 0, loopTo = hex.Length - 2; i <= loopTo; i += 2) text.Append(Strings.Chr(Convert.ToByte(hex.Substring(i, 2), 16))); return text.ToString(); } public static byte[] HexToArray(string hex) { byte[] raw = new byte[(int)Math.Round(hex.Length / 2d - 1d + 1)]; int i; var loopTo = raw.Length - 1; for (i = 0; i <= loopTo; i++) raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 0x10); return raw; } public static int GetUnixTimestamp() { return GetUnixTime(DateTime.UtcNow); } public static int GetUnixTime(DateTime dt) { var span = dt - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); return (int)Math.Round(span.TotalSeconds); } public static string ByteArrayToHex(byte[] bytes_Input) { var strTemp = new StringBuilder(bytes_Input.Length * 2); foreach (byte b in bytes_Input) strTemp.Append(Conversion.Hex(b).PadLeft(2, '0')); return strTemp.ToString(); } [DebuggerStepThrough()] public static string ExtraeValorCadena(string Cadena, string VariableBuscada, string Separador = ",", string SeparadorIgualdad = "=") { try { string[] valores = Cadena.Split(Separador); string ValorBuscado = valores.FirstOrDefault(x => (x.Split(SeparadorIgualdad)[0].Trim().ToLower() ?? "") == (VariableBuscada.ToLower() ?? "")); if (ValorBuscado is not null) { return ValorBuscado.Split(SeparadorIgualdad)[1].Trim(); } else { return ""; } } catch (Exception ex) { return ""; } } [DebuggerStepThrough()] public static string Ttagi(string sValortag, string sToken) { string TtagiRet = default; TtagiRet = ""; try { sValortag = "|" + sValortag + "|"; if (Strings.InStr(1, "|" + sValortag + "|", "|" + sToken + "=", Constants.vbTextCompare) > 0) { TtagiRet = Strings.Mid(sValortag, Strings.InStr(1, sValortag, "|" + sToken + "=") + Strings.Len(sToken) + 2, Strings.InStr(1, Strings.Mid(sValortag, Strings.InStr(1, sValortag, "|" + sToken + "=") + Strings.Len(sToken) + 2), "|") - 1); } } catch (Exception ex) { throw new Exception(ex.Message, ex); } return TtagiRet; } public static Type FindType(string name) { Type @base; @base = System.Reflection.Assembly.GetEntryAssembly().GetType(name, false, true); if (@base is not null) return @base; @base = System.Reflection.Assembly.GetExecutingAssembly().GetType(name, false, true); if (@base is not null) return @base; foreach (System.Reflection.Assembly @assembly in AppDomain.CurrentDomain.GetAssemblies()) { @base = assembly.GetType(name, false, true); if (@base is not null) return @base; } throw new Exception("Clase no encontrada"); } public static DateTime StringAFechaHora(string Fecha) { string[] sValores = Fecha.Split("_"); DateTime dFecha; dFecha = new DateTime(Conversions.ToInteger(sValores[0]), Conversions.ToInteger(sValores[1]), Conversions.ToInteger(sValores[2]), Conversions.ToInteger(sValores[3]), Conversions.ToInteger(sValores[4]), Conversions.ToInteger(sValores[5])); return dFecha; } public static string EnviarNotificacionSlack(string mensaje, string otroTexto = "", string destinatario = "", string descripcionRemitente = "") { string resultado = ""; try { // // Escapar las cadenas para compatibilizaras con JSON. mensaje = System.Web.HttpUtility.JavaScriptStringEncode(mensaje); otroTexto = System.Web.HttpUtility.JavaScriptStringEncode(otroTexto); destinatario = System.Web.HttpUtility.JavaScriptStringEncode(destinatario); descripcionRemitente = System.Web.HttpUtility.JavaScriptStringEncode(descripcionRemitente); string mensajeJSON = ""; if (string.IsNullOrWhiteSpace(destinatario)) { destinatario = "#sevilla"; } if (Environment.MachineName.ToUpper() == "INTI") { destinatario = "@danmun"; } if (string.IsNullOrWhiteSpace(descripcionRemitente)) { // descripcionRemitente = String.Format(".NET {0}@{1}, {2}", Environment.UserName, Environment.MachineName, Environment.OSVersion) descripcionRemitente = string.Format(".NET {0}@{1}", Environment.UserName, Environment.MachineName); } if (string.IsNullOrWhiteSpace(otroTexto)) { mensajeJSON = string.Format("{{\"channel\": \"{0}\", \"username\": \"notificaciones\", \"text\": \"*{1}* — {2}\"}}", destinatario.Trim(), descripcionRemitente.Trim(), mensaje.Trim()); } else { mensajeJSON = string.Format("{{\"channel\": \"{0}\", \"username\": \"notificaciones\", \"text\": \"*{1}* — {2} — _{3}_\"}}", destinatario.Trim(), descripcionRemitente.Trim(), mensaje.Trim(), otroTexto.Trim()); } using (var client = new WebClient()) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; byte[] response = client.UploadValues("https://hooks.slack.com/services/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", new System.Collections.Specialized.NameValueCollection() { { "payload", mensajeJSON } }); resultado = Encoding.UTF8.GetString(response); Console.WriteLine(resultado); } } catch (Exception ex) { // Nada. No quiero que esto ocasiones problemas allá donde sea utilizado. } return resultado; } private static bool AcceptAllCertifications(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } public static string GenerarCsvDesdeDataTable(DataTable dt, char separador = ';') { var sb = new StringBuilder(); for (int i = 0, loopTo = dt.Columns.Count - 1; i <= loopTo; i++) { sb.Append("\"" + dt.Columns[i].ToString() + "\""); if (i < dt.Columns.Count - 1) { sb.Append(separador); } } sb.AppendLine(); foreach (DataRow dr in dt.Rows) { for (int i = 0, loopTo1 = dt.Columns.Count - 1; i <= loopTo1; i++) { sb.Append("\"" + dr[i].ToString() + "\""); if (i < dt.Columns.Count - 1) { sb.Append(separador); } } sb.AppendLine(); } return sb.ToString(); } public static int? ObtenerValorDesdeNombre(string nombre) where TEnum : struct { TEnum resultado; if (Enum.TryParse(nombre, true, out resultado)) { return Convert.ToInt32(resultado); } return default; // Devuelve Nothing si no hay coincidencia } } public class DescripcionValor { public string Descripcion { get; set; } public int Valor { get; set; } public static List EnumADescripcionValor(Type Enumeracion) { var values = Enum.GetValues(Enumeracion); var underlyingType = Enum.GetUnderlyingType(Enumeracion); // Dim arr As Array = Array.CreateInstance(underlyingType, values.Length) var lista = new List(); for (int i = 0, loopTo = values.Length - 1; i <= loopTo; i++) { var dv = new DescripcionValor(); dv.Valor = Conversions.ToInteger(values.GetValue(i)); dv.Descripcion = values(i).ToString().Replace("_", " "); lista.Add(dv); } return lista; } public static List EnumADescripcionValorAmpliado(Type Enumeracion) { var values = Enum.GetValues(Enumeracion); var underlyingType = Enum.GetUnderlyingType(Enumeracion); // Dim arr As Array = Array.CreateInstance(underlyingType, values.Length) var lista = new List(); for (int i = 0, loopTo = values.Length - 1; i <= loopTo; i++) { var dv = new DescripcionValor(); dv.Valor = Conversions.ToInteger(values.GetValue(i)); dv.Descripcion = values(i).ToString().Replace("_", " ") + " (" + dv.Valor.ToString() + ")"; lista.Add(dv); } return lista; } } }