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


Tema destacado: Introducción a Git (Primera Parte)


  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 ... 1253
71  Programación / Scripting / [APORTE] [PowerShell] Crear un archivo dummy de forma fácil e interactiva en: 3 Marzo 2025, 09:36 am
El siguiente script, desarrollado de manera híbrida en PowerShell y VisualBasic.NET, permite crear de manera interactiva un archivo dummy (vacío o con contenido aleatorio) con un tamaño determinado.

La creación de un archivo dummy resulta útil para realizar pruebas de escritura en discos, o para sobrescribir el espacio en blanco del disco dificultando o imposibilitando la recuperación de datos, por ejemplo, generando un archivo dummy (con datos aleatorios) que ocupe todo el espacio disponible en el disco.

Al ejecutar este script, aparecerá el siguiente formulario que permitirá seleccionar la ubicación del archivo a crear y configurar las opciones disponibles:



Este es el procedimiento completo:



La interfaz gráfica y el resto del procedimiento está contenido en un script de PowerShell de 31 kilobytes, ideal para incluirlo como herramienta adicional en entornos de pruebas y recuperación, sin dependencias adicionales ...más allá de PowerShell y .NET Framework.



Así se verá un archivo dummy en un editor hexadecimal:



Y así se verá el archivo dummy rellenado con datos aleatorios:





CreateDummyFile.ps1
Código
  1. <#PSScriptInfo
  2. .VERSION 1.0
  3. .GUID 26C67DF9-0F1E-4806-9D23-586DFBDECF88
  4. .AUTHOR ElektroStudios
  5. .COMPANYNAME ElektroStudios
  6. .COPYRIGHT ElektroStudios © 2025
  7. #>
  8.  
  9. $vbCode = @'
  10. #Region " Option Statements "
  11.  
  12. Option Strict On
  13. Option Explicit On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports Microsoft.VisualBasic
  21.  
  22. Imports System
  23. Imports System.Collections.Generic
  24. Imports System.ComponentModel
  25. Imports System.Diagnostics
  26. Imports System.Diagnostics.CodeAnalysis
  27. Imports System.Drawing
  28. Imports System.Drawing.Design
  29. Imports System.Globalization
  30. Imports System.IO
  31. Imports System.Linq
  32. Imports System.Reflection
  33. Imports System.Runtime.CompilerServices
  34. Imports System.Runtime.InteropServices
  35. Imports System.Security
  36. Imports System.Text
  37. Imports System.Windows.Forms
  38. Imports System.Xml
  39. Imports System.Xml.Serialization
  40.  
  41. Imports DevCase.Core.IO.DigitalInformation
  42. Imports DevCase.Core.IO.FileSystem
  43. Imports DevCase.Runtime.TypeConverters
  44. Imports DevCase.Win32
  45. Imports DevCase.Win32.Enums
  46.  
  47. #End Region
  48.  
  49. #Region " CreateDummyFileOptionsForm "
  50.  
  51. Public NotInheritable Class CreateDummyFileOptionsForm : Inherits System.Windows.Forms.Form
  52.  
  53.    Public Sub New()
  54.        Me.InitializeComponent()
  55.    End Sub
  56.  
  57.    'Form overrides dispose to clean up the component list.
  58.    <System.Diagnostics.DebuggerNonUserCode()>
  59.    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
  60.        Try
  61.            If disposing AndAlso components IsNot Nothing Then
  62.                components.Dispose()
  63.            End If
  64.        Finally
  65.            MyBase.Dispose(disposing)
  66.        End Try
  67.    End Sub
  68.  
  69.    'Required by the Windows Form Designer
  70.    Private components As System.ComponentModel.IContainer
  71.    Friend WithEvents PropertyGrid1 As New PropertyGrid
  72.    Friend WithEvents ButtonCancel As Button
  73.    Friend WithEvents ButtonOk As Button
  74.    Friend WithEvents TableLayoutPanel1 As TableLayoutPanel
  75.    Friend WithEvents Panel1 As Panel
  76.  
  77.    'NOTE: The following procedure is required by the Windows Form Designer
  78.    'It can be modified using the Windows Form Designer.  
  79.    'Do not modify it using the code editor.
  80.    <System.Diagnostics.DebuggerStepThrough()>
  81.    Private Sub InitializeComponent()
  82.        Me.PropertyGrid1 = New System.Windows.Forms.PropertyGrid()
  83.        Me.ButtonCancel = New System.Windows.Forms.Button()
  84.        Me.ButtonOk = New System.Windows.Forms.Button()
  85.        Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel()
  86.        Me.Panel1 = New System.Windows.Forms.Panel()
  87.        Me.TableLayoutPanel1.SuspendLayout()
  88.        Me.Panel1.SuspendLayout()
  89.        Me.SuspendLayout()
  90.        '
  91.        'PropertyGrid1
  92.        '
  93.        Me.PropertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill
  94.        Me.PropertyGrid1.Location = New System.Drawing.Point(3, 4)
  95.        Me.PropertyGrid1.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
  96.        Me.PropertyGrid1.Name = "PropertyGrid1"
  97.        Me.PropertyGrid1.PropertySort = System.Windows.Forms.PropertySort.NoSort
  98.        Me.PropertyGrid1.Size = New System.Drawing.Size(733, 157)
  99.        Me.PropertyGrid1.TabIndex = 0
  100.        Me.PropertyGrid1.ToolbarVisible = False
  101.        '
  102.        'ButtonCancel
  103.        '
  104.        Me.ButtonCancel.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
  105.        Me.ButtonCancel.Location = New System.Drawing.Point(624, 6)
  106.        Me.ButtonCancel.Name = "ButtonCancel"
  107.        Me.ButtonCancel.Size = New System.Drawing.Size(100, 40)
  108.        Me.ButtonCancel.TabIndex = 1
  109.        Me.ButtonCancel.Text = "Cancel"
  110.        Me.ButtonCancel.UseVisualStyleBackColor = True
  111.        '
  112.        'ButtonOk
  113.        '
  114.        Me.ButtonOk.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
  115.        Me.ButtonOk.Location = New System.Drawing.Point(518, 6)
  116.        Me.ButtonOk.Name = "ButtonOk"
  117.        Me.ButtonOk.Size = New System.Drawing.Size(100, 40)
  118.        Me.ButtonOk.TabIndex = 2
  119.        Me.ButtonOk.Text = "Ok"
  120.        Me.ButtonOk.UseVisualStyleBackColor = True
  121.        '
  122.        'TableLayoutPanel1
  123.        '
  124.        Me.TableLayoutPanel1.ColumnCount = 1
  125.        Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
  126.        Me.TableLayoutPanel1.Controls.Add(Me.Panel1, 0, 1)
  127.        Me.TableLayoutPanel1.Controls.Add(Me.PropertyGrid1, 0, 0)
  128.        Me.TableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill
  129.        Me.TableLayoutPanel1.Location = New System.Drawing.Point(0, 0)
  130.        Me.TableLayoutPanel1.Name = "TableLayoutPanel1"
  131.        Me.TableLayoutPanel1.RowCount = 2
  132.        Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 73.17073!))
  133.        Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 26.82927!))
  134.        Me.TableLayoutPanel1.Size = New System.Drawing.Size(739, 226)
  135.        Me.TableLayoutPanel1.TabIndex = 3
  136.        '
  137.        'Panel1
  138.        '
  139.        Me.Panel1.Controls.Add(Me.ButtonOk)
  140.        Me.Panel1.Controls.Add(Me.ButtonCancel)
  141.        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
  142.        Me.Panel1.Location = New System.Drawing.Point(3, 168)
  143.        Me.Panel1.Name = "Panel1"
  144.        Me.Panel1.Size = New System.Drawing.Size(733, 55)
  145.        Me.Panel1.TabIndex = 4
  146.        '
  147.        'CreateDummyFileOptionsForm
  148.        '
  149.        Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 17.0!)
  150.        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
  151.        Me.ClientSize = New System.Drawing.Size(739, 226)
  152.        Me.Controls.Add(Me.TableLayoutPanel1)
  153.        Me.Font = New System.Drawing.Font("Segoe UI", 10.0!)
  154.        Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
  155.        Me.MaximizeBox = False
  156.        Me.Name = "CreateDummyFileOptionsForm"
  157.        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
  158.        Me.Text = "Create Dummy File Options"
  159.        Me.TableLayoutPanel1.ResumeLayout(False)
  160.        Me.Panel1.ResumeLayout(False)
  161.        Me.ResumeLayout(False)
  162.  
  163.    End Sub
  164.  
  165.    Public Property DummyFileOptions As New DummyFileOptions
  166.  
  167.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  168.  
  169.        Me.PropertyGrid1.SelectedObject = Me.DummyFileOptions
  170.        DevCase.Extensions.PropertyGridExtensions.SetSplitterPosition(Me.PropertyGrid1, 145)
  171.        Me.MinimumSize = Me.Size
  172.        Me.MaximumSize = New Size(3840, Me.Height)
  173.    End Sub
  174.  
  175.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles ButtonCancel.Click
  176.        Me.DialogResult = DialogResult.Cancel
  177.        Me.Close()
  178.    End Sub
  179.  
  180.    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles ButtonOk.Click
  181.        Me.DialogResult = DialogResult.OK
  182.        Me.Close()
  183.    End Sub
  184.  
  185. End Class
  186.  
  187. #End Region
  188.  
  189. #Region " DummyFileOptions "
  190.  
  191. Public NotInheritable Class DummyFileOptions
  192.  
  193.    <Browsable(True)>
  194.    <Editor(GetType(SaveFileNameEditor), GetType(UITypeEditor))>
  195.    <DisplayName("File Path")>
  196.    <Description("File path where to create the dummy file.")>
  197.    Public Property FilePath As String = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "File.dummy")
  198.  
  199.    <TypeConverter(GetType(FileSizeConverter))>
  200.    <DisplayName("File Size")>
  201.    <Description("Size of the dummy file.")>
  202.    Public Property FileSize As New FileSize(1, DigitalStorageUnits.Megabyte)
  203.  
  204.    <Browsable(False)>
  205.    Public ReadOnly Property FileSizeBytes As ULong
  206.        Get
  207.            Return CULng(Me.FileSize.Size(DigitalStorageUnits.Byte))
  208.        End Get
  209.    End Property
  210.  
  211.    <TypeConverter(GetType(FileSizeConverter))>
  212.    <DisplayName("Buffer Size")>
  213.    <Description("Size of the buffer used to write the dummy file.")>
  214.    Public Property BufferSize As New FileSize(4, DigitalStorageUnits.Megabyte)
  215.  
  216.    <Browsable(False)>
  217.    Public ReadOnly Property BufferSizeBytes As Integer
  218.        Get
  219.            Return CInt(Me.BufferSize.Size(DigitalStorageUnits.Byte))
  220.        End Get
  221.    End Property
  222.  
  223.    <DisplayName("Use Random Data")>
  224.    <Description("If True, uses random bytes to fill the dummy file content; othewise, fills the dummy file with zero bytes.")>
  225.    Public Property UseRandomData As Boolean = False
  226.  
  227. End Class
  228.  
  229. #End Region
  230.  
  231. #Region " SaveFileNameEditor "
  232.  
  233. Public NotInheritable Class SaveFileNameEditor : Inherits UITypeEditor
  234.  
  235.    Public Overrides Function GetEditStyle(context As ITypeDescriptorContext) As UITypeEditorEditStyle
  236.        Return UITypeEditorEditStyle.Modal
  237.    End Function
  238.  
  239.    Public Overrides Function EditValue(context As ITypeDescriptorContext, provider As IServiceProvider, value As Object) As Object
  240.        If context Is Nothing OrElse context.Instance Is Nothing OrElse provider Is Nothing Then
  241.            Return MyBase.EditValue(context, provider, value)
  242.        End If
  243.  
  244.        Using saveFileDialog As New SaveFileDialog()
  245.            If value IsNot Nothing Then
  246.                saveFileDialog.FileName = value.ToString()
  247.            End If
  248.  
  249.            saveFileDialog.Title = "Select a location to save the dummy file"
  250.            saveFileDialog.Filter = "All files (*.*)|*.*"
  251.            saveFileDialog.FileName = "File.dummy"
  252.            If saveFileDialog.ShowDialog() = DialogResult.OK Then
  253.                value = saveFileDialog.FileName
  254.            End If
  255.        End Using
  256.  
  257.        Return value
  258.    End Function
  259. End Class
  260.  
  261. #End Region
  262.  
  263. #Region " NativeMethods "
  264.  
  265. Namespace DevCase.Win32.NativeMethods
  266.  
  267.    <HideModuleName>
  268.    <SuppressUnmanagedCodeSecurity>
  269.    <SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification:="Required to migrate this code to .NET Core")>
  270.    <SuppressMessage("Interoperability", "CA1401:P/Invokes should not be visible", Justification:="")>
  271.    Public Module ShlwApi
  272.  
  273. #Region " ShlwApi.dll "
  274.  
  275.        <DllImport("ShlwApi.dll", SetLastError:=True, ExactSpelling:=True, CharSet:=CharSet.Ansi, BestFitMapping:=False, ThrowOnUnmappableChar:=True)>
  276.        Public Function StrFormatByteSize64A(number As ULong,
  277.                                            buffer As StringBuilder,
  278.                                            bufferSize As UInteger
  279.        ) As IntPtr
  280.        End Function
  281.  
  282.        <DllImport("ShlwApi.dll", SetLastError:=False, ExactSpelling:=True, CharSet:=CharSet.Unicode)>
  283.        Public Function StrFormatByteSizeEx(number As ULong,
  284.                                            flags As StrFormatByteSizeFlags,
  285.                                            buffer As StringBuilder,
  286.                                            bufferSize As UInteger
  287.        ) As Integer ' HResult
  288.        End Function
  289.  
  290. #End Region
  291.  
  292.    End Module
  293.  
  294. End Namespace
  295.  
  296. #End Region
  297.  
  298. #Region " StrFormatByteSizeFlags "
  299.  
  300. Namespace DevCase.Win32.Enums
  301.  
  302.    Public Enum StrFormatByteSizeFlags
  303.        RoundToNearest = 1
  304.        Truncate = 2
  305.    End Enum
  306.  
  307. End Namespace
  308.  
  309. #End Region
  310.  
  311. #Region " Size Units "
  312.  
  313. Namespace DevCase.Core.IO.DigitalInformation
  314.  
  315.    Public Enum DigitalStorageUnits As Long
  316.        [Byte] = CLng(2 ^ 0)
  317.        Kilobyte = CLng(2 ^ 10)
  318.        Megabyte = CLng(2 ^ 20)
  319.        Gigabyte = CLng(2 ^ 30)
  320.        Terabyte = CLng(2 ^ 40)
  321.        Petabyte = CLng(2 ^ 50)
  322.        Exabyte = CLng(2 ^ 60)
  323.    End Enum
  324.  
  325. End Namespace
  326.  
  327. #End Region
  328.  
  329. #Region " Filesize "
  330.  
  331. Namespace DevCase.Core.IO.FileSystem
  332.  
  333.    Public NotInheritable Class FileSize
  334.  
  335. #Region " Private Fields "
  336.  
  337.        Private ReadOnly bytesB As Double
  338.  
  339. #End Region
  340.  
  341. #Region " Properties "
  342.  
  343.        Public ReadOnly Property Size(sizeUnit As DigitalStorageUnits) As Double
  344.            Get
  345.                Return Convert(size:=Me.bytesB, fromUnit:=DigitalStorageUnits.Byte, toUnit:=sizeUnit)
  346.            End Get
  347.        End Property
  348.  
  349.        Public ReadOnly Property Size(sizeUnit As DigitalStorageUnits, decimalPrecision As Integer, Optional numberFormatInfo As NumberFormatInfo = Nothing) As String
  350.            Get
  351.                If numberFormatInfo Is Nothing Then
  352.                    numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
  353.                End If
  354.                Return Me.Size(sizeUnit).ToString(String.Format("N{0}", decimalPrecision), numberFormatInfo)
  355.            End Get
  356.        End Property
  357.  
  358.        Public Property SizeRounded As Double
  359.  
  360.        Public ReadOnly Property SizeRounded(decimalPrecision As Integer, Optional numberFormatInfo As NumberFormatInfo = Nothing) As String
  361.            Get
  362.                If numberFormatInfo Is Nothing Then
  363.                    numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
  364.                End If
  365.                Return Me.SizeRounded.ToString(String.Format("N{0}", decimalPrecision), numberFormatInfo)
  366.            End Get
  367.        End Property
  368.  
  369.        Public Property SizeUnit As DigitalStorageUnits
  370.        Public Property SizeUnitNameShort As String
  371.        Public Property SizeUnitNameLong As String
  372.  
  373. #End Region
  374.  
  375. #Region " Constructors "
  376.  
  377.        Private Sub New()
  378.        End Sub
  379.  
  380.        <DebuggerStepThrough>
  381.        Public Sub New(size As Double, sizeUnit As DigitalStorageUnits)
  382.  
  383.            Me.bytesB = System.Convert.ToDouble(size * sizeUnit)
  384.  
  385.            Select Case System.Math.Abs(Me.bytesB)
  386.  
  387.                Case Is >= DigitalStorageUnits.Petabyte
  388.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Petabyte
  389.                    Me.SizeUnit = DigitalStorageUnits.Petabyte
  390.                    Me.SizeUnitNameShort = "PB"
  391.                    Me.SizeUnitNameLong = "PetaBytes"
  392.  
  393.                Case Is >= DigitalStorageUnits.Terabyte
  394.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Terabyte
  395.                    Me.SizeUnit = DigitalStorageUnits.Terabyte
  396.                    Me.SizeUnitNameShort = "TB"
  397.                    Me.SizeUnitNameLong = "TeraBytes"
  398.  
  399.                Case Is >= DigitalStorageUnits.Gigabyte
  400.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Gigabyte
  401.                    Me.SizeUnit = DigitalStorageUnits.Gigabyte
  402.                    Me.SizeUnitNameShort = "GB"
  403.                    Me.SizeUnitNameLong = "GigaBytes"
  404.  
  405.                Case Is >= DigitalStorageUnits.Megabyte
  406.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Megabyte
  407.                    Me.SizeUnit = DigitalStorageUnits.Megabyte
  408.                    Me.SizeUnitNameShort = "MB"
  409.                    Me.SizeUnitNameLong = "MegaBytes"
  410.  
  411.                Case Is >= DigitalStorageUnits.Kilobyte
  412.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Kilobyte
  413.                    Me.SizeUnit = DigitalStorageUnits.Kilobyte
  414.                    Me.SizeUnitNameShort = "KB"
  415.                    Me.SizeUnitNameLong = "KiloBytes"
  416.  
  417.                Case Is >= DigitalStorageUnits.Byte, Is = 0
  418.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Byte
  419.                    Me.SizeUnit = DigitalStorageUnits.Byte
  420.                    Me.SizeUnitNameShort = "Bytes"
  421.                    Me.SizeUnitNameLong = "Bytes"
  422.            End Select
  423.  
  424.        End Sub
  425.  
  426. #End Region
  427.  
  428. #Region " Public Methods "
  429.  
  430.        Public Overrides Function ToString() As String
  431.            Return Me.ToString(CultureInfo.InvariantCulture.NumberFormat)
  432.        End Function
  433.  
  434.        Public Overloads Function ToString(provider As IFormatProvider) As String
  435.            Return If(Me.SizeUnit = DigitalStorageUnits.Byte,
  436.                String.Format(provider, "{0:0.##} {1}", System.Math.Floor(Me.SizeRounded * 100) / 100, Me.SizeUnitNameShort),
  437.                String.Format(provider, "{0:0.00} {1}", System.Math.Floor(Me.SizeRounded * 100) / 100, Me.SizeUnitNameShort))
  438.        End Function
  439.  
  440.        Public Function ToStringFormatByteSize(flags As StrFormatByteSizeFlags) As String
  441.  
  442.            Dim buffer As New StringBuilder(8, 16)
  443.            Dim result As Integer = NativeMethods.StrFormatByteSizeEx(CULng(Me.bytesB), flags, buffer, 16) ' HRESULT
  444.            If result <> 0 Then
  445.                Marshal.ThrowExceptionForHR(result)
  446.            End If
  447.  
  448.            Return buffer.ToString()
  449.        End Function
  450.  
  451. #End Region
  452.  
  453. #Region " Private Methods "
  454.  
  455.        <DebuggerStepThrough>
  456.        Private Shared Function Convert(size As Double,
  457.                                 fromUnit As DigitalStorageUnits,
  458.                                 toUnit As DigitalStorageUnits) As Double
  459.  
  460.            Dim bytes As Double = If(fromUnit = DigitalStorageUnits.Byte, size, System.Convert.ToDouble(size * fromUnit))
  461.  
  462.            If toUnit < fromUnit Then
  463.                Select Case toUnit
  464.                    Case DigitalStorageUnits.Byte
  465.                        Return bytes
  466.  
  467.                    Case DigitalStorageUnits.Kilobyte
  468.                        Return bytes / DigitalStorageUnits.Kilobyte
  469.  
  470.                    Case DigitalStorageUnits.Megabyte
  471.                        Return bytes / DigitalStorageUnits.Megabyte
  472.  
  473.                    Case DigitalStorageUnits.Gigabyte
  474.                        Return bytes / DigitalStorageUnits.Gigabyte
  475.  
  476.                    Case DigitalStorageUnits.Terabyte
  477.                        Return bytes / DigitalStorageUnits.Terabyte
  478.  
  479.                    Case DigitalStorageUnits.Petabyte
  480.                        Return bytes / DigitalStorageUnits.Petabyte
  481.  
  482.                    Case Else
  483.                        Throw New InvalidEnumArgumentException(argumentName:="toUnit", invalidValue:=CInt(toUnit),
  484.                                                               enumClass:=GetType(DigitalStorageUnits))
  485.                End Select
  486.  
  487.            ElseIf toUnit > fromUnit Then
  488.                Select Case toUnit
  489.  
  490.                    Case DigitalStorageUnits.Byte
  491.                        Return bytes
  492.  
  493.                    Case DigitalStorageUnits.Kilobyte
  494.                        Return bytes * DigitalStorageUnits.Kilobyte / (DigitalStorageUnits.Kilobyte ^ 2)
  495.  
  496.                    Case DigitalStorageUnits.Megabyte
  497.                        Return bytes * DigitalStorageUnits.Megabyte / (DigitalStorageUnits.Megabyte ^ 2)
  498.  
  499.                    Case DigitalStorageUnits.Gigabyte
  500.                        Return bytes * DigitalStorageUnits.Gigabyte / (DigitalStorageUnits.Gigabyte ^ 2)
  501.  
  502.                    Case DigitalStorageUnits.Terabyte
  503.                        Return bytes * DigitalStorageUnits.Terabyte / (DigitalStorageUnits.Terabyte ^ 2)
  504.  
  505.                    Case DigitalStorageUnits.Petabyte
  506.                        Return bytes * DigitalStorageUnits.Petabyte / (DigitalStorageUnits.Petabyte ^ 2)
  507.  
  508.                    Case Else
  509.                        Throw New InvalidEnumArgumentException(argumentName:="toUnit", invalidValue:=CInt(toUnit),
  510.                                                               enumClass:=GetType(DigitalStorageUnits))
  511.                End Select
  512.  
  513.            Else ' If toUnit = fromUnit
  514.                Return bytes
  515.  
  516.            End If
  517.        End Function
  518.  
  519. #End Region
  520.  
  521.    End Class
  522.  
  523. End Namespace
  524.  
  525. #End Region
  526.  
  527. #Region " FileSizeConverter "
  528.  
  529. Namespace DevCase.Runtime.TypeConverters
  530.  
  531.    Public Class FileSizeConverter : Inherits TypeConverter
  532.  
  533. #Region " Private Fields "
  534.  
  535.        Private ReadOnly sizeUnitsDictionary As Dictionary(Of String(), ULong)
  536.  
  537. #End Region
  538.  
  539. #Region " Constructors "
  540.  
  541.        Public Sub New()
  542.            Me.sizeUnitsDictionary = New Dictionary(Of String(), ULong)(StringComparison.OrdinalIgnoreCase) From {
  543.                {{"b", "byte", "bytes"}, 1UL},
  544.                {{"KB", "kilo", "kilos", "kilobyte", "kilobytes", "kilo byte", "kilo bytes"}, 1024UL},
  545.                {{"MB", "mega", "megas", "megabyte", "megabytes", "mega byte", "mega bytes"}, CULng(1024UL ^ 2UL)},
  546.                {{"GB", "giga", "gigas", "gigabyte", "gigabytes", "giga byte", "giga bytes"}, CULng(1024UL ^ 3UL)},
  547.                {{"TB", "tera", "teras", "terabyte", "terabytes", "tera byte", "tera bytes"}, CULng(1024UL ^ 4UL)},
  548.                {{"PB", "peta", "petas", "petabyte", "petabytes", "peta byte", "peta bytes"}, CULng(1024UL ^ 5UL)},
  549.                {{"EB", "exa", "exas", "exabyte", "exabytes", "exa byte", "exa bytes"}, CULng(1024UL ^ 6UL)}
  550.            }
  551.        End Sub
  552.  
  553. #End Region
  554.  
  555. #Region " Public Methods "
  556.  
  557.        Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  558.  
  559.            Return sourceType Is GetType(String) OrElse
  560.                   MyBase.CanConvertFrom(context, sourceType)
  561.        End Function
  562.  
  563.        Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  564.  
  565.            Return destinationType Is GetType(ULong) OrElse
  566.                   destinationType Is GetType(String) OrElse
  567.                   MyBase.CanConvertTo(context, destinationType)
  568.        End Function
  569.  
  570.        <DebuggerStepThrough>
  571.        Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
  572.  
  573.            If TypeOf value Is String Then
  574.                Dim strValue As String = DirectCast(value, String)
  575.                If strValue.Contains("("c) Then
  576.                    strValue = strValue.Substring(0, strValue.IndexOf("("c))
  577.                End If
  578.                Dim bytes As ULong
  579.                If ULong.TryParse(strValue, bytes) Then
  580.                    Return bytes
  581.                End If
  582.                bytes = Me.ParseFileSizeString(strValue)
  583.                If bytes <> 0UL Then
  584.                    If context.PropertyDescriptor IsNot Nothing AndAlso context.PropertyDescriptor.PropertyType Is GetType(FileSize) Then
  585.                        Return New FileSize(bytes, DigitalStorageUnits.Byte)
  586.                    Else
  587.                        Return DirectCast(bytes, Object)
  588.                    End If
  589.                End If
  590.            End If
  591.  
  592.            Return MyBase.ConvertFrom(context, culture, value)
  593.        End Function
  594.  
  595.        <DebuggerStepThrough>
  596.        Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
  597.            If destinationType Is GetType(String) Then
  598.                Dim bytes As ULong = If((TypeOf value Is FileSize), CULng(DirectCast(value, FileSize).Size(DigitalStorageUnits.Byte)), DirectCast(value, ULong))
  599.                Dim formattedSize As String = Me.FormatByteFileSize(bytes)
  600.                Return If(bytes < 1024, String.Format("{0}", formattedSize), String.Format("{0} ({1:N0} bytes)", formattedSize, bytes))
  601.            End If
  602.  
  603.            Return MyBase.ConvertTo(context, culture, value, destinationType)
  604.        End Function
  605.  
  606. #End Region
  607.  
  608. #Region " Private Methods "
  609.  
  610.        <DebuggerStepThrough>
  611.        Private Function ParseFileSizeString(sizeString As String) As ULong
  612.  
  613.            Dim trimmedSizeString As String = sizeString.Trim()
  614.            If trimmedSizeString.Contains("("c) Then
  615.                trimmedSizeString = trimmedSizeString.Substring(0, trimmedSizeString.IndexOf("("c))
  616.            End If
  617.  
  618.            For Each kvp As KeyValuePair(Of String(), ULong) In sizeUnitsDictionary
  619.                For Each sizeUnitName As String In kvp.Key
  620.                    If trimmedSizeString.EndsWith(sizeUnitName, StringComparison.OrdinalIgnoreCase) Then
  621.                        Dim numString As String = trimmedSizeString.Substring(0, trimmedSizeString.Length - sizeUnitName.Length).Trim()
  622.                        Dim num As Double
  623.                        Dim numberFormat As IFormatProvider
  624. #If NETCOREAPP Then
  625.                        numberFormat = Thread.CurrentThread.CurrentUICulture.NumberFormat
  626. #Else
  627.                        numberFormat = My.Application.UICulture.NumberFormat
  628. #End If
  629.                        If Double.TryParse(numString, NumberStyles.Number, numberFormat, num) Then
  630.                            Try
  631.                                Return CULng((num * kvp.Value))
  632.                            Catch ex As OverflowException
  633.                                Return ULong.MaxValue
  634.                            Catch ex As Exception
  635.                                Throw
  636.                            End Try
  637.                        End If
  638.                    End If
  639.                Next sizeUnitName
  640.            Next kvp
  641.  
  642.            Throw New Exception("Cannot parse the specified file size value.")
  643.        End Function
  644.  
  645.  
  646.        <DebuggerStepThrough>
  647.        Private Function FormatByteFileSize(bytes As ULong) As String
  648.            Dim unitIndex As Integer = 0
  649.            Dim fileSize As Double = bytes
  650.  
  651.            While (fileSize >= 1024) AndAlso (unitIndex < sizeUnitsDictionary.Count - 1)
  652.                fileSize /= 1024
  653.                unitIndex += 1
  654.            End While
  655.  
  656.            Return If(unitIndex = 0,
  657.                       String.Format("{0} bytes", fileSize),
  658.                       String.Format("{0:F2} {1}", fileSize, sizeUnitsDictionary.ElementAt(unitIndex).Key(0)).Replace(",00", ""))
  659.        End Function
  660.  
  661. #End Region
  662.  
  663.    End Class
  664.  
  665. End Namespace
  666.  
  667. #End Region
  668.  
  669. #Region " PropertyGridExtensions "
  670.  
  671. Namespace DevCase.Extensions.PropertyGridExtensions
  672.  
  673.    <HideModuleName>
  674.    Public Module PropertyGridExtensions
  675.  
  676. #Region " Public Extension Methods "
  677.  
  678.        <DebuggerStepThrough>
  679.        <Extension>
  680.        <EditorBrowsable(EditorBrowsableState.Always)>
  681.        Public Function IsInitialized(propGrid As PropertyGrid) As Boolean
  682.  
  683.            Return PropertyGridExtensions.GetInternalLabelWidth(propGrid) <> -1
  684.        End Function
  685.  
  686.        <DebuggerStepThrough>
  687.        <Extension>
  688.        <EditorBrowsable(EditorBrowsableState.Always)>
  689.        Public Sub SetSplitterPosition(propGrid As PropertyGrid, xPos As Integer)
  690.  
  691.            If Not PropertyGridExtensions.IsInitialized(propGrid) Then
  692.                Throw New InvalidOperationException("The PropertyGrid must be initialized in order to set the splitter control position.")
  693.            End If
  694.  
  695.            Dim internalGridView As Control = PropertyGridExtensions.GetPropertyGridInternal(propGrid)
  696.            Dim moveSplitterToMethod As MethodInfo = internalGridView.GetType().GetMethod("MoveSplitterTo", BindingFlags.NonPublic Or BindingFlags.Instance)
  697.            moveSplitterToMethod.Invoke(internalGridView, {xPos})
  698.        End Sub
  699.  
  700. #End Region
  701.  
  702. #Region " Private Methods "
  703.  
  704.        Private Function GetPropertyGridInternal(propGrid As PropertyGrid) As Control
  705.  
  706.            ' Class: System.Windows.Forms.PropertyGridInternal.PropertyGridView
  707.  
  708.            Dim getPropertyGridViewMethod As MethodInfo = GetType(PropertyGrid).GetMethod("GetPropertyGridView", BindingFlags.NonPublic Or BindingFlags.Instance)
  709.            Dim gridView As Control = DirectCast(getPropertyGridViewMethod.Invoke(propGrid, Array.Empty(Of Object)()), Control)
  710.            Return gridView
  711.  
  712.            ' We can also retrieve the internal PropertyGridView this other way:
  713.            ' ------------------------------------------------------------------
  714.            ' Dim gridViewFieldInfo As FieldInfo = propGrid.GetType().GetField("gridView", BindingFlags.Instance Or BindingFlags.NonPublic)
  715.            ' Dim gridView As Control = DirectCast(gridViewFieldInfo.GetValue(propGrid), Control)
  716.            ' Return gridView
  717.        End Function
  718.  
  719.        Private Function GetInternalLabelWidth(propGrid As PropertyGrid) As Integer
  720.  
  721.            Dim internalGridView As Control = PropertyGridExtensions.GetPropertyGridInternal(propGrid)
  722.            Dim propInfo As PropertyInfo = internalGridView.GetType().GetProperty("InternalLabelWidth", BindingFlags.NonPublic Or BindingFlags.Instance)
  723.            Return CInt(propInfo.GetValue(internalGridView))
  724.        End Function
  725.  
  726. #End Region
  727.  
  728.    End Module
  729.  
  730. End Namespace
  731.  
  732. #End Region
  733. '@
  734. $assembly = Add-Type -TypeDefinition $vbCode `
  735.                      -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
  736.                      -PassThru `
  737.                      -ReferencedAssemblies "Microsoft.VisualBasic.dll", `
  738.                                            "System.Windows.Forms.dll", `
  739.                                            "System.Security.dll", `
  740.                                            "System.Collections.dll", `
  741.                                            "System.Drawing.dll", `
  742.                                            "System.Globalization.dll", `
  743.                                            "System.Reflection.dll", `
  744.                                            "System.Linq.dll", `
  745.                                            "System.IO.dll", `
  746.                                            "System.Xml.dll", `
  747.                                            "System.Xml.Serialization.dll", `
  748.                                            "System.dll" `
  749.                      | where { $_.IsPublic }
  750.  
  751.  
  752. function Get-FormattedSize {
  753.    param (
  754.        [int64]$sizeInBytes
  755.    )
  756.  
  757.    $buffer = New-Object System.Text.StringBuilder 24
  758.    $resultPtr = [DevCase.Win32.NativeMethods.ShlwApi]::StrFormatByteSize64A($sizeInBytes, $buffer, $buffer.Capacity)
  759.  
  760.    if ($resultPtr -eq [IntPtr]::Zero) {
  761.        return "Error formatting the file size."
  762.    } else {
  763.        return $buffer.ToString()
  764.    }
  765. }
  766.  
  767. function WriteDummyFile {
  768.    param (
  769.        [string]$FilePath,
  770.        [uint64]$FileSize,
  771.        [uint64]$BufferSize = 4MB,
  772.        [bool]$randomData = $false
  773.    )
  774.  
  775.    $formattedFileSize = Get-FormattedSize -sizeInBytes $FileSize
  776.  
  777.    $fs = [System.IO.File]::Create($FilePath)
  778.  
  779.    if ($BufferSize -ge $FileSize) {
  780.        $BufferSize = [math]::Floor($FileSize / 2)
  781.    }
  782.  
  783.    [int64]$bytesWritten = 0
  784.    $buffer = New-Object byte[] $BufferSize
  785.    $rand = New-Object Random
  786.  
  787.    Write-Host "Creating dummy file at '$FilePath' with a size of $formattedFileSize..."
  788.  
  789.    while ($bytesWritten -lt $FileSize) {
  790.        $bytesToWrite = [math]::Min($BufferSize, $FileSize - $bytesWritten)
  791.  
  792.        if ($randomData) {
  793.            $rand.NextBytes($buffer)
  794.        } else {
  795.            [Array]::Clear($buffer, 0, $bytesToWrite)
  796.        }
  797.  
  798.        $fs.Write($buffer, 0, $bytesToWrite)
  799.  
  800.        $bytesWritten += $bytesToWrite
  801.        $formattedBytesWritten = Get-FormattedSize -sizeInBytes $bytesWritten
  802.  
  803.        $progressPercent = [math]::Min(($bytesWritten / $FileSize) * 100, 100)
  804.  
  805.        Write-Progress -PercentComplete $progressPercent -Status "$FilePath" -Activity "Writing dummy file..." -CurrentOperation "$formattedBytesWritten written."
  806.    }
  807.        Write-Progress -PercentComplete 100 -Status "$FilePath" -Activity "Dummy file has been written." -CurrentOperation "$formattedBytesWritten written."
  808.  
  809.    $fs.Close()
  810.  
  811.    Write-Host ""
  812.    Write-Host ""
  813.    Write-Host ""
  814.    Write-Host ""
  815.    Write-Host ""
  816.    Write-Host ""
  817.    Write-Host ""
  818.    Write-Host ""
  819.    Write-Host ""
  820.    Write-Host "Dummy file successfully created at '$FilePath' with a size of $formattedFileSize."
  821. }
  822.  
  823.  
  824. $form = New-Object CreateDummyFileOptionsForm
  825. $dlgResult = $form.ShowDialog()
  826.  
  827. if ($dlgResult -eq [System.Windows.Forms.DialogResult]::OK) {
  828.    $fileOptions = $form.DummyFileOptions
  829.    WriteDummyFile -FilePath $fileOptions.FilePath -FileSize $fileOptions.FileSizeBytes -BufferSize $fileOptions.BufferSizeBytes -randomData $fileOptions.UseRandomData
  830. } else {
  831.    Write-Host "Operation canceled. No file selected."
  832. }
  833.  
  834. Write-Host "Press any key to exit..."
  835. $key = [System.Console]::ReadKey($true)
  836. Exit(0)
  837.  
72  Foros Generales / Foro Libre / En honor a quienes caminaron antes que nosotros (en el foro) en: 6 Febrero 2025, 19:50 pm
En honor a quienes caminaron antes que nosotros

A lo largo de los años, muchas personas han pasado por este foro, compartiendo su conocimiento, su tiempo y su pasión por la informática y el hacking ético. Pseudónimos como Simorg, Randomize o engel lex, entre tantos otros que se merecen una mención, quedarán en el recuerdo de muchos, y perdurarán por siempre en las páginas del foro ...o al menos hasta que el-brujo pulse el botón rojo. 🔌

Algunos fueron mentores, otros fueron compañeros de aprendizaje, otros fueron amigos, y todos ellos dejaron su marca en cada hilo, en cada respuesta y en cada solución compartida. 🏆 Sois los mejores, ¡todos!.

Este humilde y pequeño homenaje está dedicado para aquellos que ya no están activos, pero cuyo legado sigue vivo en cada línea de código y en cada enseñanza que dejaron: gracias. Sus aportes siguen iluminando el camino de quienes hoy buscan aprender, tal como ustedes lo hicieron en su momento.

Foro.elhacker.net no es solo una comunidad, es el reflejo de la perseverancia, el altruismo y el esfuerzo de quienes alguna vez estuvieron aquí y quienes siguen estando resolviendo dudas, demostrando que el conocimiento es más valioso cuando se comparte.

A todos ustedes, los que alguna vez fueron parte de esto, los que caminaron antes que nosotros: no se les olvida.

🙏 Gracias por todo.

Atentamente,
Elektro.
73  Foros Generales / Foro Libre / Re: Elon Musk responde a las críticas por su presunto saludo nazi: "El ataque de 'todo el mundo es Hitler' es muy cansin en: 24 Enero 2025, 13:12 pm
Bueno, yo en este lugar no puedo dar mi opinión libre al respecto de tu comentario, por que entonces me pongo a escribir mucho y me eliminan el comentario por "desviar el tema".

Y me gustaría ofrecerte otro punto de vista, por que el fascismo no tiene una sola forma ni se presenta en una sola ideología, no se manifiesta solamente de la forma en que políticos como Nicolás Maduro o Pedro Sánchez señalan a cada minuto, sino también de la forma en que les señala a ellos mismos. Pero si lo hiciera, argumentando mis motivos y señalando y razonando los puntos en común con el fascismo, probablemente me eliminarían el comentario... precisamente por que en España, aunque parezca mentira, existe el fascismo, el que no te permite expresar una opinión diferente a la narrativa oficialista del progresismo que apoyan muchas personas, por que si lo haces, serás silenciado y castigado de forma totalitaria por autócratas (y no me refiero a moderadores del foro, ¡sino a los políticos y sus simpatizantes!).

No hay más que ver lo poco que le cuesta asumir a una parte de la sociedad, que un grupo de vecinos afectados e indignados en Paiporta, por la riada de Valencia se conviertan de la noche a la mañana en un "grupo radical violento de extrema derecha", por que así lo dice el líder y así lo transmiten en sus instrumentos de difusión.

No hay más que ver eso. Y yo como valenciano pues que quieres que te diga, ¡que quieres que te diga!, si digo todo lo que pienso me banean.

Así que me saltaré esa argumentación y pasaré a decir que:

Yo comparto por España el mismo sentimiento de soberanía y patriotismo que Trump y Elon Musk dicen profesar por su nación estadounidense, o Milei por argentina, Bukele por El Salvador, y Viktor Orbán por Polonia. A Abascal no lo menciono por que no me parece digno de mención, pero si que mencionaría a Iván Espinosa de Los Monteros, ex-miembro de VOX y un excelentísimo economista liberal.

¿Todos ellos son fascistas?...

Pues parece ser que sí. Para el progresismo, incluyendo Nicolás Maduro, Pedro Sánchez y toda esta gente de PODEMOS/SUMAR, para ellos son "fascistas" o "ultra derecha reaccionaria internacional", pero lo cierto es que Milei es liberal-libertario, Orbán conservador, y Bukele se define a si mismo (y la prensa extranjera lo define) como progresista, y mira lo que ha hecho el tío, ha empezado a encarcelar a criminales omitiendo la carta de derechos progresistas de los "derechos humanos" de los delincuentes, para lograr devolverle a su pueblo la seguridad en las calles, el poder cruzar una esquina de noche sin que te roben ni te maten, sin que te violen o te hagan un mataleón y te dejen en coma, cosa con la que los españoles... bueno, para qué decir nada sobre como está España en este aspecto de la seguridad ciudadana, me gustaría dar explicaciones y argumentar, pero insisto en que si lo hiciera probablemente me eliminarían el comentario...

A lo que voy. Las diferencias ideológicas personales de cada personaje político que he mencionado, debería demostrar que los opuestos ideológicos no necesariamente tienen por que suponer un conflicto de intereses para poder restaurar el sentido común y hacer prosperar a la sociedad. Si un político tiene la voluntad, se considere progresista o conservador, se puede hacer.

En eso estamos todos, en acabar con lo que muchos consideramos el fascismo moderno del siglo XXI, que en nuestra opinión ha tomado una forma progresista, woke en el caso de EEUU, o para ser más específicos, una forma globalista. Acabar con sus imposiciones ideológicas extremistas y elitistas para restaurar, entre otras cosas, el estado de bien estar de la sociedad, y la prosperidad económica de nuestros países, dos cosas que en muchos países europeos (en la inmensa mayoría, exceptuando Hungría y Polonia) han estado sujetos durante muchos años (en el caso de España, sigue estando, desde 2008, mucho antes de que se fundase la "Agenda 2030") a intereses extranjeros (globalistas) promovidos por líderes políticos autodenominados progresistas, y también por centristas.

PD: Al final he vuelto a escribir mucho xD no puedo evitarlo. Bueno, si me eliminan el comentario pues nada. Lo siento.

Un saludo.
74  Foros Generales / Foro Libre / Re: Elon Musk responde a las críticas por su presunto saludo nazi: "El ataque de 'todo el mundo es Hitler' es muy cansin en: 22 Enero 2025, 18:31 pm
Yo no siento ninguna admiración hacia Elon Musk, ni me cae generosamente bien, ni tampoco es que me caiga mal, me causa cierta indeferencia como persona, aunque reconozco sus logros con Space X y con Twitter/X...

Pero a lo que voy, lo más importante es que no siento ninguna envidia al saber que Elon es considerado el hombre más rico del planeta (SPOILER: no lo es), y por ello capaz de hacer lo que él quiera y sin pensar mucho ni preocuparse en como se podrá interpretar un gesto o unas declaraciones.

¿Por qué Elon debería actuar de forma diferente a como lo ha hecho?. ¿SE NOS HA OLVIDADO YA QUE ELON MUSK ES UNA PERSONA NEURODIVERGENTE (AUTISTA)?. Si al final los que llevan los hilos en el otro extremo de la ideología política van a decir de él lo que quieran atribuirle para atacarle, como también lo harían desde el extremo de la ideología de Elon y Trump para atacar a los que no piensan como ellos.

Por poner un ejemplo contrario a la ideología de derechas de Elon Musk, hay otros muchos personajes públicos, en especial "filántropos" y políticos de izquierda (aunque también los hay de derechas), que le sacan una foto haciendo un gesto muy particular con las manos, y a cada minuto les están acusando de ser masones o de hacer ritos satánicos por ese gesto... solo por poner las manos de una forma en específico...

¿Acaso esto no es exactamente el mismo tipo de ataque pero cambiando la persona que recibe los ataques?.

Así es, esto también es una... TEORÍA CONSPIRATIVA infundada.

La gente que se crea esto del "saludo nazi" debería utilizar más su capacidad de análisis y observación para darse cuenta de que la mayoría de las veces las cosas no son blanco o negro, sino grises con muchos matices.

Un saludo!
75  Foros Generales / Foro Libre / Re: Elon Musk responde a las críticas por su presunto saludo nazi: "El ataque de 'todo el mundo es Hitler' es muy cansin en: 21 Enero 2025, 22:08 pm
Yo he visto muchas intervenciones de Elon en directo, y le he visto hacer gestos iguales y parecidos hablando sobre criptomonedas y sobre Space X también. Hay varios ejemplos muy claros y sencillos de encontrar, cuando Elon dice la típica frase de "To the moon!!".

En fin. Cuando Elon no es un nazi, es un satánico, masón, conspirador, lunático, autoritario o cualquier otra cosa negativa que cause animadversión.

Y mira que es fácil describir al verdadero Elon: un ricachón que hace lo que le sale de las pelotas. Pero eso da igual, los políticos seguirán reviviendo enemigos artificiales para seguir dividiendo y enfrentando a la mitad de la sociedad con la otra mitad.

Un saludo.
76  Foros Generales / Foro Libre / Re: "Solo hay dos géneros, masculino y femenino", "Dios me salvó...": las frases más polémicas del discurso de Trump en: 21 Enero 2025, 00:38 am
Hay ciertas frases que solo pueden volverse polémicas en un mundo idiotizado como este.

Como Trump dijo durante su toma de posesión: Se trata de restaurar el sentido común.
77  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) en: 16 Enero 2025, 15:27 pm
Clase DllExportAttribute

La clase DllExportAttribute indica que un método puede ser exportado como una función de C, desde una biblioteca de enlace dinámico (DLL) de .NET, lo que hace que el método sea invocable desde código no administrado.

La clase DllExportAttribute está destinada únicamente a replicar y mejorar la clase de atributo DllExportAttribute de plugins como:


Permitiendo que un programador pueda utilizar esta clase de atributo sin necesidad de tener el plugin instalado en sus proyectos de Visual Studio.

Sigue siendo estrictamente necesario utilizar alguno de los proyectos mencionados para habilitar la exportación de funciones .NET.



Capturas de pantalla de la documentación interactiva:













El código fuente:

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 16-January-2025
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Usage Examples "
  15.  
  16. ' VB.NET
  17. ' <DllExport(NameOf(MyStringFunction), CallingConvention.StdCall)>
  18. ' Public Shared Function MyStringFunction() As <MarshalAs(UnmanagedType.BStr)> String
  19. '     Return "Hello World!"
  20. ' End Function
  21.  
  22. ' C#
  23. ' [DllExport(nameof(MyStringFunction), CallingConvention.StdCall)]
  24. ' [return: MarshalAs(UnmanagedType.BStr)]
  25. ' public static string MyStringFunction() {
  26. '     return "Hello World!";
  27. ' }
  28.  
  29. #End Region
  30.  
  31. #Region " Imports "
  32.  
  33. Imports System.Runtime.InteropServices
  34.  
  35. #End Region
  36.  
  37. ' ReSharper disable once CheckNamespace
  38.  
  39. #Region " DllExportAttribute "
  40.  
  41. Namespace DevCase.Runtime.Attributes
  42.  
  43.    ''' <summary>
  44.    ''' The <see cref="DllExportAttribute"/> class indicates that a method can be
  45.    ''' exported as a C function from a .NET dynamic-link library (DLL) file,
  46.    ''' making the method callable from unmanaged code.
  47.    ''' <para></para>
  48.    ''' The <see cref="DllExportAttribute"/> class is solely intended to replicate and improve the
  49.    ''' <b>DllExportAttribute</b> attribute class from plugins like:
  50.    ''' <list type="bullet">
  51.    '''   <item><b>DllExport</b> by 3F
  52.    '''     <para></para>
  53.    '''     <see href="https://github.com/3F/DllExport"/>
  54.    '''   </item>
  55.    '''  
  56.    '''   <item><b>UnmanagedExports</b> by Huajitech
  57.    '''     <para></para>
  58.    '''     <see href="https://github.com/huajitech/UnmanagedExports"/>
  59.    '''   </item>
  60.    '''  
  61.    '''   <item><b>UnmanagedExports.Repack.Upgrade</b> by StevenEngland
  62.    '''     <para></para>
  63.    '''     <see href="https://github.com/stevenengland/UnmanagedExports.Repack.Upgrade"/>
  64.    '''   </item>
  65.    ''' </list>
  66.    ''' Allowing a programmer to use this attribute class without having the plugin installed in their Visual Studio projects.
  67.    ''' <para></para>
  68.    ''' Be aware that it is still necessary to use one of the mentioned projects to enable .NET functions export.
  69.    ''' </summary>
  70.    <AttributeUsage(AttributeTargets.Method, AllowMultiple:=False, Inherited:=False)>
  71.    Public NotInheritable Class DllExportAttribute : Inherits Attribute
  72.  
  73. #Region " Properties "
  74.  
  75.        ''' <summary>
  76.        ''' Gets or sets the calling convention required to call this C-exported function from unmanaged code.
  77.        ''' <para></para>
  78.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  79.        ''' like for other C/C++ programs (Microsoft Specific).
  80.        ''' <para></para>
  81.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  82.        ''' <para></para>
  83.        ''' </summary>
  84.        Public Property CallingConvention As CallingConvention = CallingConvention.Cdecl
  85.  
  86.        ''' <summary>
  87.        ''' Gets or sets the optional name for this C-exported function.
  88.        ''' </summary>
  89.        ''' <remarks>
  90.        ''' See also:
  91.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  92.        ''' Format of a C decorated name.
  93.        ''' </seealso>
  94.        ''' </remarks>
  95.        Public Property ExportName As String
  96.  
  97. #End Region
  98.  
  99. #Region " Constructors "
  100.  
  101.        ''' <summary>
  102.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  103.        ''' <para></para>
  104.        ''' Use this constructor only if you plan to use <b>DllExport</b> by 3F (<see href="https://github.com/3F/DllExport"/>),
  105.        ''' <para></para>
  106.        ''' otherwise, use <see cref="DllExportAttribute.New(String, CallingConvention)"/>
  107.        ''' to specify the export name and calling convention.
  108.        ''' </summary>
  109.        '''
  110.        ''' <param name="convention">
  111.        ''' The calling convention required to call this C-exported function.
  112.        ''' <para></para>
  113.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  114.        ''' like for other C/C++ programs (Microsoft Specific).
  115.        ''' <para></para>
  116.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  117.        ''' <para></para>
  118.        ''' </param>
  119.        '''
  120.        ''' <param name="exportName">
  121.        ''' The optional name for this C-exported function.
  122.        ''' See also:
  123.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  124.        ''' Format of a C decorated name.
  125.        ''' </seealso>
  126.        ''' </param>
  127.        Public Sub New(convention As CallingConvention, exportName As String)
  128.  
  129.            Me.CallingConvention = convention
  130.            Me.ExportName = exportName
  131.        End Sub
  132.  
  133.        ''' <summary>
  134.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  135.        ''' <para></para>
  136.        ''' Do not use this constructor if you plan to use <b>DllExport</b> by 3F (<see href="https://github.com/3F/DllExport"/>),
  137.        ''' <para></para>
  138.        ''' in that case use <see cref="DllExportAttribute.New(CallingConvention, String)"/>  
  139.        ''' to specify the export name and calling convention.
  140.        ''' </summary>
  141.        '''
  142.        ''' <param name="exportName">
  143.        ''' The optional name for this C-exported function.
  144.        ''' See also:
  145.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  146.        ''' Format of a C decorated name.
  147.        ''' </seealso>
  148.        ''' </param>
  149.        '''
  150.        ''' <param name="convention">
  151.        ''' The calling convention required to call this C-exported function.
  152.        ''' <para></para>
  153.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  154.        ''' like for other C/C++ programs (Microsoft Specific).
  155.        ''' <para></para>
  156.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  157.        ''' <para></para>
  158.        ''' </param>
  159.        Public Sub New(exportName As String, convention As CallingConvention)
  160.  
  161.            Me.ExportName = exportName
  162.            Me.CallingConvention = convention
  163.        End Sub
  164.  
  165.        ''' <summary>
  166.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  167.        ''' </summary>
  168.        '''
  169.        ''' <param name="exportName">
  170.        ''' The optional name for this C-exported function.
  171.        ''' See also:
  172.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  173.        ''' Format of a C decorated name.
  174.        ''' </seealso>
  175.        ''' </param>
  176.        Public Sub New(exportName As String)
  177.  
  178.            Me.New(exportName, CallingConvention.Cdecl)
  179.        End Sub
  180.  
  181.        ''' <summary>
  182.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  183.        ''' </summary>
  184.        '''
  185.        ''' <param name="convention">
  186.        ''' The calling convention required to call this C-exported function.
  187.        ''' <para></para>
  188.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  189.        ''' like for other C/C++ programs (Microsoft Specific).
  190.        ''' <para></para>
  191.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  192.        ''' <para></para>
  193.        ''' </param>
  194.        Public Sub New(convention As CallingConvention)
  195.  
  196.            Me.New(String.Empty, convention)
  197.        End Sub
  198.  
  199.        ''' <summary>
  200.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  201.        ''' </summary>
  202.        Public Sub New()
  203.        End Sub
  204.  
  205. #End Region
  206.  
  207.    End Class
  208.  
  209. #End Region
  210.  
  211. End Namespace



Ejemplos de modo de exportación:

VB.NET:
Código
  1. <DllExport(NameOf(MyStringFunction), CallingConvention.StdCall)>
  2. Public Shared Function MyStringFunction() As <MarshalAs(UnmanagedType.BStr)> String
  3.    Return "Hello World!"
  4. End Function

C#:
Código
  1. [DllExport(nameof(MyStringFunction), CallingConvention.StdCall)]
  2. [return: MarshalAs(UnmanagedType.BStr)]
  3. public static string MyStringFunction() {
  4.    return "Hello World!";
  5. }

Ejemplos de modo de importación:

Pascal Script:
Código:
function MyStringFunction(): Cardinal;
  external 'MyStringFunction@files:MyNetAPI.dll stdcall';
78  Programación / Programación General / Re: En muchos lenguajes, tempArray = array ¿es una referencia y les parece bien? en: 14 Enero 2025, 13:24 pm
TL/DR

Edit2: Es como si al copiar un archivo en Windows, este en vez de eso copiara un acceso directo. Joder, si quiero una copia porque voy a modificar una, dejame copiar tranquilo  >:(

Sin pretenderlo has descrito una peculiaridad muy fastidiosa de Windows que sucede con ciertos archivos executables. Si arrastras el archivo *.exe a otra ubicación, en vez de moverse o copiarse el archivo, se crea un acceso directo (*.lnk). El sistema no te avisa de este comportamiento al realizar la operación de arrastrar y soltar (mover/copiar), así que si no estás prestando atención y acto seguido borras permanentemente el archivo original pensando que se ha copiado el archivo real, pierdes el original y es un fastidio. Para solucionarlo basta con arrastrar el archivo manteniendo apretado el botón derecho del mouse, y al soltarlo seleccionar la opción de mover o copiar,o en su defecto CTRL+X|C y CTRL+V.

Esto he notado que sucede generalmente con algunos (pocos) archivos executables asociados a instalaciones, y supongo que será por como estos motores de instalación configuran ciertas claves en el registro que podrían alterar el comportamiento por defecto al arrastrar y soltar ese archivo .exe instalado.
No recuerdo ahora mismo si he visto que ocurriese esto con algún archivo protegido del sistema y que además no fuese un *.exe, sinceramente no lo recuerdo, pero creo que en mi caso no. Además, es que yo utilizo la cuenta "oculta" e integrada 'Administrador', y con UAC desactivado para olvidarme por completo de que para otras personas existen ciertas limitaciones a la hora de interactuar con archivos del sistema ...entre otras cosas xD.

Habría que informase en profundidad sobre el tema para entender mejor por que sucede esto.

Saludos.
79  Foros Generales / Dudas Generales / Re: Obtener Certificado digital con Vídeo Identificación sin tener que salir de casa alguien sabía de esto ? en: 13 Enero 2025, 19:40 pm
Pues gracias por el tiempo empleado en redactar todo eso. Creo que habría sido genial detallarlo en un video de Youtube así en modo explicativo, más que nada por que seguro que habrá miles de personas en España haciéndose preguntas, je!, aunque entiendo que la temática del canal es otra, pero bueno, yo doy la idea.

No se quien será el listillo que a ideado esa porquería de sistema pero vamos se a lucido a base de bien. Por ejemplo cuando te piden que pongas la cara centrada en el ovalo vertical de la pantalla de tu móvil a los pocos segundos te dicen que gires la cabeza a la derecha, y a los pocos segundos de eso te dice que vuelvas a mirar al centro, pero claro está si tu estas mirando a la derecha o tienes la visión periférica de superman o no puedes leerlo por lo que claro está no giras la cabeza esperando que de alguna manera con algún sonido o algo se te indique algo, pero no, simplemente a los pocos segundos si no vuelves a mirar de frente da error en la identificación y vuelta a empezar. Por lo que tienes que calcular muy bien los 2 o 3 segundos que quieren que permanezcas con la cara girada y luego regresar al frente, y después lo mismo con el lado izquierdo, y si, también pasa lo mismo cuando te piden que mires hacia arriba y hacia abajo. En fin que si no hay alguien a tu lado que te vaya indicando o leyendo lo que pone en la pantalla cuando tu miras para algún lado o para arriba o abajo pues las puedes pasar canutas si no tienes una visión periférica sobrehumana. ¿Que les habría costado dar un sonido que indique que ya puedes volver la cabeza, o reproducir una grabación al respecto?.

España, sin más. xD Para qué decir nada... luego me censuran... pero si esos sistemas los desarrollasen trabajadores de una empresa privada, no serían una *****.

Supongo que si realizas el proceso de verificación teniendo un espejo al lado será más intuitivo saber cuando girar la cabeza hacia el frente.

Un saludo!
80  Foros Generales / Foro Libre / Re: ¿La posible union de Windows y Linux por los chips de IA? en: 8 Enero 2025, 12:42 pm
¿Cual "unión"?. La noticia no habla de poder usar Windows y Linux simultáneamente como una fusión de sistemas operativos combinados y en igualdad de condiciones, sino que menciona la posibilidad de que Nvidia utilice y se favorezca de la tecnología Windows Subsystem for Linux (WSL) de Microsoft - la cual ya existe desde hace varios años y es accesible para cualquier usuario a partir de Windows 10 - para facilitar la coexistencia y compatibilidad entre ambos sistemas en un mismo entorno. Esto no es ninguna novedad revolucionaria...

Recordemos que WSL por si solo no tiene soporte nativo para entornos gráficos de escritorio, ni para ejecutar aplicaciones con interfaz gráfica. WSL trabaja bajo un entorno de terminal (línea de comandos) emulado, que traduce llamadas del sistema Linux al kernel de Windows, y con muchas limitaciones técnicas. Sin embargo, existe la posibilidad (hay tutoriales en Internet) de utilizar herramientas adicionales como un servidor X (VcXsrv o Xming) para redirigir la salida gráfica desde WSL y así poder utilizar un entorno de escritorio como el de GNOME en WSL.
En la versión 'WSL 2' se mejoró bastante la compatibilidad con Linux, ya que se utiliza una máquina virtual para poder ejecutar un kernel Linux real, y se añadió soporte para ejecutar aplicaciones con interfaz gráfica mediante la tecnología Windows Subsystem for Linux GUI (WSLg).

Windows y Linux son sistemas operativos con kernels distintos e incompatibles entre sí, y eso hace que sea técnicamente imposible que Windows ejecute Linux de forma nativa. Microsoft tiene que optar por emular su kernel, u optar por la virtualización.

Dicho esto, Linux nunca desaparecerá, por la sencilla razón de que las personas tienen diferentes necesidades y cada sistema operativo está diseñado para cubrir esas necesidades por separado. Hay cosas que resulta óptimo llevarlas a cabo en un sistema basado en Linux, y cosas que resultan óptimas en Windows, y esto no va a cambiar, por que son sistemas diferentes, y por esas diferencias las empresas y los usuarios domésticos seguirán eligiendo el sistema que les resulte óptimo para sus necesidades. Es absurdo discutir esto.

Atentamente,
Elektro.
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 ... 1253
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines