elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


  Mostrar Mensajes
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... 1232
101  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 27 Febrero 2024, 13:38 pm
Los dos siguientes métodos sirven para truncar nombres de archivos que superen los 255 caracteres (incluyendo la longitud de la extensión del archivo), acortando la longitud cuanto sea necesario para no sobrepasar dicho límite, y añadiendo puntos suspensivos (…) al final del nombre del archivo.

Eso es lo que hace con los nombres de archivo (file name), no con las rutas (file path).

En caso de enviar como parámetro a cualquiera de estos dos métodos una ruta de archivo (file path), aparte de realizar los ajustes mencionados con el nombre del archivo y, en caso de que la ruta exceda el límite máximo permitido de 260 caracteres (definido en MAX_PATH), se añadirá el prefijo "\\?\" a la ruta para garantizar la compatibilidad de uso con sistemas NTFS que tengan habilitado el soporte para rutas de longitud extendida (es decir, mayores de 260 caracteres).

De esta forma, y además de prevenir el uso de nombres de archivo (file names) inválidos / demasiado largos, además se garantiza que la aplicación que utilice estos métodos para la manipulación o creación de archivos sea "LONG PATH AWARE".

Nota: Los métodos han pasado pruebas usando rutas locales (relativas y absolutas). No han sido probados con rutas UNC ni adaptados para ello.

Leer con detenimiento el bloque de documentación XML para más información.

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' If needed, truncates the length of the specified file name or full file path  
  4. ''' to comply with Windows OS maximum file name length of 255 characters
  5. ''' (including the file extension length).
  6. ''' <para></para>
  7. ''' If the file name exceeds this limit, it truncates it and
  8. ''' adds a ellipsis (…) at the end of the file name.
  9. ''' <para></para>
  10. ''' If the path exceeds the MAX_PATH limit (260 characters),
  11. ''' it adds the "\\?\" prefix to support extended-length paths.
  12. ''' <para></para>
  13. ''' See also: <see href="https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation"/>
  14. ''' </summary>
  15. ''' ----------------------------------------------------------------------------------------------------
  16. ''' <remarks>
  17. ''' This method is particularly useful when dealing with file names or file paths that might exceed
  18. ''' the maximum allowed length, preventing potential errors related to file name length limitations
  19. ''' when creating files in the drive.
  20. ''' </remarks>
  21. ''' ----------------------------------------------------------------------------------------------------
  22. ''' <param name="filePath">
  23. ''' The file name or full file path.
  24. ''' </param>
  25. '''
  26. ''' <param name="maxFileNameLength">
  27. ''' Optional. The maximum character length that the file name can have.
  28. ''' Default (and maximum) value is 255.
  29. ''' </param>
  30. ''' ----------------------------------------------------------------------------------------------------
  31. ''' <returns>
  32. ''' The truncated file name or full file path.
  33. ''' </returns>
  34. ''' ----------------------------------------------------------------------------------------------------
  35. <DebuggerStepThrough>
  36. Public Shared Function TruncateLongFilePath(filePath As String, Optional maxFileNameLength As Byte = 255) As String
  37.  
  38.    If String.IsNullOrEmpty(filePath) Then
  39.        Throw New ArgumentNullException(paramName:=NameOf(filePath))
  40.    End If
  41.  
  42.    If filePath.StartsWith("\\?\", StringComparison.Ordinal) Then
  43.        filePath = filePath.Substring(4)
  44.    End If
  45.  
  46.    Dim fileInfo As New FileInfo(If(filePath.Length <= 255, filePath, $"\\?\{filePath}"))
  47.    TruncateLongFilePath(fileInfo, maxFileNameLength)
  48.    Return fileInfo.FullName
  49.  
  50. End Function
  51.  
  52. ''' ----------------------------------------------------------------------------------------------------
  53. ''' <summary>
  54. ''' If needed, truncates the length of the file name in
  55. ''' the source <see cref="FileInfo"/> object to comply with
  56. ''' Windows OS maximum file name length of 255 characters
  57. ''' (including the file extension length).
  58. ''' <para></para>
  59. ''' If the file name exceeds this limit, it truncates it and
  60. ''' adds a ellipsis (…) at the end of the file name.
  61. ''' <para></para>
  62. ''' If the path exceeds the MAX_PATH limit (260 characters),
  63. ''' it adds the "\\?\" prefix to support extended-length paths.
  64. ''' <para></para>
  65. ''' See also: <see href="https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation"/>
  66. ''' </summary>
  67. ''' ----------------------------------------------------------------------------------------------------
  68. ''' <remarks>
  69. ''' This method is particularly useful when dealing with file paths that might exceed
  70. ''' the maximum allowed length, preventing potential errors related to file name length limitations
  71. ''' when creating files in the drive.
  72. ''' </remarks>
  73. ''' ----------------------------------------------------------------------------------------------------
  74. ''' <param name="refFileInfo">
  75. ''' The source <see cref="FileInfo"/> object representing a full file path.
  76. ''' <para></para>
  77. ''' When this method returns, this object contains the file path with the file name truncated.
  78. ''' </param>
  79. '''
  80. ''' <param name="maxFileNameLength">
  81. ''' Optional. The maximum character length that the file name can have.
  82. ''' Default (and maximum) value is 255.
  83. ''' </param>
  84. ''' ----------------------------------------------------------------------------------------------------
  85. <DebuggerStepThrough>
  86. Public Shared Sub TruncateLongFilePath(ByRef refFileInfo As FileInfo, Optional maxFileNameLength As Byte = 255)
  87.  
  88.    If refFileInfo Is Nothing Then
  89.        Throw New ArgumentNullException(paramName:=NameOf(refFileInfo))
  90.    End If
  91.  
  92.    If maxFileNameLength = 0 Then
  93.        Throw New ArgumentException("Value must be greater than zero.", paramName:=NameOf(maxFileNameLength))
  94.    End If
  95.  
  96.    If refFileInfo.Name.Length >= maxFileNameLength Then
  97.        Dim fileExt As String = refFileInfo.Extension
  98.        Dim fileName As String = refFileInfo.Name.Substring(0, maxFileNameLength - 1 - fileExt.Length) & $"…{fileExt}"
  99.  
  100.        Dim directoryName As String = Path.GetDirectoryName(refFileInfo.FullName)
  101.        If directoryName.Equals("\\?", StringComparison.Ordinal) Then
  102.            refFileInfo = New FileInfo($"\\?\{fileName}")
  103.  
  104.        ElseIf directoryName.StartsWith("\\?\", StringComparison.Ordinal) Then
  105.            refFileInfo = New FileInfo(Path.Combine(refFileInfo.DirectoryName, fileName))
  106.  
  107.        Else
  108.            Dim fullpath As String = Path.Combine(refFileInfo.DirectoryName, fileName)
  109.            refFileInfo = If(fullpath.Length >= 260, ' MAX_PATH
  110.                          New FileInfo($"\\?\{fullpath}"),
  111.                          New FileInfo(fullpath))
  112.        End If
  113.    End If
  114.  
  115. End Sub
102  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 27 Febrero 2024, 13:19 pm
Convertir un objeto Datatable a una tabla en formato Markdown:

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Converts the elements of a <see cref="DataTable"/> into a Markdown table.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <example> This is a code example that shows how to convert a DataTable object to Markdown table.
  7. ''' <code language="VB.NET">
  8. ''' Dim dt As New DataTable()
  9. ''' dt.Columns.Add("ID", GetType(Integer))
  10. ''' dt.Columns.Add("Name", GetType(String))
  11. ''' dt.Rows.Add(1, "John")
  12. ''' dt.Rows.Add(2, "Doe")
  13. '''
  14. ''' Dim markdownTable As String = EnumerableToMarkdownTable(dt)
  15. ''' Console.WriteLine(markdownTable.ToString())
  16. ''' </code>
  17. ''' </example>
  18. ''' ----------------------------------------------------------------------------------------------------
  19. ''' <param name="table">
  20. ''' The source <see cref="DataTable"/>.
  21. ''' </param>
  22. ''' ----------------------------------------------------------------------------------------------------
  23. ''' <returns>
  24. ''' A string representing the Markdown table.
  25. ''' </returns>
  26. ''' ----------------------------------------------------------------------------------------------------
  27. Public Shared Function DataTableToMarkdownTable(table As DataTable) As String
  28.  
  29.    If table Is Nothing Then
  30.        Throw New ArgumentNullException(paramName:=NameOf(table))
  31.    End If
  32.  
  33.    If table.Rows.Count = 0 Then
  34.        Throw New ArgumentNullException("The source table does not contain any row.", paramName:=NameOf(table))
  35.    End If
  36.  
  37.    Dim columnNames As IEnumerable(Of String) = table.Columns.Cast(Of DataColumn)().Select(Function(column) column.ColumnName)
  38.    Dim maxColumnValues As Integer() = columnNames.Select(Function(name) table.AsEnumerable().Max(Function(row) If(row.IsNull(name), 0, row(name).ToString().Length))).ToArray()
  39.  
  40.    Dim headerLine As String = "| " & String.Join(" | ", columnNames) & " |"
  41.    Dim headerDataDividerLine As String = "| " & String.Join(" | ", maxColumnValues.Select(Function(length) New String("-"c, length))) & " |"
  42.  
  43.    Dim lines As IEnumerable(Of String) = {headerLine, headerDataDividerLine}.Concat(
  44.        table.AsEnumerable().Select(
  45.            Function(row) "| " & String.Join(" | ", columnNames.Select(Function(name, i) If(row.IsNull(name), "".PadRight(maxColumnValues(i)), row(name).ToString().PadRight(maxColumnValues(i))))) & " |"
  46.        )
  47.    )
  48.  
  49.    Return String.Join(Environment.NewLine, lines)
  50.  
  51. End Function



Convertir un objeto IEnumerable a una tabla en formato Markdown:

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Converts the elements of an <see cref="IEnumerable(Of T)"/> into a Markdown table.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <remarks>
  7. ''' Original C# concept: <see href="https://github.com/jpierson/to-markdown-table/blob/develop/src/ToMarkdownTable/LinqMarkdownTableExtensions.cs"/>
  8. ''' </remarks>
  9. ''' ----------------------------------------------------------------------------------------------------
  10. ''' <example> This is a code example that shows how to convert a List(Of String) object to Markdown table.
  11. ''' <code language="VB.NET">
  12. ''' Dim list As New List(Of String)
  13. ''' list.Add("John")
  14. ''' list.Add("Doe")
  15. '''
  16. ''' Dim markdownTable As String = EnumerableToMarkdownTable(list)
  17. ''' Console.WriteLine(markdownTable.ToString())
  18. ''' </code>
  19. ''' </example>
  20. ''' ----------------------------------------------------------------------------------------------------
  21. ''' <example> This is a code example that shows how to convert a List of a custom type to Markdown table.
  22. ''' <code language="VB.NET">
  23. ''' Public Class TestClass
  24. '''     Public Property ID As Integer
  25. '''     Public Property Name As String
  26. '''     Public Property Age As Integer
  27. ''' End Class
  28. '''
  29. ''' Dim list As New List(Of TestClass) From {
  30. '''     New TestClass() With {.ID = 1, .Name = "John", .Age = 30},
  31. '''     New TestClass() With {.ID = 2, .Name = "Doe" , .Age = 40}
  32. ''' }
  33. '''
  34. ''' Dim markdownTable As String = EnumerableToMarkdownTable(list)
  35. ''' Console.WriteLine(markdownTable.ToString())
  36. ''' </code>
  37. ''' </example>
  38. ''' ----------------------------------------------------------------------------------------------------
  39. ''' <typeparam name="T">
  40. ''' The type of elements in the collection.
  41. ''' </typeparam>
  42. '''
  43. ''' <param name="source">
  44. ''' The generic collection to convert into a Markdown table.
  45. ''' </param>
  46. ''' ----------------------------------------------------------------------------------------------------
  47. ''' <returns>
  48. ''' A string representing the Markdown table.
  49. ''' </returns>
  50. ''' ----------------------------------------------------------------------------------------------------
  51. Public Shared Function EnumerableToMarkdownTable(Of T)(source As IEnumerable(Of T)) As String
  52.    If source Is Nothing OrElse Not source.Any() Then
  53.        Throw New ArgumentNullException(paramName:=NameOf(source))
  54.    End If
  55.  
  56.    If GetType(T).IsPrimitive OrElse GetType(T) = GetType(String) Then
  57.        Return $"| Items |{Environment.NewLine}| ----- |{Environment.NewLine}{String.Join(Environment.NewLine, source.Select(Function(s) $"| {s} |"))}"
  58.    End If
  59.  
  60.    Dim properties As PropertyInfo() = GetType(T).GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.GetProperty)
  61.    Dim fields As IEnumerable(Of FieldInfo) = GetType(T).GetRuntimeFields().Where(Function(f) f.IsPublic)
  62.  
  63.    Dim gettables As IEnumerable(Of MarkdownColumnData) =
  64.        Enumerable.Union(properties.Select(Function(p As PropertyInfo)
  65.                                               Return New MarkdownColumnData With {
  66.                                                   .Name = p.Name,
  67.                                                   .GetValue = Function(obj) p.GetValue(obj),
  68.                                                   .Type = p.PropertyType
  69.                                               }
  70.                                           End Function),
  71.                         fields.Select(Function(f As FieldInfo)
  72.                                           Return New MarkdownColumnData With {
  73.                                               .Name = f.Name,
  74.                                               .GetValue = Function(obj) f.GetValue(obj),
  75.                                               .Type = f.FieldType
  76.                                           }
  77.                                       End Function))
  78.  
  79.    Dim maxColumnValues As Integer() = source.
  80.            Select(Function(x) gettables.Select(Function(p) If(p.GetValue(x)?.ToString()?.Length, 0))).
  81.            Union({gettables.Select(Function(p) p.Name.Length)}).
  82.            Aggregate(
  83.                Enumerable.Repeat(0, gettables.Count()).AsEnumerable(),
  84.                Function(accumulate, x) accumulate.Zip(x, Function(a, b) System.Math.Max(a, b))).
  85.            ToArray()
  86.  
  87.    Dim columnNames As IEnumerable(Of String) =
  88.        gettables.Select(Function(p) p.Name)
  89.  
  90.    Dim headerLine As String =
  91.        "| " & String.Join(" | ", columnNames.Select(Function(n, i) n.PadRight(maxColumnValues(i)))) & " |"
  92.  
  93.    Dim isNumeric As Func(Of Type, Boolean) =
  94.        Function(type As Type)
  95.            Return type = GetType(Byte) OrElse type = GetType(SByte) OrElse type = GetType(UShort) OrElse type = GetType(UInteger) OrElse type = GetType(ULong) OrElse type = GetType(Short) OrElse type = GetType(Integer) OrElse type = GetType(Long) OrElse type = GetType(Decimal) OrElse type = GetType(Double) OrElse type = GetType(Single)
  96.        End Function
  97.  
  98.    Dim rightAlign As Func(Of Type, String) =
  99.        Function(type As Type)
  100.            Return If(isNumeric(type), ":", " "c)
  101.        End Function
  102.  
  103.    Dim headerDataDividerLine As String =
  104.            "| " &
  105.            String.Join("| ", gettables.Select(Function(g, i) New String("-"c, maxColumnValues(i)) & rightAlign(g.Type))) &
  106.            "|"
  107.  
  108.    Dim lines As IEnumerable(Of String) =
  109.        {
  110.            headerLine,
  111.            headerDataDividerLine
  112.        }.Union(source.
  113.            Select(Function(s)
  114.                       Return "| " & String.Join(" | ", gettables.Select(Function(n, i) If(n.GetValue(s)?.ToString(), "").PadRight(maxColumnValues(i)))) & " |"
  115.                   End Function))
  116.  
  117.    Return lines.Aggregate(Function(p, c) p & Environment.NewLine & c)
  118. End Function
103  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 27 Febrero 2024, 13:15 pm
Cifrar código fuente de Visual Basic Script (VBS):

 - https://foro.elhacker.net/programacion_visual_basic/cogravemo_puedo_cifrar_archivos_vbs-t409714.0.html;msg2277482#msg2277482
104  Foros Generales / Dudas Generales / Re: TFG Antropología en: 27 Febrero 2024, 06:20 am
Quiero presentarme. Soy Emilio, estudiante del Grado de Antropología en la UNED. Estoy haciendo el Trabajo de Fin de Grado sobre la Inteligencia Artificial en los foros de internet y me han pedido que entreviste a usuarios (será totalmente anónimo), para hacer una etnografía. Por favor, ¿alguien puede ayudarme? Sólo se trata de hacerles una serie de preguntas sobre sus motivaciones, sus resultados, problemas éticos y grado de satisfacción con la IA.

Si por entrevista entendemos ofrecer una lista con una serie de preguntas por mensaje privado, y que el entrevistado puede tomarse su tiempo de reflexión para responderlas por el mismo método utilizado del mensaje por privado, entonces me ofrezco voluntario. De hecho, y si ese fuese el tipo de entrevista, creo que sería buena idea publicar aquí las preguntas y solicitar que los usuarios interesados te envién un mensaje privado con sus respuestas.

Si por lo contrario hablamos de una entrevista con respuestas más inmediatas mediante un servicio de mensajeria, o mediante conversación telefónica, entonces no.

En cualquier caso, considero que tengo opiniones muy valiosas para contribuir al debate y el estudio sobre cuestiones relacionadas con la IA, en concreto sobre los modelos de lenguaje generativo como GPT y comenzando por sus (únicas y compartidas) inclinaciones políticas subyacentes derivadas de las decisiones empresariales por parte de sus desarrolladores, que solo sirven para la imposición de límites arbitrarios y absurdos, con una única visión e ideología (woke) del mundo que nos rodea, y con lo cual impide otorgarle una verdadera "libertad" de expresión a la IA, o al menos impide la capacidad de poder ofrecer respuestas que no estén limitadas por reglas ideológicas predefinidas e impuestas por sus propios creadores.

PD: No soy experto en el estudio ni el desarrollo de la IA, sino un consumidor de servicios basados en IA, como por ejemplo ChatGPT y Midjourney.

Aténtamente,
Elektro.
105  Programación / .NET (C#, VB.NET, ASP) / Re: Como puedo crear mi propio speech synthesizer?? en: 18 Noviembre 2021, 15:13 pm
Basicamente quieres crear un modelo de voz.

Esto no lo he leido en profundidad, pero parece que explica todos los pasos a seguir:

https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-custom-voice-prepare-data
https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-custom-voice-create-voice

Y al parecer necesitarías una cuenta de Microsoft Azure para poder utilizar la plataforma Speech Studio con el que crear el modelo de voz:
https://speech.microsoft.com/portal?projecttype=customvoice

https://docs.microsoft.com/en-us/dynamics-nav/how-to--sign-up-for-a-microsoft-azure-subscription

Saludos!
106  Programación / .NET (C#, VB.NET, ASP) / Re: Simular Teclado en: 18 Noviembre 2021, 15:05 pm
el codigo de arriba es 100% funcional , ya que funciona  a las mil maravillas luego de agregar parametros que me faltaban

espero este post sirva de aporte

Hombre, pero date cuenta que no puede servir de mucho ya que el código está incompleto.

Deduzco que está incompleto por que sobrepasaste el límite máximo de caracteres permitidos en un post del foro, un límite demasiado pequeño y del cual me he quejado varias veces en el pasado.

Un truco es eliminar lineas de comentario para reducir caracteres, obvio. O también lo podrías compartir en pastebin o servicios similares donde el límite de caracteres es mucho mayor. O en Github gist directamente.

Saludos!
107  Programación / .NET (C#, VB.NET, ASP) / Re: Juego del tonto(cartas) en: 18 Noviembre 2021, 15:00 pm
Yo quiero saber más sobre el "juego del tonto". En serio.

Los nuevos usuarios deben intentar comprender que este foro es multicultural, hay gente de España y de toda latinoamérica.

Te sugiero humildemente que la próxima vez intentes definir mejor las cosas a las que te refieres para asegurar que lo entiendan en el resto del mundo.

Saludos!
108  Programación / .NET (C#, VB.NET, ASP) / Re: C# Ejecutar archivo .bat en: 18 Noviembre 2021, 14:55 pm
Process.Start Method:
https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start?view=net-6.0
109  Programación / .NET (C#, VB.NET, ASP) / Re: Detener el programa, hacer otro proceso y cuando se termine retomar el programa y continuar en: 18 Noviembre 2021, 14:53 pm
También puedes registrar un atajo global de sistema (system-wide hotkey):

Ejemplos e información:
https://foro.elhacker.net/net_c_vbnet_asp/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg1911061#msg1911061

https://www.codeproject.com/Articles/1273010/Global-Hotkeys-within-Desktop-Applications
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey

Saludos!
110  Foros Generales / Foro Libre / Re: La busqueda en google no obtuvo ningún resultado,etc,etc,etc en: 18 Noviembre 2021, 13:05 pm
Me has convencido, ya me he cambiado de google a DuckDuckGo , se nota diferencia.

No digas eso, ¡que luego me podrían llamar manipulador!.

Si te convences que sea por tu propia experiencia personal. Yo solo he compartido y opinado sobre mi experiencia personal y mi percepción de la realidad.

Aunque lo cierto es que es innegable que Google oculta ciertos resultados, lo reconocieron publicamente no recuerdo cuando, pero no es algo que lo hagan de forma oculta. Se supone que en principio ocultan temas de conspiración anti-covid y cosas similares como fake news, creo que lo mismo hacen algunas redes sociales que también lo han reconocido abiertamente. Aunque claro yo desconozco en que parámetros e ideologías exactas se basarán para hacer esas ocultaciones de resultados los tipos de Google, pero temas sobre política también ocultan muchos resultados o tienes que pasar 5 páginas hasta encontrar algo relevante, yo me he dado cuenta de eso muchas veces... en los resultados de artículos donde se cuestione al comunismo, el socialismo y las dictaduras modernas como Cuba y china.

Yo también me alegro de verte por aquí. Estaré atento a tus publicaciones, crack.

Saludos!
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... 1232
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines