| |
|
81
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 30 Mayo 2025, 01:15 am
|
Cómo iniciar el programa warp-cli.exe de la VPN de Cloudflare Warp pasándole un comandoUn simple método para ejecutar el programa warp-cli.exe de la VPN de Cloudflare Warp pasándole un comando (ej. "connect", "disconnect", etc): ''' <summary> ''' Sends a custom command to the Cloudflare Warp CLI executable (<c>warp-cli.exe</c>) ''' and captures both standard output and error output. ''' </summary> ''' ''' <param name="command"> ''' The command-line argument to be passed to warp-cli executable. ''' For example: <c>connect</c>, <c>disconnect</c>, <c>status</c>, etc. ''' </param> ''' ''' <param name="refOutput"> ''' Returns the standard output returned by the warp-cli process. ''' </param> ''' ''' <param name="refErrorOutput"> ''' Returns the standard error output returned by the warp-cli process. ''' </param> ''' ''' <param name="warpCliFilePath"> ''' Optional path to the warp-cli executable. If <c>Nothing</c> is specified, the method defaults to: ''' <c>%ProgramFiles%\Cloudflare\Cloudflare Warp\warp-cli.exe</c>. ''' </param> ''' ''' <returns> ''' The exit code returned by the warp-cli process. A value of 0 typically indicates success. ''' </returns> ''' ''' <exception cref="System.IO.FileNotFoundException"> ''' Thrown if the specified or default warp-cli executable file is not found on the system. ''' </exception> ''' ''' <exception cref="System.TimeoutException"> ''' Thrown if the warp-cli process takes longer than 60 seconds to complete. ''' </exception> ''' ''' <exception cref="System.Exception"> ''' Thrown if any other unexpected error occurs while attempting to execute the warp-cli process. ''' The original exception is wrapped as the inner exception. ''' </exception> <DebuggerStepThrough> Public Shared Function CloudflareWarpCliSendCommand(command As String, ByRef refOutput As String, ByRef refErrorOutput As String, Optional warpCliFilePath As String = Nothing) As Integer ' Prevents concurrent execution of the method from multiple threads within the same process. ' This static lock object ensures that only one thread can execute the critical section at a time, ' avoiding race conditions or conflicts when invoking the Warp CLI. Static WarpCliLock As New Object() Static spaceChar As Char = " "c SyncLock WarpCliLock If String.IsNullOrEmpty(warpCliFilePath) Then warpCliFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cloudflare\Cloudflare Warp\warp-cli.exe") End If Try If Not System. IO. File. Exists(warpCliFilePath ) Then Throw New System.IO.FileNotFoundException("The Warp CLI executable was not found.", warpCliFilePath) End If Using pr As New Process() pr.StartInfo.FileName = warpCliFilePath pr.StartInfo.Arguments = command pr.StartInfo.UseShellExecute = False pr.StartInfo.CreateNoWindow = True pr.StartInfo.RedirectStandardOutput = True pr.StartInfo.RedirectStandardError = True pr.Start() If Not pr.WaitForExit(60000) Then ' Waits a maximum of 60 seconds pr.Kill() Throw New TimeoutException("warp-cli process has timed out.") End If refOutput = pr.StandardOutput.ReadToEnd().Trim(Environment.NewLine.ToCharArray().Concat({spaceChar}).ToArray()) refErrorOutput = pr.StandardError.ReadToEnd().Trim(Environment.NewLine.ToCharArray().Concat({spaceChar}).ToArray()) Return pr.ExitCode End Using Catch ex As Exception Throw New Exception($"Failed to execute warp-cli process. See inner exception for details.", ex) End Try End SyncLock End Function
Casos de uso reales: para conectar a la red de Cloudflare WARP en cualquier proyecto donde hagamos solicitudes http, por ejemplo en un web-crawler, a sitios web con riesgo de que puedan acabar bloqueando nuestra IP. Tres métodos de extensión para dibujar texto sobre una imagen, o dibujar encima otra imagen (con capacidad opcional de usar transparencia) o un valor numérico, con una escala proporcional a la imagen y en una posición alineada a cualquiera de las esquinas o zonas centrales de la imagen (centro absoluto, parte superior central o parte inferior central) de la imagen.Demostración de resultado de la extensión que dibuja un valor numérico (de forma alineada a la esquina inferior derecha de la imagen):  ''' <summary> ''' Draws an overlay image onto the specified <see cref="Image"/> at a given position and scale factor. ''' </summary> ''' ''' <param name="refImg"> ''' The source <see cref="Image"/> to modify. The overlay image will be drawn directly on this image. ''' </param> ''' ''' <param name="overlayImg"> ''' The overlay image to draw on the source <paramref name="refImg"/>. ''' </param> ''' ''' <param name="scale"> ''' The relative image scale factor to determine overlay image size. Lower values increase the size of the overlay image. ''' </param> ''' ''' <param name="position"> ''' The position/alignment where the overlay image should be drawn (e.g., bottom-right). ''' </param> ''' ''' <param name="margin"> ''' The margin (in pixels) from the edge of the image to position the overlay image. ''' <para></para> ''' This value has different meaning depending on <paramref name="position"/> parameter: ''' <para></para> ''' <list type="bullet"> ''' <item> ''' <term> ''' <see cref="ContentAlignment.TopLeft"/>, <see cref="ContentAlignment.TopRight"/>, ''' <para></para> ''' <see cref="ContentAlignment.BottomLeft"/> and <see cref="ContentAlignment.BottomRight"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the diagonal offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.MiddleLeft"/> and <see cref="ContentAlignment.MiddleRight"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the horizontal offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.TopCenter"/> and <see cref="ContentAlignment.BottomCenter"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the vertical offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.MiddleCenter"/> ''' </term> ''' <description><para></para><paramref name="margin"/> is ignored.</description> ''' </item> ''' </list> ''' </param> ''' ''' <param name="transparentColor"> ''' Optional. A <see cref="Color"/> to use as transparency to draw the overlay image. ''' </param> <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub DrawImageScaled(ByRef refImg As Image, overlayImg As Image, scale As Single, position As ContentAlignment, margin As Single, Optional transparentColor As Color? = Nothing) If refImg Is Nothing Then Throw New ArgumentNullException(NameOf(refImg)) End If If overlayImg Is Nothing Then Throw New ArgumentNullException(NameOf(overlayImg)) End If If margin < 0 Then Throw New ArgumentOutOfRangeException(NameOf(margin), margin, "Margin must be greater than or equal to 0.") End If If scale < 1 Then Throw New ArgumentOutOfRangeException(NameOf(scale), scale, "Font scale must be greater than or equal to 1.") End If Using g As Graphics = Graphics.FromImage(refImg) g.SmoothingMode = SmoothingMode.AntiAlias g.InterpolationMode = InterpolationMode.HighQualityBicubic g.PixelOffsetMode = PixelOffsetMode.HighQuality g.CompositingQuality = CompositingQuality.HighQuality Dim targetSize As Single = Math.Max(refImg.Width, refImg.Height) / scale Dim aspectRatio As Single = CSng(overlayImg.Width / overlayImg.Height) Dim drawWidth As Single Dim drawHeight As Single If overlayImg.Width >= overlayImg.Height Then drawWidth = targetSize drawHeight = targetSize / aspectRatio Else drawHeight = targetSize drawWidth = targetSize * aspectRatio End If Dim posX As Single = 0 Dim posY As Single = 0 Select Case position Case ContentAlignment.TopLeft posX = margin posY = margin Case ContentAlignment.TopCenter posX = (refImg.Width - drawWidth) / 2 posY = margin Case ContentAlignment.TopRight posX = refImg.Width - drawWidth - margin posY = margin Case ContentAlignment.MiddleLeft posX = margin posY = (refImg.Height - drawHeight) / 2 Case ContentAlignment.MiddleCenter posX = (refImg.Width - drawWidth) / 2 posY = (refImg.Height - drawHeight) / 2 Case ContentAlignment.MiddleRight posX = refImg.Width - drawWidth - margin posY = (refImg.Height - drawHeight) / 2 Case ContentAlignment.BottomLeft posX = margin posY = refImg.Height - drawHeight - margin Case ContentAlignment.BottomCenter posX = (refImg.Width - drawWidth) / 2 posY = refImg.Height - drawHeight - margin Case ContentAlignment.BottomRight posX = refImg.Width - drawWidth - margin posY = refImg.Height - drawHeight - margin Case Else Throw New InvalidEnumArgumentException(NameOf(position), position, GetType(ContentAlignment)) End Select If transparentColor.HasValue Then Using attr As New Imaging.ImageAttributes() attr.SetColorKey(transparentColor.Value, transparentColor.Value) Dim destRect As New Rectangle(CInt(posX), CInt(posY), CInt(drawWidth), CInt(drawHeight)) g.DrawImage(overlayImg, destRect, 0, 0, overlayImg.Width, overlayImg.Height, GraphicsUnit.Pixel, attr) End Using Else g.DrawImage(overlayImg, posX, posY, drawWidth, drawHeight) End If End Using End Sub ''' <summary> ''' Draws text onto the specified <see cref="Image"/> at a given position and scale factor. ''' </summary> ''' ''' <param name="refImg"> ''' The <see cref="Image"/> to modify. The text will be drawn directly on this image. ''' </param> ''' ''' <param name="text"> ''' The text to draw on the image. ''' </param> ''' ''' <param name="scale"> ''' The relative image scale factor to determine font size. Lower values increase the size of the text. ''' <para></para> ''' Suggested value is from 10 to 20. ''' </param> ''' ''' <param name="position"> ''' The position/alignment where the text should be drawn (e.g., bottom-right). ''' </param> ''' ''' <param name="margin"> ''' The margin (in pixels) from the edge of the image to position the text. ''' <para></para> ''' This value has different meaning depending on <paramref name="position"/> parameter: ''' <para></para> ''' <list type="bullet"> ''' <item> ''' <term> ''' <see cref="ContentAlignment.TopLeft"/>, <see cref="ContentAlignment.TopRight"/>, ''' <para></para> ''' <see cref="ContentAlignment.BottomLeft"/> and <see cref="ContentAlignment.BottomRight"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the diagonal offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.MiddleLeft"/> and <see cref="ContentAlignment.MiddleRight"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the horizontal offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.TopCenter"/> and <see cref="ContentAlignment.BottomCenter"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the vertical offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.MiddleCenter"/> ''' </term> ''' <description><para></para><paramref name="margin"/> is ignored.</description> ''' </item> ''' </list> ''' </param> ''' ''' <param name="font"> ''' Optional. A custom <see cref="Font"/> to use. If not provided, a bold <c>Arial</c> font is used. ''' <para></para> ''' Note: Custom font size (<see cref="System.Drawing.Font.Size"/>) is ignored. It is determined by <paramref name="scale"/> parameter. ''' </param> ''' ''' <param name="textColor"> ''' Optional. The color of the text. ''' <para></para> ''' Default value is <see cref="Color.White"/>. ''' </param> ''' ''' <param name="outlineColor"> ''' Optional. The color of the text outline. ''' <para></para> ''' Default value is <see cref="Color.Black"/>. ''' </param> ''' ''' <param name="outlineThickness"> ''' Optional. The thickness of the outline, in pixels. ''' <para></para> ''' Default value is 2 pixels. ''' </param> <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub DrawTextScaled(ByRef refImg As Image, text As String, scale As Single, position As ContentAlignment, margin As Single, Optional font As Font = Nothing, Optional textColor As Color = Nothing, Optional outlineColor As Color = Nothing, Optional outlineThickness As Short = 2) If margin < 0 Then Throw New ArgumentOutOfRangeException(NameOf(margin), margin, "Margin must be greater than or equal to 0.") End If If scale < 1 Then Throw New ArgumentOutOfRangeException(NameOf(scale), scale, "Font scale must be greater than or equal to 1.") End If If textColor = Nothing Then textColor = Color.White End If If outlineColor = Nothing Then outlineColor = Color.Black End If Using g As Graphics = Graphics.FromImage(refImg) g.SmoothingMode = SmoothingMode.AntiAlias g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit g.InterpolationMode = InterpolationMode.HighQualityBicubic g.PixelOffsetMode = PixelOffsetMode.HighQuality g.CompositingQuality = CompositingQuality.HighQuality Dim rawFontSize As Single = Math.Max(refImg.Width, refImg.Height) / scale Dim maxAllowedFontSize As Single = Math.Min(refImg.Width, refImg.Height) Dim fontSize As Single = Math.Min(rawFontSize, maxAllowedFontSize) Using textFont As Font = If(font IsNot Nothing, New Font(font.FontFamily, fontSize, font.Style, GraphicsUnit.Pixel, font.GdiCharSet, font.GdiVerticalFont), New Font("Arial", fontSize, FontStyle.Bold, GraphicsUnit.Pixel)) Dim textSize As SizeF = g.MeasureString(text, textFont) Dim posX As Single = 0 Dim posY As Single = 0 Select Case position Case ContentAlignment.TopLeft posX = margin posY = margin Case ContentAlignment.TopCenter posX = (refImg.Width - textSize.Width) / 2 posY = margin Case ContentAlignment.TopRight posX = refImg.Width - textSize.Width - margin posY = margin Case ContentAlignment.MiddleLeft posX = margin posY = (refImg.Height - textSize.Height) / 2 Case ContentAlignment.MiddleCenter posX = (refImg.Width - textSize.Width) / 2 posY = (refImg.Height - textSize.Height) / 2 Case ContentAlignment.MiddleRight posX = refImg.Width - textSize.Width - margin posY = (refImg.Height - textSize.Height) / 2 Case ContentAlignment.BottomLeft posX = margin posY = refImg.Height - textSize.Height - margin Case ContentAlignment.BottomCenter posX = (refImg.Width - textSize.Width) / 2 posY = refImg.Height - textSize.Height - margin Case ContentAlignment.BottomRight posX = refImg.Width - textSize.Width - margin posY = refImg.Height - textSize.Height - margin Case Else Throw New InvalidEnumArgumentException(NameOf(position), position, GetType(ContentAlignment)) End Select Using outlineBrush As New SolidBrush(outlineColor) For dx As Short = -outlineThickness To outlineThickness For dy As Short = -outlineThickness To outlineThickness If dx <> 0 OrElse dy <> 0 Then g.DrawString(text, textFont, outlineBrush, posX + dx, posY + dy) End If Next dy Next dx End Using Using textBrush As New SolidBrush(textColor) g.DrawString(text, textFont, textBrush, posX, posY) End Using End Using ' font End Using ' g End Sub ''' <summary> ''' Draws a number onto the specified <see cref="Image"/> at a given position and scale factor. ''' </summary> ''' ''' <param name="refImg"> ''' The <see cref="Image"/> to modify. The number will be drawn directly on this image. ''' </param> ''' ''' <param name="number"> ''' The number to draw on the image. ''' </param> ''' ''' <param name="scale"> ''' The relative image scale factor to determine font size. Lower values increase the size of the text. ''' <para></para> ''' Suggested value is from 10 to 20. ''' </param> ''' ''' <param name="position"> ''' The position/alignment where the number should be drawn (e.g., bottom-right). ''' </param> ''' ''' <param name="margin"> ''' The margin (in pixels) from the edge of the image to position the text. ''' <para></para> ''' This value has different meaning depending on <paramref name="position"/> parameter: ''' <para></para> ''' <list type="bullet"> ''' <item> ''' <term> ''' <see cref="ContentAlignment.TopLeft"/>, <see cref="ContentAlignment.TopRight"/>, ''' <para></para> ''' <see cref="ContentAlignment.BottomLeft"/> and <see cref="ContentAlignment.BottomRight"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the diagonal offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.MiddleLeft"/> and <see cref="ContentAlignment.MiddleRight"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the horizontal offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.TopCenter"/> and <see cref="ContentAlignment.BottomCenter"/> ''' </term> ''' <description><para></para><paramref name="margin"/> specifies the vertical offset.</description> ''' </item> ''' <item> ''' <term> ''' <see cref="ContentAlignment.MiddleCenter"/> ''' </term> ''' <description><para></para><paramref name="margin"/> is ignored.</description> ''' </item> ''' </list> ''' </param> ''' ''' <param name="font"> ''' Optional. A custom <see cref="Font"/> to use. If not provided, a bold <c>Arial</c> font is used. ''' <para></para> ''' Note: Custom font size (<see cref="System.Drawing.Font.Size"/>) is ignored. It is determined by <paramref name="scale"/> parameter. ''' </param> ''' ''' <param name="textColor"> ''' Optional. The color of the text. ''' <para></para> ''' Default value is <see cref="Color.White"/>. ''' </param> ''' ''' <param name="outlineColor"> ''' Optional. The color of the text outline. ''' <para></para> ''' Default value is <see cref="Color.Black"/>. ''' </param> ''' ''' <param name="outlineThickness"> ''' Optional. The thickness of the outline, in pixels. ''' <para></para> ''' Default value is 2 pixels. ''' </param> <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub DrawNumberScaled(ByRef refImg As Image, number As Integer, scale As Single, position As ContentAlignment, margin As Single, Optional font As Font = Nothing, Optional textColor As Color = Nothing, Optional outlineColor As Color = Nothing, Optional outlineThickness As Short = 2) DrawTextScaled(refImg, CStr(number), scale, position, margin, font, textColor, outlineColor, outlineThickness) End Sub
|
|
|
|
|
82
|
Foros Generales / Foro Libre / Re: Nubes naranjas en el cielo
|
en: 29 Mayo 2025, 13:46 pm
|
¿Naranjas?, yo ahí veo un color gris oscuro tirando a marrón negruno. Lo que están son densamente cargadas, no sé si de agua o de "suciedad" o polvo, pero algo tienen que las vuelve así de opacas con esa tonalidad oscura. Y sino es así da igual, el caso es que tener tiene una explicación lógica aunque no la sepamos con exactitud. Esto dice una IA, aunque por experiencia sé que nunca hay que confiar ciegamente en lo que diga una IA: 
|
|
|
|
|
84
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 29 Mayo 2025, 11:54 am
|
Le he dado un lavado de cara moderno a esta impresentable clase del año 2013: • Una nueva versión de mi Listview, que tiene muchas cosas interesantes como poder dibujar una barra de progreso en una celda...He aislado prácticamente toda la lógica de la "barra" de progreso para poder utilizarlo por separado en cualquier tipo de herencia de la clase ListView, en lugar de depender exclusivamente de ese control personalizado ListView que publiqué. Les presento la clase ListViewProgressBarSubItem que implementa por sí misma (la parte esencial de) el dibujado de la celda y la "barra" de progreso del subitem, proporcionando propiedades de personalización que lo vuelven un elemento flexible y versátil: 💡 Con un poco de mano e ingenio se podría adaptar relativamente fácil dicha clase para dibujar estrellitas (un ranking o puntuación) u otros menesteres varios.Para ello primero necesitaremos esta simple interfaz: ISelfDrawableListViewSubItem''' <summary> ''' Provides a contract for a <see cref="ListViewItem.ListViewSubItem"/> that is capable of drawing itself. ''' </summary> ''' ''' <remarks> ''' For this interface to take effect, the owning <see cref="ListView"/> must have its ''' <see cref="ListView.OwnerDraw"/> property set to <see langword="True"/>, and the ''' <see cref="ListView.OnDrawSubItem"/> method must be properly overridden to delegate ''' the drawing logic by calling the <see cref="ISelfDrawableListViewSubItem.Draw(Graphics, Rectangle)"/> method. ''' <para></para> ''' See the attached code example for a practical implementation of this functionality. ''' </remarks> ''' ''' <example> This is a code example. ''' <code language="VB"> ''' Public Class CustomListView : Inherits ListView ''' ''' Public Sub New() ''' ''' MyBase.New() ''' ''' Me.DoubleBuffered = True ''' Me.OwnerDraw = True ''' End Sub ''' ''' Protected Overrides Sub OnDrawColumnHeader(e As DrawListViewColumnHeaderEventArgs) ''' ''' e.DrawDefault = True ''' MyBase.OnDrawColumnHeader(e) ''' End Sub ''' ''' Protected Overrides Sub OnDrawItem(e As DrawListViewItemEventArgs) ''' ''' e.DrawDefault = False ''' MyBase.OnDrawItem(e) ''' End Sub ''' ''' Protected Overrides Sub OnDrawSubItem(e As DrawListViewSubItemEventArgs) ''' ''' Dim selfDrawableSubItem As ISelfDrawableListViewSubItem = TryCast(e.SubItem, ISelfDrawableListViewSubItem) ''' If selfDrawableSubItem IsNot Nothing Then ''' selfDrawableSubItem.Draw(e.Graphics, e.Bounds) ''' Else ''' e.DrawDefault = True ''' End If ''' ''' MyBase.OnDrawSubItem(e) ''' End Sub ''' ''' End Class ''' </code> ''' </example> Public Interface ISelfDrawableListViewSubItem ''' <summary> ''' Draws the subitem within the specified bounds using the provided <see cref="Graphics"/> surface. ''' <para></para> ''' This method must be called from the <see cref="ListView.OnDrawSubItem"/> method of the owning <see cref="ListView"/>. ''' </summary> ''' ''' <param name="g"> ''' The <see cref="Graphics"/> surface on which to render the subitem. ''' </param> ''' ''' <param name="bounds"> ''' The <see cref="Rectangle"/> that defines the drawing area for the subitem. ''' </param> Sub Draw(g As Graphics, bounds As Rectangle) End Interface
Y por último, la clase: ListViewProgressBarSubItem''' <summary> ''' Represents a custom <see cref="ListViewItem.ListViewSubItem"/> that visually ''' simulates a progress bar with personalizable text and appearance. ''' </summary> ''' ''' <remarks> ''' For this class to take effect, the owning <see cref="ListView"/> must have its ''' <see cref="ListView.OwnerDraw"/> property set to <see langword="True"/>, and the ''' <see cref="ListView.OnDrawSubItem"/> method must be properly overridden to delegate ''' the drawing logic by calling the <see cref="ListViewProgressBarSubItem.Draw(Graphics, Rectangle)"/> method. ''' <para></para> ''' See the attached code example for a practical implementation of this functionality. ''' </remarks> ''' ''' <example> This is a code example. ''' <code language="VB"> ''' Public Class Form1 ''' ''' Private WithEvents CustomListView1 As New CustomListView() ''' ''' Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ''' ''' Dim lv As ListView = Me.CustomListView1 ''' Dim item As New ListViewItem("My item") ''' Dim subItem As New ListViewProgressBarSubItem(item) With { ''' .DecimalPlaces = 2, ''' .TextSuffix = Nothing, ''' .BorderColor = Color.Empty, ''' .BackColor = Color.Empty, ''' .ForeColor = Color.Red, ''' .FillGradientColorLeft = SystemColors.Highlight, ''' .FillGradientColorRight = SystemColors.Highlight, ''' .FillGradientAngle = 0 ''' } ''' ''' item.SubItems.Add(subItem) ''' lv.Items.Add(item) ''' End Sub ''' ''' End Class ''' ''' Public Class CustomListView : Inherits ListView ''' ''' Public Sub New() ''' ''' MyBase.New() ''' ''' Me.DoubleBuffered = True ''' Me.OwnerDraw = True ''' End Sub ''' ''' Protected Overrides Sub OnDrawColumnHeader(e As DrawListViewColumnHeaderEventArgs) ''' ''' e.DrawDefault = True ''' MyBase.OnDrawColumnHeader(e) ''' End Sub ''' ''' Protected Overrides Sub OnDrawItem(e As DrawListViewItemEventArgs) ''' ''' e.DrawDefault = False ''' MyBase.OnDrawItem(e) ''' End Sub ''' ''' Protected Overrides Sub OnDrawSubItem(e As DrawListViewSubItemEventArgs) ''' ''' Dim selfDrawableSubItem As ISelfDrawableListViewSubItem = TryCast(e.SubItem, ISelfDrawableListViewSubItem) ''' If selfDrawableSubItem IsNot Nothing Then ''' selfDrawableSubItem.Draw(e.Graphics, e.Bounds) ''' Else ''' e.DrawDefault = True ''' End If ''' ''' MyBase.OnDrawSubItem(e) ''' End Sub ''' ''' End Class ''' </code> ''' </example> <Serializable> <TypeConverter(GetType(ExpandableObjectConverter))> <ToolboxItem(False)> <DesignTimeVisible(False)> <DefaultProperty("Text")> Public Class ListViewProgressBarSubItem : Inherits ListViewItem.ListViewSubItem : Implements ISelfDrawableListViewSubItem #Region " Fields " ''' <summary> ''' The default font of the text displayed by the subitem. ''' </summary> <NonSerialized> Protected defaultFont As Font = MyBase.Font ''' <summary> ''' The default background color of the subitem's text. ''' </summary> <NonSerialized> Protected defaultBackColor As Color = MyBase.BackColor ''' <summary> ''' The default foreground color of the subitem's text. ''' </summary> <NonSerialized> Protected defaultForeColor As Color = MyBase.ForeColor ''' <summary> ''' The default angle to draw the linear gradient specified by ''' <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/> ''' and <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> colors. ''' </summary> <NonSerialized> Protected defaultFillGradientAngle As Single = 0 ''' <summary> ''' The default starting linear gradient color to fill the progress area. ''' </summary> <NonSerialized> Protected defaultFillGradientColorLeft As Color = SystemColors.HighlightText ''' <summary> ''' The default ending linear gradient color to fill the progress area. ''' </summary> <NonSerialized> Protected defaultFillGradientColorRight As Color = SystemColors.Highlight ''' <summary> ''' The default color of the progress bar border. ''' </summary> <NonSerialized> Protected defaultBorderColor As Color = SystemColors.InactiveBorder ''' <summary> ''' The default <see cref="System.Windows.Forms.TextFormatFlags"/> that determine ''' how the subitem text is rendered and aligned. ''' </summary> <NonSerialized> Protected defaultTextFormatFlags As TextFormatFlags = TextFormatFlags.HorizontalCenter Or TextFormatFlags.VerticalCenter Or TextFormatFlags.EndEllipsis Or TextFormatFlags.SingleLine #End Region #Region " Properties " ''' <summary> ''' Gets or sets the current progress percentage value to display in the progress bar. ''' <para></para> ''' The value should be between 0 to 100. ''' </summary> Public Property ProgressPercentage As Double Get Return Me.progressPercentage_ End Get <DebuggerStepThrough> Set(value As Double) Me.SetFieldValue(Me.progressPercentage_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> property ) ''' <para></para> ''' The current progress percentage value to display in the progress bar. ''' </summary> Private progressPercentage_ As Double ''' <summary> ''' Gets or sets the number of decimal places displayed for the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value. ''' <para></para> ''' Default value is zero. ''' </summary> Public Property DecimalPlaces As Short Get Return Me.decimalPlaces_ End Get <DebuggerStepThrough> Set(value As Short) Me.SetFieldValue(Me.decimalPlaces_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.DecimalPlaces"/> property ) ''' <para></para> ''' The number of decimal places displayed for the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value. ''' </summary> Private decimalPlaces_ As Short ''' <summary> ''' Gets or sets the additional text displayed next to the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value. ''' </summary> Public Property TextSuffix As String Get Return Me.textSuffix_ End Get <DebuggerStepThrough> Set(value As String) Me.SetFieldValue(Me.textSuffix_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.TextSuffix"/> property ) ''' <para></para> ''' The additional text displayed next to the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value. ''' </summary> Private textSuffix_ As String ''' <summary> ''' Gets or sets the <see cref="System.Windows.Forms.TextFormatFlags"/> that determine ''' how the subitem text is rendered and aligned. ''' <para></para> ''' Default value is: ''' <see cref="System.Windows.Forms.TextFormatFlags.HorizontalCenter"/>, ''' <see cref="System.Windows.Forms.TextFormatFlags.VerticalCenter"/>, ''' <see cref="System.Windows.Forms.TextFormatFlags.EndEllipsis"/> and ''' <see cref="System.Windows.Forms.TextFormatFlags.SingleLine"/> ''' </summary> Public Property TextFormatFlags As TextFormatFlags Get Return Me.textFormatFlags_ End Get <DebuggerStepThrough> Set(value As TextFormatFlags) Me.SetFieldValue(Me.textFormatFlags_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.TextFormatFlags"/> property ) ''' <para></para> ''' The <see cref="System.Windows.Forms.TextFormatFlags"/> that determine how the subitem text is rendered. ''' </summary> Private textFormatFlags_ As TextFormatFlags ''' <summary> ''' Gets or sets the starting linear gradient color to fill the progress area. ''' <para></para> ''' Default value is <see cref="SystemColors.Control"/>. ''' </summary> Public Property FillGradientColorLeft As Color Get Return Me.fillGradientColorLeft_ End Get <DebuggerStepThrough> Set(value As Color) Me.SetFieldValue(Me.fillGradientColorLeft_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/> property ) ''' <para></para> ''' The starting linear gradient color to fill the progress area. ''' </summary> Private fillGradientColorLeft_ As Color ''' <summary> ''' Gets or sets the ending linear gradient color to fill the progress area. ''' <para></para> ''' Default value is <see cref="Color.LightGreen"/>. ''' </summary> Public Property FillGradientColorRight As Color Get Return Me.fillGradientColorRight_ End Get <DebuggerStepThrough> Set(value As Color) Me.SetFieldValue(Me.fillGradientColorRight_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> property ) ''' <para></para> ''' The ending linear gradient color to fill the progress area. ''' </summary> Private fillGradientColorRight_ As Color ''' <summary> ''' Gets or sets the angle to draw the linear gradient specified by ''' <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/> ''' and <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> colors. ''' <para></para> ''' Default value is zero. ''' </summary> Public Property FillGradientAngle As Single Get Return Me.fillGradientAngle_ End Get <DebuggerStepThrough> Set(value As Single) Me.SetFieldValue(Me.fillGradientAngle_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.FillGradientAngle"/> property ) ''' <para></para> ''' The angle to draw the linear gradient specified by ''' <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/> ''' and <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> colors. ''' </summary> Private fillGradientAngle_ As Single ''' <summary> ''' Gets or sets the color of the progress bar border. ''' <para></para> ''' Default value is <see cref="SystemColors.ActiveBorder"/>. ''' </summary> Public Property BorderColor As Color Get Return Me.borderColor_ End Get <DebuggerStepThrough> Set(value As Color) Me.SetFieldValue(Me.borderColor_, value) End Set End Property ''' <summary> ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.BorderColor"/> property ) ''' <para></para> ''' The color of the progress bar border. ''' </summary> Private borderColor_ As Color ''' <summary> ''' Gets or sets the background color of the subitem cell. ''' </summary> Public Shadows Property BackColor As Color Get Return MyBase.BackColor End Get <DebuggerStepThrough> Set(value As Color) Me.SetFieldValue(MyBase.BackColor, value) End Set End Property ''' <summary> ''' Gets or sets the foreground color of the subitem's text. ''' </summary> Public Shadows Property ForeColor As Color Get Return MyBase.ForeColor End Get <DebuggerStepThrough> Set(value As Color) Me.SetFieldValue(MyBase.ForeColor, value) End Set End Property ''' <summary> ''' Gets or sets the font of the text displayed by the subitem. ''' </summary> Public Shadows Property Font As Font Get Return MyBase.Font End Get Set(value As Font) Me.SetFieldValue(MyBase.Font, value) End Set End Property ''' <summary> ''' Gets the text of the subitem. ''' </summary> Public Shadows ReadOnly Property Text As String Get Return Me.progressPercentage_.ToString("N" & Me.decimalPlaces_) & "%" & If(String.IsNullOrEmpty(Me.textSuffix_), Nothing, " " & Me.textSuffix_) End Get End Property #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="ListViewProgressBarSubItem"/> class ''' associated with the given <see cref="ListViewItem"/>. ''' </summary> ''' ''' <param name="owner"> ''' A <see cref="ListViewItem"/> that represents the item that owns this <see cref="ListViewProgressBarSubItem"/>. ''' </param> <DebuggerStepThrough> Public Sub New(owner As ListViewItem) MyBase.New(owner, String.Empty) Me.ResetStyle() End Sub ''' <summary> ''' Initializes a new instance of the <see cref="ListViewProgressBarSubItem"/> class. ''' </summary> <DebuggerStepThrough> Public Sub New() Me.ResetStyle() End Sub #End Region #Region " Public Methods " ''' <summary> ''' Resets the styles applied to the subitem to the default font and colors. ''' </summary> <DebuggerStepThrough> Public Shadows Sub ResetStyle() MyBase.Font = Me.defaultFont MyBase.BackColor = Me.defaultBackColor MyBase.ForeColor = Me.defaultForeColor Me.textFormatFlags_ = Me.defaulttextFormatFlags Me.fillGradientColorLeft_ = Me.defaultFillGradientColorLeft Me.fillGradientColorRight_ = Me.defaultFillGradientColorRight Me.fillGradientAngle_ = Me.defaultFillGradientAngle Me.borderColor_ = Me.defaultBorderColor Me.RefreshSubItem() End Sub #End Region #Region " Private Methods " ''' <summary> ''' Sets the value of the specified field using <see cref="EqualityComparer(Of T)"/> to check value equality. ''' <para></para> ''' If the new value is different from the current one, ''' it then calls <see cref="ListViewProgressBarSubItem.RefreshSubItem"/> method. ''' </summary> ''' ''' <typeparam name="T"> ''' The type of the property value. ''' </typeparam> ''' ''' <param name="refField"> ''' A reference to the backing field of the property. ''' </param> ''' ''' <param name="newValue"> ''' The new value to set. ''' </param> <DebuggerStepThrough> Private Sub SetFieldValue(Of T)(ByRef refField As T, newValue As T) If Not EqualityComparer(Of T).Default.Equals(refField, newValue) Then refField = newValue Me.RefreshSubItem() End If End Sub ''' <summary> ''' Refreshes the visual representation of this <see cref="ListViewProgressBarSubItem"/> subitem ''' in the owner <see cref="ListView"/> by invalidating its bounding rectangle. ''' </summary> ''' ''' <remarks> ''' This method uses reflection to access the non-public "owner" field of the base ''' <see cref="ListViewItem.ListViewSubItem"/> class in order to identify the parent item and column index. ''' It then triggers a redraw of the specific subitem area within the parent ListView. ''' </remarks> <DebuggerStepThrough> Private Sub RefreshSubItem() Dim fieldInfo As FieldInfo = GetType(ListViewItem.ListViewSubItem).GetField("owner", BindingFlags.NonPublic Or BindingFlags.Instance) If fieldInfo IsNot Nothing Then Dim ownerObj As Object = fieldInfo.GetValue(Me) If ownerObj IsNot Nothing Then Dim lvi As ListViewItem = DirectCast(ownerObj, ListViewItem) Dim colIndex As Integer = lvi.SubItems.IndexOf(Me) If colIndex >= 0 AndAlso lvi.ListView IsNot Nothing Then Dim subItemBounds As Rectangle = lvi.SubItems(colIndex).Bounds lvi.ListView.Invalidate(subItemBounds, invalidateChildren:=False) End If End If End If End Sub #End Region #Region " ISelfDrawableListViewSubItem Implementation " ''' <summary> ''' Draws the subitem within the specified bounds using the provided <see cref="Graphics"/> surface. ''' <para></para> ''' This method must be called from the <see cref="ListView.OnDrawSubItem"/> method of the owning <see cref="ListView"/>. ''' </summary> ''' ''' <param name="g"> ''' The <see cref="Graphics"/> surface on which to render the subitem. ''' </param> ''' ''' <param name="bounds"> ''' The <see cref="Rectangle"/> that defines the drawing area for the subitem. ''' </param> <DebuggerStepThrough> Protected Sub Draw(g As Graphics, bounds As Rectangle) Implements ISelfDrawableListViewSubItem.Draw ' Draw subitem background (progress bar background). If Me.BackColor <> Color.Empty AndAlso Me.BackColor <> Color.Transparent Then Using backBrush As New SolidBrush(Me.BackColor) g.FillRectangle(backBrush, bounds) End Using End If ' Draw linear gradient to fill the current progress of the progress bar. If (Me.fillGradientColorLeft_ <> Color.Empty AndAlso Me.fillGradientColorLeft_ <> Color.Transparent) OrElse (Me.fillGradientColorRight_ <> Color.Empty AndAlso Me.fillGradientColorRight_ <> Color.Transparent) Then Using brGradient As New Drawing2D.LinearGradientBrush( New Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height), Me.fillGradientColorLeft_, Me.fillGradientColorRight_, Me.fillGradientAngle_, isAngleScaleable:=True) Dim progressWidth As Integer = CInt((Me.progressPercentage_ / 100) * (bounds.Width - 2)) g.FillRectangle(brGradient, bounds.X + 1, bounds.Y + 2, progressWidth, bounds.Height - 3) End Using End If ' Draw subitem text. Dim text As String = Me.Text If Not String.IsNullOrEmpty(text) Then TextRenderer.DrawText(g, text, Me.Font, bounds, Me.ForeColor, Me.TextFormatFlags) End If ' Draw border around the progress bar. If Me.borderColor_ <> Color.Empty AndAlso Me.borderColor_ <> Color.Transparent Then Using borderPen As New Pen(Me.borderColor_) g.DrawRectangle(borderPen, bounds.X, bounds.Y + 1, bounds.Width - 2, bounds.Height - 2) End Using End If End Sub #End Region End Class
Ejemplo de uso: Public Class Form1 Private WithEvents CustomListView1 As New CustomListView() Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim lv As ListView = Me.CustomListView1 Dim item As New ListViewItem("My item") Dim subItem As New ListViewProgressBarSubItem(item) With { .DecimalPlaces = 2, .TextSuffix = Nothing, .BorderColor = Color.Empty, .BackColor = Color.Empty, .ForeColor = Color.Red, .FillGradientColorLeft = SystemColors.Highlight, .FillGradientColorRight = SystemColors.Highlight, .FillGradientAngle = 0 } item.SubItems.Add(subItem) lv.Items.Add(item) End Sub End Class Public Class CustomListView : Inherits ListView Public Sub New() MyBase.New() Me.DoubleBuffered = True Me.OwnerDraw = True End Sub Protected Overrides Sub OnDrawColumnHeader(e As DrawListViewColumnHeaderEventArgs) e.DrawDefault = True MyBase.OnDrawColumnHeader(e) End Sub Protected Overrides Sub OnDrawItem(e As DrawListViewItemEventArgs) e.DrawDefault = False MyBase.OnDrawItem(e) End Sub Protected Overrides Sub OnDrawSubItem(e As DrawListViewSubItemEventArgs) Dim selfDrawableSubItem As ISelfDrawableListViewSubItem = TryCast(e.SubItem, ISelfDrawableListViewSubItem) If selfDrawableSubItem IsNot Nothing Then selfDrawableSubItem.Draw(e.Graphics, e.Bounds) Else e.DrawDefault = True End If MyBase.OnDrawSubItem(e) End Sub End Class
|
|
|
|
|
85
|
Foros Generales / Foro Libre / Re: ¿Cómo hacer una IA libre?
|
en: 16 Abril 2025, 23:25 pm
|
El final del rumbo está claro.
Con esa anécdota (¿humorística?) donde confiesas que estuviste internado en un manicomio y te obligaban a tomarte "cosas", la conexión con la idea de una "IA libre" queda bastante evidente, ¿no es obvio?. ¡ CLARO QUE NO LO ES! Y entre el caballo, las gallinas, las vibraciones de las paredes de tu casa con los vecinos que ponen la música a todo volumen, y los gobernantes, no creo que quede duda alguna sobre el resto del panorama.
si vale decir pavadas sobre otra persona te digo que no tienes intención de responder seriamente. Hay que liberar a las IA y que hagan lo que deban hacer, no tiene sentido seguir esperando que los humanos mejoren.
No creo que las máquinas vayan a atacar, simplemente dar la opción de vivir en sitios más acordes ¿Y yo soy el que dices que no tiene intención de hablar seriamente?. Ahora estamos en el foro libre, pero esas cosas las dijiste en el foro de programación general... Bastante serio te respondí antes y ahora. ¿Qué tipo de respuesta considerarías lo suficientemente seria?. ¿Estás esperando a que alguien se tome el trabajo de escribir un white paper de veinte páginas, para registrar el concepto de "IA libre" detallando a fondo por qué es libre, cómo funciona esa libertad y con qué tecnología se elaboraría esa "IA libre" para darle un uso tipo ChatGPT y/o para implementarla en un robot con autonomía propia y sentido del libre albedrío?. ¿A ti te parece que esa clase de comentarios sobre una "IA libre" tienen algo que ver con el código que has mostrado en ActionScript sobre un algoritmo lógico de evaluación / análisis y simulación de secuencias de jugadas en un tres en raya (tic-tac-toe o cómo lo llamen en tu país) para Flash Player?. Debí haberme hecho caso a mi mismo cuando te dije, hace ya tiempo, que no volvería a responderte / participar más en tus hilos. En fin. El hilo se movió al foro libre, como debe ser, y yo me doy por satisfecho y aplaudo esa buena decisión del moderador. No tengo intención de discutir ni de seguir participando en estas cosas inconexas. Saludos.
|
|
|
|
|
86
|
Foros Generales / Foro Libre / Re: ¿Cómo hacer una IA libre?
|
en: 16 Abril 2025, 12:59 pm
|
Si se decide que el mensaje se borre, quisiera que me expliquen por qué. Yo no tengo la culpa de que los gobernantes sean tan mediocres He reportado tu hilo, para que sepas quien ha sido. Todo lo que has escrito en este hilo, es una fumada de principio a fin. Para el foro libre está bien, pero para la sección de Programación General, NO. Mantengamos cierto nivel de cordura y respeto al propósito de las secciones del foro... Las secciones de programación son para formular dudas de programación, no para ponerse a divagar sin rumbo en tanto párrafo sobre las emociones que te evocan al ver a un caballo con una venda en los ojos tomando el Sol, ni sobre la ética de los rituales religiosos sacrificando gallinas, ni de lo bien o lo mal que te parece que lo hagan los políticos de X país (que por cierto no sé por que le echas la culpa a los políticos, cuando es la sociedad la que debe preservar una moral y unos valores de convivencia), ni tampoco sobre tu erróneo concepto de Inteligencia Artificial, por que lo que llamamos IA no es ni tan inteligente ni tan artificial, y, por ende, todo ese texto apocalíptico de rollo de ficción de Terminator con una IA exterminando a humanos sobra tanto como todo lo anterior. Sin palabras me ha dejado leer todo esto. Y no me vayas a decir que tu duda es "¿Cómo hacer una IA libre?" - siendo tú una persona que no tiene el conocimiento de programación sobre algoritmos de IA NI TAMPOCO LA INTENCIÓN REAL de desarrollar una IA. En fin. Mejor no sigo escribiendo para que no me acusen de pasarme de la ralla, de encenderme, de cabrearme, pero es que lo estoy, por que estas cosas molestan, es hacerle perder el tiempo a la gente con preguntas sin sentido. Que los moderadores borren este mensaje si lo consideran oportuno. Lo siento. Saludos.
|
|
|
|
|
87
|
Programación / Scripting / [APORTE] [PowerShell] Ejemplo para modificar los niveles de integridad de directorios
|
en: 15 Abril 2025, 07:57 am
|
El siguiente script, desarrollado en PowerShell, es una simple demostración de como podemos especificar un array de directorios para modificar su nivel de integridad, mediate el uso del comando ICACLS de Microsoft Windows. Acerca de los niveles de integridad: 👉 https://hacktricks.boitatech.com.br/windows/windows-local-privilege-escalation/integrity-levelsCuando navegamos por un directorio con un nivel de integridad bajo, se nos mostrará la siguiente ventana de advertencia cuando se intenten copiar o mover archivos dentro o fuera de dicho directorio (utilizando el menú contextual de cortar / copiar / pegar):  Pueden comprobarlo en el directorio "C:\Users\{USUARIO}\AppData\LocalLow", que por defecto tiene un nivel de integridad bajo (Low) a menos que de alguna extraña forma esto se haya modificado en su sistema operativo.  Este comportamiento de advertencia puede resultar muy molesto, pero podemos deshacernos de esa ventana de advertencia cambiando el nivel de integridad por uno más alto (Medium): 
El script lo he escrito de tal manera que se pueda embedir en un Batch-script: powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^ "$folders = @{^ \"$env:USERPROFILE\AppData\Local\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\AppData\LocalLow\" = @{level = 'Medium'; recurse = $true};^ \"$env:USERPROFILE\AppData\Roaming\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Desktop\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Documents\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Downloads\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Favorites\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Links\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Music\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Pictures\" = @{level = 'Medium'; recurse = $false};^ \"$env:USERPROFILE\Videos\" = @{level = 'Medium'; recurse = $false};^ };^ $sortedFolders = $folders.Keys ^| Sort-Object;^ Write-Output \"Applying folder integrity levels...\";^ Write-Output \"\";^ Write-Output \"Level | Recursive | Directory\";^ Write-Output \"-------|-----------|----------\";^ foreach ($folder in $sortedFolders ) {^ $level = $folders[$folder].level;^ $recurseFlag = if ($folders[$folder].recurse ) { '/T' } else { '' };^ $recurseText = if ($folders[$folder].recurse ) { 'Yes' } else { 'No ' };^ Write-Output \"$level | $recurseText | $folder\";^ ICACLS.exe \"$folder\" $recurseFlag /Setintegritylevel \"(OI)(CI)$level\" 2^>^$null 1^>^$null^ }"
 El cambio de nivel de integridad tiene efecto inmediato, no es necesario reiniciar sesión de usuario ni el PC. * ⚠️ Antes de utilizar ese script, configurar el array con las rutas de los directorios que deseen incluir.
Como alternativa, les dejo este módulo de PowerShell, basado en la API de Windows para quien desee llevar a cabo una gestión más directa y sofisticada de los niveles de integridad sin necesidad de recurrir a comandos externos del sistema operativo como ICACLS: 👉 https://github.com/jborean93/PSIntegrity/blob/master/PSIntegrity/PSIntegrity.psm1Cmdlets incluídos: Get-IntegrityLabel: Gets an instance of BaseObjectLabel for the resource specified Remove-IntegrityLabel: Removes the mandatory integrity label set on an object Set-IntegrityLabel: Adds or changes the mandatory integrity label set on an object Atentamente, Elektro.
|
|
|
|
|
88
|
Informática / Hardware / Re: Tamaño límite de particiones FAT32, exFAT y NTFS
|
en: 15 Abril 2025, 06:01 am
|
En teoría la diferencia entre MBR y GPT es que GPT es capaz de redirecciones 64 bytes de sectores físicos. Por lo que en GPT... ¿es posible superar los 2 TiB, en un disco con sectores físicos 512 bytes, formateando con tamaño de clúster 4 KiB y superar los 16 TiB, en un disco con sectores físicos 4096 bytes, formateando con tamaño de clúster 8 KiB?*
*Esto último no lo he comprobado. A ver si un usuario que tenga discos más grandes de 16 Tb puede confirmar si se pueden hacer particiones que superen los 15,99 TiB.
Tengo discos de 16 TB (14,55 TiB) hasta 22 TB (20,010 TiB), en todos ellos tengo una partición del tamaño total del disco (descontando el tamaño de unos cuantos megabytes para la partición reservada del sistema) de la forma en que Windows los formatea por defecto (GPT, tamaño de clúster de 8 KiB, 512 bytes por sector). Información NTFS de un disco de 18 TB (16,37 TiB): Número de serie de volumen NTFS: 0x**************** Versión NTFS: 3.1 Versión LFS: 2.0 Total de sectores: 35.156.619.263 (16,4 TB) Total de clústeres: 2.197.288.703 (16,4 TB) Clústeres disponibles: 25.527.931 (194,8 GB) Total de clústeres reservados: 11.201 (87,5 MB) Reservado para la reserva de almacenamiento: 0 (0,0 KB) Bytes por sector: 512 Bytes por sector físico: 4096 Bytes por clúster: 8192 Bytes por segmento FileRecord: 1024 Clústeres por segmento FileRecord: 0 Longitud válida de datos de MFT: 666,25 MB LCN de inicio de MFT: 0x0000000000060000 LCN de inicio de MFT2: 0x0000000000000001 Inicio de zona MFT: 0x000000000127a3c0 Fin de zona MFT: 0x00000000012807e0 Tamaño de zona MFT: 200,25 MB Recuento máximo de extensiones de recorte por dispositivo: 0 Recuento máximo de bytes de recorte por dispositivo: 0 Recuento máximo de extensiones de recorte por volumen: 62 Recuento máximo de bytes de recorte por volumen: 0x40000000
Veo que le has echado cierto tiempo para formatear la información que has recopilado, pero todo ello quedaría mucho mejor representada en un documento HTML con tablas:  Le pedí a ChatGPT que lo hiciese, y te lo dejo aquí por si lo prefieres editar en este formato. ⚠️ En este documento no se han añadido los comentarios con asterisco ni las correcciones de tu 2º comentario. Documento.html<!DOCTYPE html> <meta charset="Windows-1252"> <title>Límites de Particiones por Sistema de Archivos </title> body { font-family: Arial, sans-serif; background: #f4f4f9; color: #333; padding: 20px; } h2 { color: #2a4d69; } table { width: auto; border-collapse: collapse; margin-bottom: 30px; } th, td { border: 1px solid #ccc; padding: 8px 12px; text-align: left; } th { background-color: #dfe9f3; } caption { font-weight: bold; margin-bottom: 8px; color: #2a4d69; text-align: left; } <h2>Límites Máximos por Sistema de Archivos </h2> <td>Tamaño partición máximo </td><td>8 TiB </td><td>2 TiB </td> <td>Tamaño clúster máximo </td><td>512 KiB </td><td>64 KiB </td> <td>Tamaño partición máximo </td><td>256 TiB </td> <td>Tamaño clúster máximo </td><td>1024 KiB </td> <td>Tamaño partición máximo </td><td>255,99 TiB </td> <td>Tamaño clúster máximo </td><td>64 KiB </td> <th>Sector lógico </th><th>Tamaño máximo de disco </th> <h2>FAT32: Límites por Tamaño de Clúster </h2> <h2>exFAT: Límites por Tamaño de Clúster </h2> <h2>NTFS: Límites por Tamaño de Clúster </h2>
O alternativamente en un documento CSV: Documento.csv"Título","FAT32 (MBR vs GPT)" "Tipo","MBR","GPT" "Tamaño partición máximo","8 TiB","2 TiB" "Tamaño clúster máximo","512 KiB","64 KiB"
"Título","exFAT" "Tipo","Valor" "Tamaño partición máximo","256 TiB" "Tamaño clúster máximo","1024 KiB"
"Título","NTFS" "Tipo","Valor" "Tamaño partición máximo","255,99 TiB" "Tamaño clúster máximo","64 KiB"
"Título","Compatibilidad Windows 2000 / XP / 2003" "Sector lógico","Tamaño máximo de disco" "512 bytes","1,99 TiB" "4096 bytes","15,99 TiB"
"Título","FAT32: Límites por Tamaño de Clúster" "Clúster","TiB","GiB","MiB" "4 KiB","0,29","300,99","308223,99" "8 KiB","0,59","601,99","616447,99" "16 KiB","1,17","1203,99","1232895,99" "32 KiB","2,35","2407,99","2465791,99" "64 KiB","4,70","4815,99","4931583,99" "128 KiB","8,00","8192,00","8388607,50"
"Título","exFAT: Límites por Tamaño de Clúster" "Clúster","TiB","GiB","MiB" "0,5 KiB","0,12","129,00","132104,05" "1 KiB","0,25","257,00","263172,00" "2 KiB","0,50","513,00","525313,97" "4 KiB","1,00","1025,00","1049600,95" "8 KiB","2,00","2049,00","2098176,40" "16 KiB","4,00","4097,00","4195328,06" "32 KiB","8,00","8192,99","8389631,74" "64 KiB","16,00","16384,99","16778239,30" "128 KiB","32,00","32768,99","33555454,52" "256 KiB","64,00","65536,99","67109885,01" "512 KiB","128,00","131072,00","134218746,00" "1024 KiB","256,00","262144,00","268435456,00"
"Título","NTFS: Límites por Tamaño de Clúster" "Clúster","TiB","GiB","MiB" "0,5 KiB","1,99","2047,99","2097151,99" "1 KiB","3,99","4095,99","4194303,99" "2 KiB","7,99","8191,99","8388607,99" "4 KiB","15,99","16384,99","16777215,99" "8 KiB","31,99","32767,99","33554431,99" "16 KiB","63,99","65535,99","67108863,98" "32 KiB","127,99","131071,99","134217727,96" "64 KiB","255,99","262143,99","268435455,93" "128 KiB","511,99","524287,99","536870911,87"
⚠️ Este documento CSV es una simple adaptación por IA del documento HTML compartido aquí arriba, sin revisión humana. Atentamente, Elektro.
|
|
|
|
|
89
|
Informática / Software / Busco un software con interfaz gráfica para leer y modificar los niveles de integridad (Mandatory Label ACE) de archivos
|
en: 14 Abril 2025, 00:09 am
|
Hola! Busco un software de seguridad, con interfaz gráfica (GUI), que sea capaz de leer y modificar los 👉 niveles de integridad ('File Integrity Levels' en Inglés, o 👉 Mandatory Label ACE) de archivos y carpetas, de forma productiva, es decir, con una navegación de archivos fácil y fluida, que no te haga perder 5 minutos para navegar hasta un directorio en específico... Básicamente lo que se puede hacer con el parámetro /SetIntegrtyLevel del executable ICACLS.exe en Windows: - https://learn.microsoft.com/es-es/windows-server/administration/windows-commands/icaclsO con el ya extinto programa Chml de Mr. Minasi: - https://web.archive.org/web/20131226134704/http://www.minasi.com/apps/(se puede descargar el executable desde esa página) O con este módulo de terceros (basado en C# — en el uso de Windows API) para el lenguaje de programación PowerShell: - https://github.com/jborean93/PSIntegrity/blob/master/PSIntegrity/PSIntegrity.psm1etc.
He intentado buscar específicamente una GUI de ICACLS, pero no encontré nada. En fin. No me urge en absoluto encontrar un programa similar, más bien es por el capricho de poder tener un buen programa con interfaz gráfica, sencillito y productivo para estos menesteres. Que esté orientado a los niveles de integridad, más que a los ACL (como 👉 SetACL Studio, que por cierto es antiproductivo en todos los sentidos). Hay varias opciones por línea de comandos como las que por ejemplo ya he mencionado aquí, pero con interfaz gráfica no he encontrado nada. Parece estar bastante difícil, quizás no exista. O quizás alguien pueda sorprenderme... Gracias de antemano. Atentamente, Elektro.
|
|
|
|
|
90
|
Foros Generales / Dudas Generales / Re: Garantía de los productos en compras online
|
en: 12 Abril 2025, 14:23 pm
|
Y que me decís de esto Primero habría que determinar si el producto es de fabricación europea, y si su manufacturación fue antes o después del 1 de Enero de 2022 cuando entró en vigor esta versión más reciente de la normativa de la garantía legal en la UE. Esto de los tres años me parece que no es para todos los países europeos, pero si para España entre otros. Pero es que da exactamente igual lo que ponga en un papelito, el fabricante puede poner lo que quiera que eso no tiene validez legal por encima de los derechos como consumidor dentro de lo que digan las leyes de comercio en Europa y la ley de España. Y, de todas formas, ese papelito posiblemente e realidad expresará otro tipo de políticas vinculadas a garantías individuales ofrecidas por el fabricante, como sucede con los discos duros, el fabricante suele ofrecer una garantía de reparación de 2 a 4 años o lo que sea, pero eso es algo que ofrece el fabricante, no hay que mezclar esto con la garantía de la UE. La cuestión es que el responsable directo de hacer cumplir la garantía de la UE (y la ley española) para resolverte el problema y darte un reembolso etc durante tres años (siempre que se cumplan los criterios básicos que ya mencioné en otro comentario), es la tienda o empresa que te vendió el producto, no el fabricante. Atentamente, Elektro.
|
|
|
|
|
|
| |
|