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


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


  Mostrar Mensajes
Páginas: 1 ... 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 [699] 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 ... 1254
6981  Programación / .NET (C#, VB.NET, ASP) / Re: Información en int, hex y bin dentro de un Form en: 21 Agosto 2014, 09:42 am
¿Cuál es la mejor forma de codearlo?[/b]

Pues hombre... agregar 35 controles y usar 35 event-handlers para suscribirte al mismo evento desde luego que no es lo más eficiente, se puede reducir mucho el código para que sea siendo dinámico como dijo el compañero seba123neo, pero seguiría habiendo 35 controles en la UI, hay otras formas de hacerlo de forma dinámica (como también te explicó seba123neo).

Mi consejo:

1. Utiliza solo 1 picturebox de fondo, y para todo lo demás utiliza las classes de GDI+.

2. Dibuja una rejilla del tamaño deseado sobre el picturebox, con las columnas y filas deseadas, en el evento Paint del picturebox.

3. Crea 1 Rectangle por cada sector de la rejilla, y así ya tienes una referencia de cada sector de la rejilla con su respectiva localización y tamaño a la que puedes acceder en cualquier momento.

4. En este punto ya se supone que deberías haber obtenido una coleción de los sectores de la rejilla( te sugiero añadirlos a una List(Of Rectangle) ),
    así que solo tienes que suscribirte a los eventos del Mouse (MouseMove y MouseClick) del PictureBox donde harás las operaciones necesarias (como por ejemplo especificar en que sector de la rejilla se hizo click, y el color despues de hacer click, etc), fin del problema.


Te muestro un ejemplo:



En ese ejemplo solo utilicé 1 picturebox con el fondo negro (aunque un picturebox tampoco es totalmente necesario pero facilita un poco la tarea), dibujé la rejilla con Pens, y para todo lo demás utilicé Rectangle, siguiendo los pasos que te he explicado.





No voy a mostrar todo el trabajo porque la idea es que aprendas a hacerlo pro ti mismo, y además, yo lo hice en VB.NET, peor te dejo una ayudita por si te sirve (lo puedes traducir a C# en convertidores online):

Este método lo escribí para dibujar los márgenes del grid (lo debes utilizar en el evento Paint):

Código
  1.    ' Draw Grid
  2.    ' By Elektro
  3.    '
  4.    ''' <summary>
  5.    ''' Draws a grid in the specified <see cref="System.Drawing.Graphics"/> space.
  6.    ''' </summary>
  7.    ''' <param name="g">Indicates the <see cref="System.Drawing.Graphics"/> object.</param>
  8.    ''' <param name="GridSize">Indicates the size of the grid.</param>
  9.    ''' <param name="Columns">Indicates the amount of columns to draw.</param>
  10.    ''' <param name="Rows">Indicates the amount of rows to draw.</param>
  11.    ''' <param name="ColorColumns">Indicates the columns color.</param>
  12.    ''' <param name="ColorRows">Indicates the rows color.</param>
  13.    ''' <param name="DrawBorder">If set to <c>true</c>, a border is drawn on the grid edges.</param>
  14.    ''' <param name="ColorBorder">Indicates the border color. Default value is the same color as <param ref="ColorColumns"/></param>
  15.    ''' <param name="ColorStyle">Indicates the colors <see cref="System.Drawing.Drawing2D.DashStyle"/>.</param>
  16.    ''' <exception cref="System.ArgumentException">
  17.    ''' GridSize.Width is not divisible by the specified number of columns.
  18.    ''' or
  19.    ''' GridSize.Height is not divisible by the specified number of rows.
  20.    ''' </exception>
  21.    Private Sub DrawGrid(ByVal g As Graphics,
  22.                         ByVal GridSize As Size,
  23.                         ByVal Columns As Integer,
  24.                         ByVal Rows As Integer,
  25.                         ByVal ColorColumns As Color,
  26.                         ByVal ColorRows As Color,
  27.                         Optional ByVal DrawBorder As Boolean = True,
  28.                         Optional ByVal ColorBorder As Color = Nothing,
  29.                         Optional ByVal ColorStyle As Drawing2D.DashStyle = Drawing2D.DashStyle.Solid)
  30.  
  31.        If Not (GridSize.Width Mod Columns = 0I) Then
  32.            Throw New ArgumentException(
  33.                "GridSize.Width is not divisible by the specified number of columns.",
  34.                "GridSize")
  35.            Exit Sub
  36.  
  37.        ElseIf Not (GridSize.Height Mod Rows = 0I) Then
  38.            Throw New ArgumentException(
  39.                "GridSize.Height is not divisible by the specified number of rows.",
  40.                "GridSize")
  41.            Exit Sub
  42.  
  43.        End If
  44.  
  45.        Dim SectorWidth As Integer = (GridSize.Width \ Columns)
  46.        Dim SectorHeight As Integer = (GridSize.Height \ Rows)
  47.  
  48.        Using PenRow As New Pen(ColorRows) With {.DashStyle = ColorStyle}
  49.  
  50.            Using PenCol As New Pen(ColorColumns) With {.DashStyle = ColorStyle}
  51.  
  52.                For row As Integer = 0I To GridSize.Height - 1 Step (SectorHeight)
  53.  
  54.                    For col As Integer = 0I To GridSize.Width - 1 Step SectorWidth
  55.  
  56.                        ' Draw the vertical grid-lines.
  57.                        g.DrawLine(PenCol,
  58.                                   New Point(x:=col - 1, y:=0I),
  59.                                   New Point(x:=col - 1, y:=GridSize.Height))
  60.  
  61.                    Next col
  62.  
  63.                    ' Draw the horizontal grid-lines.
  64.                    g.DrawLine(PenRow,
  65.                               New Point(x:=0I, y:=row - 1),
  66.                               New Point(x:=GridSize.Width, y:=row - 1))
  67.  
  68.                Next row
  69.  
  70.                If DrawBorder Then
  71.  
  72.                    Using PenBorder As New Pen(If(ColorBorder = Nothing, ColorColumns, ColorBorder)) With {.DashStyle = ColorStyle}
  73.  
  74.                        ' Draw the vertical left grid-line.
  75.                        g.DrawLine(PenBorder,
  76.                                   New Point(x:=0, y:=0I),
  77.                                   New Point(x:=0, y:=GridSize.Height))
  78.  
  79.                        ' Draw the vertical right grid-line.
  80.                        g.DrawLine(PenBorder,
  81.                                   New Point(x:=(GridSize.Width - 1I), y:=0I),
  82.                                   New Point(x:=(GridSize.Width - 1I), y:=GridSize.Height))
  83.  
  84.                        ' Draw the horizontal top grid-line.
  85.                        g.DrawLine(PenBorder,
  86.                                   New Point(x:=0I, y:=0I),
  87.                                   New Point(x:=GridSize.Width, y:=0I))
  88.  
  89.                        ' Draw the horizontal bottom grid-line.
  90.                        g.DrawLine(PenBorder,
  91.                                   New Point(x:=0I, y:=(GridSize.Height - 1I)),
  92.                                   New Point(x:=GridSize.Width, y:=(GridSize.Height - 1I)))
  93.                    End Using ' PenBorder
  94.  
  95.                End If ' DrawBorder
  96.  
  97.            End Using '  PenCol
  98.  
  99.        End Using ' PenRow
  100.  
  101.    End Sub


Y este método lo escribí para obtener los rectangles de la rejilla:

Código
  1.    ' Get Grid
  2.    ' By Elektro
  3.    '
  4.    ''' <summary>
  5.    ''' Calculates the drawing of a grid with the specified size,
  6.    ''' and returns a<see cref="List(Of Rectangle)"/> that contains the grid-sector specifications.
  7.    ''' </summary>
  8.    ''' <param name="GridSize">Indicates the grid size.</param>
  9.    ''' <param name="Columns">Indicates the amount of columns.</param>
  10.    ''' <param name="Rows">Indicates the amount of rows.</param>
  11.    ''' <returns>A <see cref="List(Of Rectangle)"/> that contains the grid-sector specifications.</returns>
  12.    ''' <exception cref="System.ArgumentException">
  13.    ''' GridSize.Width is not divisible by the specified number of columns.
  14.    ''' or
  15.    ''' GridSize.Height is not divisible by the specified number of rows.
  16.    ''' </exception>
  17.    Private Function GetGrid(ByVal GridSize As Size,
  18.                             ByVal Columns As Integer,
  19.                             ByVal Rows As Integer) As List(Of Rectangle)
  20.  
  21.        If Not (GridSize.Width Mod Columns = 0I) Then
  22.            Throw New ArgumentException(
  23.                "GridSize.Width is not divisible by the specified number of columns.",
  24.                "GridSize")
  25.            Return Nothing
  26.  
  27.        ElseIf Not (GridSize.Height Mod Rows = 0I) Then
  28.            Throw New ArgumentException(
  29.                "GridSize.Height is not divisible by the specified number of rows.",
  30.                "GridSize")
  31.            Return Nothing
  32.  
  33.        End If
  34.  
  35.        Dim Sectors As New List(Of Rectangle)
  36.        Dim SectorWidth As Integer = GridSize.Width \ Columns
  37.        Dim SectorHeight As Integer = GridSize.Height \ Rows
  38.  
  39.        For row As Integer = 0I To GridSize.Height - 1 Step (SectorHeight)
  40.  
  41.            For col As Integer = 0I To GridSize.Width - 1 Step SectorWidth
  42.  
  43.                Sectors.Add(New Rectangle(col, row, SectorWidth, SectorHeight))
  44.  
  45.            Next col
  46.  
  47.        Next row
  48.  
  49.        Return Sectors
  50.  
  51.    End Function


EDITO2:

bueno voy a mostrate el resto del código porque total lo hice para ayudarte con el problema y ya no me sirve para nada esto así que antes de tirarlo te lo enseño xD, espero que te sirva.

( esta parte del code lo desarrollé en poco tiempo, está bastante sucio el código y se puede mejorar mucho, pero sirve para hacerse una idea )

Código
  1.    Public Property currentsector As Integer = 0
  2.    Public Property currentcolor As Color = Color.Gray
  3.  
  4.    Public ReadOnly Property GridSectors As List(Of Rectangle)
  5.        Get
  6.            Return Me.GetGrid(GridSize:=PictureBox1.ClientRectangle.Size, Columns:=5, Rows:=5)
  7.        End Get
  8.    End Property
  9.  
  10.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
  11.  
  12.        Label1.Text = "Sectors: " & GridSectors.Count
  13.  
  14.    End Sub
  15.  
  16.    Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _
  17.    Handles PictureBox1.Paint
  18.  
  19.  
  20.        Me.DrawGrid(g:=e.Graphics,
  21.                    GridSize:=sender.ClientRectangle.Size,
  22.                    Columns:=5,
  23.                    Rows:=5,
  24.                    ColorColumns:=Color.YellowGreen,
  25.                    ColorRows:=Color.YellowGreen,
  26.                    DrawBorder:=True,
  27.                    ColorBorder:=Nothing,
  28.                    ColorStyle:=Drawing2D.DashStyle.Solid)
  29.  
  30.    End Sub
  31.  
  32.    Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
  33.  
  34.        Dim Sectors As List(Of Rectangle) = Me.GridSectors
  35.  
  36.        For X As Integer = 0I To (Sectors.Count - 1I)
  37.  
  38.            If Sectors(X).Contains(sender.PointToClient(MousePosition)) Then
  39.  
  40.                Dim myBrush As New SolidBrush(currentcolor)
  41.  
  42.                Using formGraphics As Graphics = sender.CreateGraphics()
  43.  
  44.                    formGraphics.FillRectangle(myBrush, New Rectangle(Sectors(X).X + 1, Sectors(X).Y + 1, Sectors(X).Width - 2, Sectors(X).Height - 2))
  45.                    myBrush.Dispose()
  46.  
  47.                End Using ' formGraphics
  48.                currentsector = X + 1
  49.                Label2.Text = "Current sector: " & currentsector
  50.  
  51.            Else
  52.                Dim myBrush As New SolidBrush(Color.Black)
  53.  
  54.                Using formGraphics As Graphics = sender.CreateGraphics()
  55.  
  56.                    formGraphics.FillRectangle(myBrush, New Rectangle(Sectors(X).X + 1, Sectors(X).Y + 1, Sectors(X).Width - 2, Sectors(X).Height - 2))
  57.                    myBrush.Dispose()
  58.  
  59.                End Using ' formGraphics
  60.            End If ' Sectors(X).Contains(...)
  61.  
  62.        Next X
  63.  
  64.    End Sub
  65.  
  66.    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.MouseDown
  67.  
  68.        Label3.Text = "Last Sector Clicked: " & currentsector
  69.  
  70.        '  Dim sector As Rectangle = Me.GridSectors(currentsector - 1)
  71.        currentcolor = Color.Red
  72.        PictureBox1.Cursor = Cursors.Hand
  73.        PictureBox1.Update()
  74.  
  75.        'Dim myBrush As New SolidBrush(Color.Red)
  76.  
  77.        'Using formGraphics As Graphics = PictureBox1.CreateGraphics()
  78.  
  79.        '    formGraphics.FillRectangle(myBrush, New Rectangle(sector.X + 1, sector.Y + 1, sector.Width - 2, sector.Height - 2))
  80.        '    myBrush.Dispose()
  81.  
  82.        'End Using ' formGraphics
  83.  
  84.    End Sub
  85.  
  86.    Private Sub PictureBox1_Clic(sender As Object, e As EventArgs) Handles PictureBox1.MouseUp
  87.        Label3.Text = "Last Sector Clicked: " & currentsector
  88.  
  89.        '  Dim sector As Rectangle = Me.GridSectors(currentsector - 1)
  90.        currentcolor = Color.Gray
  91.        PictureBox1.Cursor = Cursors.Default
  92.        PictureBox1.Update()
  93.  
  94.        'Dim myBrush As New SolidBrush(Color.Red)
  95.  
  96.        'Using formGraphics As Graphics = PictureBox1.CreateGraphics()
  97.  
  98.        '    formGraphics.FillRectangle(myBrush, New Rectangle(sector.X + 1, sector.Y + 1, sector.Width - 2, sector.Height - 2))
  99.        '    myBrush.Dispose()
  100.  
  101.        'End Using ' formGraphics
  102.  
  103.    End Sub




EDITO1:


Fijándome justo la imagen de arriba, al pinchar los pictureBox quiero que aparezcan en tiempo real los resultados en Decimales, Hexadecimales y Binarios.

El tiempo real quiero decir, que desde que pulse un pictureBox, se actualiza los datos dentro de los textBox inficado arriba.

Con usar timer de 0.1 segundo funciona en vez de usar un botón para actualizar.

Espero que se entienda lo que quiero hacer. Esta parte si que no me sale.

Lo siento creo que no te entendí muy bien, ¿que problema tienes actualmente a la hora de actualizar los valores de cada control?.

Si vas a utilizar tropecientos pictureboxes entonces deberías suscribirte al evento Click como te explicó seba123neo, y una vez pulses cualquier picturebox actualizaríass los valores (de forma interna) y los imprimirías en los textboxes, ¿cual es el problema?

Saludos
6982  Programación / Scripting / Re: [AYUDA][PYTHON] Leer y guardar archivos .exe de forma hexadecimal en python??? en: 21 Agosto 2014, 08:44 am
Todo lo que necesitas para leer/escribir bytes en un stream lo tienes en el módulo 'IO': https://docs.python.org/2/library/io.html

Ejemplo:
Código:
>>> f = open('/tmp/IMG_5982.JPG', 'rb')
>>> data = f.read(10)
>>> data
'\x00\x00II*\x00\x08\x00\x00\x00'

Código:
>>> data[2]
'I'

Las secuencias de Bytes en Python se representan como strings, como puedes ver.

Pero puedes utilizar el método Ord() o Bin() para obtener una representación Decimal o Binaria respectivamente

Código:
>>> ord(data[2])
73

>>> hex(ord(data[2]))
'0x49'

>>> bin(ord(data[2]))
'0b1001001'

Tienes muchos ejemplos de todo ello en Google.

Saludos!
6983  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 20 Agosto 2014, 02:06 am
He escrito este ejemplo para mostrar como se puede compartir un espacio de memoria que puede ser leido por diferentes aplicaciones:



Esta sería la aplicación número 1, creen un nuevo proyecto, copien y compilen este Form:

Código
  1. ' Example of sharing memory across different running applications.
  2. ' By Elektro
  3. '
  4. ' *************************
  5. ' This is the Application 1
  6. ' *************************
  7.  
  8. #Region " Imports "
  9.  
  10. Imports System.IO.MemoryMappedFiles
  11.  
  12. #End Region
  13.  
  14. #Region " Application 2 "
  15.  
  16. ''' <summary>
  17. ''' Class MemoryMappedFile_Form1.
  18. ''' This should be the Class used to compile our first application.
  19. ''' </summary>
  20. Public Class MemoryMappedFile_Form1
  21.  
  22.    ' The controls to create on execution-time.
  23.    Dim WithEvents btMakeFile As New Button ' Writes the memory.
  24.    Dim WithEvents btReadFile As New Button ' Reads the memory.
  25.    Dim tbMessage As New TextBox ' Determines the string to map into memory.
  26.    Dim tbReceptor As New TextBox ' Print the memory read's result.
  27.    Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons.
  28.    Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'.
  29.  
  30.    ''' <summary>
  31.    ''' Indicates the name of our memory-file.
  32.    ''' </summary>
  33.    Private ReadOnly MemoryName As String = "My Memory-File Name"
  34.  
  35.    ''' <summary>
  36.    ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes.
  37.    ''' </summary>
  38.    Private ReadOnly MemoryBufferSize As Integer = 1024I
  39.  
  40.    ''' <summary>
  41.    ''' Indicates the string to map in memory.
  42.    ''' </summary>
  43.    Private ReadOnly Property strMessage As String
  44.        Get
  45.            Return tbMessage.Text
  46.        End Get
  47.    End Property
  48.  
  49.    ''' <summary>
  50.    ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form1"/> class.
  51.    ''' </summary>
  52.    Public Sub New()
  53.  
  54.        ' This call is required by the designer.
  55.        InitializeComponent()
  56.  
  57.        ' Set the properties of the controls.
  58.        With lbInfotbMessage
  59.            .Location = New Point(20, 10)
  60.            .Text = "Type in this TextBox the message to write in memory:"
  61.            .AutoSize = True
  62.            ' .Size = tbReceptor.Size
  63.        End With
  64.        With tbMessage
  65.            .Text = "Hello world from application one!"
  66.            .Location = New Point(20, 30)
  67.            .Size = New Size(310, Me.tbMessage.Height)
  68.        End With
  69.        With btMakeFile
  70.            .Text = "Write Memory"
  71.            .Size = New Size(130, 45)
  72.            .Location = New Point(20, 50)
  73.        End With
  74.        With btReadFile
  75.            .Text = "Read Memory"
  76.            .Size = New Size(130, 45)
  77.            .Location = New Point(200, 50)
  78.        End With
  79.        With tbReceptor
  80.            .Location = New Point(20, 130)
  81.            .Size = New Size(310, 100)
  82.            .Multiline = True
  83.        End With
  84.        With lbInfoButtons
  85.            .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30)
  86.            .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications."
  87.            .AutoSize = False
  88.            .Size = tbReceptor.Size
  89.        End With
  90.  
  91.        ' Set the Form properties.
  92.        With Me
  93.            .Text = "Application 1"
  94.            .Size = New Size(365, 300)
  95.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  96.            .MaximizeBox = False
  97.            .StartPosition = FormStartPosition.CenterScreen
  98.        End With
  99.  
  100.        ' Add the controls on the UI.
  101.        Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons})
  102.  
  103.    End Sub
  104.  
  105.    ''' <summary>
  106.    ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>.
  107.    ''' </summary>
  108.    ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param>
  109.    ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param>
  110.    ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param>
  111.    Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte())
  112.  
  113.        ' Create or open the memory-mapped file.
  114.        Dim MessageFile As MemoryMappedFile =
  115.            MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  116.  
  117.        ' Write the byte-sequence into memory.
  118.        Using Writer As MemoryMappedViewAccessor =
  119.            MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  120.  
  121.            ' Firstly fill with null all the buffer.
  122.            Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize)
  123.  
  124.            ' Secondly write the byte-data.
  125.            Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length)
  126.  
  127.        End Using ' Writer
  128.  
  129.    End Sub
  130.  
  131.    ''' <summary>
  132.    ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>.
  133.    ''' </summary>
  134.    ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param>
  135.    ''' <param name="BufferLength">The buffer-length to read in.</param>
  136.    ''' <returns>System.Byte().</returns>
  137.    Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte()
  138.  
  139.        Try
  140.            Using MemoryFile As MemoryMappedFile =
  141.                MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read)
  142.  
  143.                Using Reader As MemoryMappedViewAccessor =
  144.                    MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read)
  145.  
  146.                    Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {}
  147.                    Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length)
  148.                    Return ReadBytes
  149.  
  150.                End Using ' Reader
  151.  
  152.            End Using ' MemoryFile
  153.  
  154.        Catch ex As IO.FileNotFoundException
  155.            Throw
  156.            Return Nothing
  157.  
  158.        End Try
  159.  
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Handles the 'Click' event of the 'btMakeFile' control.
  164.    ''' </summary>
  165.    Private Sub btMakeFile_Click() Handles btMakeFile.Click
  166.  
  167.        ' Get the byte-data to create the memory-mapped file.
  168.        Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage)
  169.  
  170.        ' Create the memory-mapped file.
  171.        Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData)
  172.  
  173.    End Sub
  174.  
  175.    ''' <summary>
  176.    ''' Handles the 'Click' event of the 'btReadFile' control.
  177.    ''' </summary>
  178.    Private Sub btReadFile_Click() Handles btReadFile.Click
  179.  
  180.  
  181.        Dim ReadBytes As Byte()
  182.  
  183.        Try ' Read the byte-sequence from memory.
  184.            ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize)
  185.  
  186.        Catch ex As IO.FileNotFoundException
  187.            Me.tbReceptor.Text = "Memory-mapped file does not exist."
  188.            Exit Sub
  189.  
  190.        End Try
  191.  
  192.        ' Convert the bytes to String.
  193.        Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray)
  194.  
  195.        ' Remove null chars (leading zero-bytes)
  196.        Message = Message.Trim({ControlChars.NullChar})
  197.  
  198.        ' Print the message.
  199.        tbReceptor.Text = Message
  200.  
  201.    End Sub
  202.  
  203. End Class
  204.  
  205. #End Region

Esta sería la aplicación número 2, creen un nuevo proyecto, copien y compilen este Form:

Código
  1. ' Example of sharing memory across different running applications.
  2. ' By Elektro
  3. '
  4. ' *************************
  5. ' This is the Application 2
  6. ' *************************
  7.  
  8. #Region " Imports "
  9.  
  10. Imports System.IO.MemoryMappedFiles
  11.  
  12. #End Region
  13.  
  14. #Region " Application 2 "
  15.  
  16. ''' <summary>
  17. ''' Class MemoryMappedFile_Form2.
  18. ''' This should be the Class used to compile our first application.
  19. ''' </summary>
  20. Public Class MemoryMappedFile_Form2
  21.  
  22.    ' The controls to create on execution-time.
  23.    Dim WithEvents btMakeFile As New Button ' Writes the memory.
  24.    Dim WithEvents btReadFile As New Button ' Reads the memory.
  25.    Dim tbMessage As New TextBox ' Determines the string to map into memory.
  26.    Dim tbReceptor As New TextBox ' Print the memory read's result.
  27.    Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons.
  28.    Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'.
  29.  
  30.    ''' <summary>
  31.    ''' Indicates the name of our memory-file.
  32.    ''' </summary>
  33.    Private ReadOnly MemoryName As String = "My Memory-File Name"
  34.  
  35.    ''' <summary>
  36.    ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes.
  37.    ''' </summary>
  38.    Private ReadOnly MemoryBufferSize As Integer = 1024I
  39.  
  40.    ''' <summary>
  41.    ''' Indicates the string to map in memory.
  42.    ''' </summary>
  43.    Private ReadOnly Property strMessage As String
  44.        Get
  45.            Return tbMessage.Text
  46.        End Get
  47.    End Property
  48.  
  49.    ''' <summary>
  50.    ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form2"/> class.
  51.    ''' </summary>
  52.    Public Sub New()
  53.  
  54.        ' This call is required by the designer.
  55.        InitializeComponent()
  56.  
  57.        ' Set the properties of the controls.
  58.        With lbInfotbMessage
  59.            .Location = New Point(20, 10)
  60.            .Text = "Type in this TextBox the message to write in memory:"
  61.            .AutoSize = True
  62.            ' .Size = tbReceptor.Size
  63.        End With
  64.        With tbMessage
  65.            .Text = "Hello world from application two!"
  66.            .Location = New Point(20, 30)
  67.            .Size = New Size(310, Me.tbMessage.Height)
  68.        End With
  69.        With btMakeFile
  70.            .Text = "Write Memory"
  71.            .Size = New Size(130, 45)
  72.            .Location = New Point(20, 50)
  73.        End With
  74.        With btReadFile
  75.            .Text = "Read Memory"
  76.            .Size = New Size(130, 45)
  77.            .Location = New Point(200, 50)
  78.        End With
  79.        With tbReceptor
  80.            .Location = New Point(20, 130)
  81.            .Size = New Size(310, 100)
  82.            .Multiline = True
  83.        End With
  84.        With lbInfoButtons
  85.            .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30)
  86.            .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications."
  87.            .AutoSize = False
  88.            .Size = tbReceptor.Size
  89.        End With
  90.  
  91.        ' Set the Form properties.
  92.        With Me
  93.            .Text = "Application 2"
  94.            .Size = New Size(365, 300)
  95.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  96.            .MaximizeBox = False
  97.            .StartPosition = FormStartPosition.CenterScreen
  98.        End With
  99.  
  100.        ' Add the controls on the UI.
  101.        Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons})
  102.  
  103.    End Sub
  104.  
  105.    ''' <summary>
  106.    ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>.
  107.    ''' </summary>
  108.    ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param>
  109.    ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param>
  110.    ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param>
  111.    Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte())
  112.  
  113.        ' Create or open the memory-mapped file.
  114.        Dim MessageFile As MemoryMappedFile =
  115.            MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  116.  
  117.        ' Write the byte-sequence into memory.
  118.        Using Writer As MemoryMappedViewAccessor =
  119.            MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  120.  
  121.            ' Firstly fill with null all the buffer.
  122.            Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize)
  123.  
  124.            ' Secondly write the byte-data.
  125.            Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length)
  126.  
  127.        End Using ' Writer
  128.  
  129.    End Sub
  130.  
  131.    ''' <summary>
  132.    ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>.
  133.    ''' </summary>
  134.    ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param>
  135.    ''' <param name="BufferLength">The buffer-length to read in.</param>
  136.    ''' <returns>System.Byte().</returns>
  137.    Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte()
  138.  
  139.        Try
  140.            Using MemoryFile As MemoryMappedFile =
  141.                MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read)
  142.  
  143.                Using Reader As MemoryMappedViewAccessor =
  144.                    MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read)
  145.  
  146.                    Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {}
  147.                    Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length)
  148.                    Return ReadBytes
  149.  
  150.                End Using ' Reader
  151.  
  152.            End Using ' MemoryFile
  153.  
  154.        Catch ex As IO.FileNotFoundException
  155.            Throw
  156.            Return Nothing
  157.  
  158.        End Try
  159.  
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Handles the 'Click' event of the 'btMakeFile' control.
  164.    ''' </summary>
  165.    Private Sub btMakeFile_Click() Handles btMakeFile.Click
  166.  
  167.        ' Get the byte-data to create the memory-mapped file.
  168.        Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage)
  169.  
  170.        ' Create the memory-mapped file.
  171.        Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData)
  172.  
  173.    End Sub
  174.  
  175.    ''' <summary>
  176.    ''' Handles the 'Click' event of the 'btReadFile' control.
  177.    ''' </summary>
  178.    Private Sub btReadFile_Click() Handles btReadFile.Click
  179.  
  180.  
  181.        Dim ReadBytes As Byte()
  182.  
  183.        Try ' Read the byte-sequence from memory.
  184.            ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize)
  185.  
  186.        Catch ex As IO.FileNotFoundException
  187.            Me.tbReceptor.Text = "Memory-mapped file does not exist."
  188.            Exit Sub
  189.  
  190.        End Try
  191.  
  192.        ' Convert the bytes to String.
  193.        Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray)
  194.  
  195.        ' Remove null chars (leading zero-bytes)
  196.        Message = Message.Trim({ControlChars.NullChar})
  197.  
  198.        ' Print the message.
  199.        tbReceptor.Text = Message
  200.  
  201.    End Sub
  202.  
  203. End Class
  204.  
  205. #End Region

Ahora ya solo tienen que ejecutar ambas aplicaciones para testear.

Saludos!
6984  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 19 Agosto 2014, 22:06 pm
Un ejemplo de uso de la librería MagicGraphics: http://www.codeproject.com/Articles/19188/Magic-Graphics







Escribí este Form para jugar un poco con la funcionalidad de esta librería, la verdad es que es muy sencillo.



Código
  1. Public Class MagicGraphics_Test
  2.  
  3.    Private WithEvents RotationTimer As New Timer With {.Enabled = True, .Interval = 25}
  4.  
  5.    Dim SC As MagicGraphics.ShapeContainer
  6.  
  7.    Private Sub Tst_Shown() Handles MyBase.Shown
  8.  
  9.        SC = New MagicGraphics.ShapeContainer(PictureBox1.CreateGraphics, PictureBox1.Width, PictureBox1.Height, Color.Black, PictureBox1.Image)
  10.        PictureBox1.Image = SC.BMP
  11.        SC.AutoFlush = False
  12.  
  13.        Dim Sq As New MagicGraphics.Rectangle(New Pen(Color.Black, 3), Brushes.Aqua, 60, 20, 50, 50)
  14.        Sq.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(60, 0), Color.Yellow, Color.Red)
  15.        SC.AddShape(Sq)
  16.        Dim El As New MagicGraphics.Ellipse(New Pen(Color.Black, 3), Brushes.Olive, 60, 88, 50, 71)
  17.        El.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(30, 0), Color.Red, Color.SteelBlue)
  18.        SC.AddShape(El)
  19.  
  20.        RotationTimer.Start()
  21.  
  22.    End Sub
  23.  
  24.  
  25.    Private Sub RotationTimer_Tick() Handles RotationTimer.Tick
  26.  
  27.        Static Direction As Integer = 1I ' 0 = Left, 1 = Right
  28.  
  29.        For X As Integer = 0I To (SC.ShapesL.Count - 1)
  30.  
  31.            Dim shp As MagicGraphics.Shape = SC.ShapesL(X)
  32.  
  33.            shp.Rotate(-8)
  34.  
  35.            If shp.Location.X > (PictureBox1.Width - shp.Width) Then
  36.                Direction = 1I ' Right
  37.  
  38.            ElseIf shp.Location.X < PictureBox1.Location.X Then
  39.                Direction = 0I ' Left
  40.  
  41.            End If
  42.  
  43.            If Direction = 0 Then
  44.                shp.Move(shp.Location.X + 2, shp.Location.Y)
  45.  
  46.            Else
  47.                shp.Move(shp.Location.X - 2, shp.Location.Y)
  48.  
  49.            End If
  50.  
  51.            ' Debug.WriteLine(String.Format("Shape {0} Rotation: {1}", CStr(X), shp.Rotation))
  52.  
  53.        Next X
  54.  
  55.        SC.Flush()
  56.  
  57.    End Sub
  58.  
  59. End Class
  60.  
6985  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 19 Agosto 2014, 13:49 pm
Mil gracias de nuevo ahora si pude hacerlo funcionar :)

Bien aca donde me pones esto , es lo debería de cambiar por mi variable " result " que es la que tiene los números después de efectuada la operación que hago en mi programa ?

Código
  1. ReadOnly FixedValues As Integer() = {1, 5, 19, 22, 34, 55, 66, 88, 99, etc...}

¿A cual de las miles de variables que bautizaste con el nombre de "Result" te refieres? :P

Supongo que si, en la variable FixedValues debes especificarle los numeros que se tomarán para hacer las combinaciones, en tu ejemplo pusiste del 1 al 30, no se si harás eso con la variable "result" que mencionas, pero creo que ya te hiciste una idea de lo que debe ir en esa variable FixedValues (valores fijos).

por lo demas funciona como queria

Me alegro de oir eso

PD: Por si acaso te recuerdo que para ordenar de mayor a menor lo tienes facil usando una LINQ-query:
Código
  1. dim values as integer() = (from n as integer in TUSNUMEROS order by n ascending).toarray

o el método Sort, en una lista.

Saludos!
6986  Sistemas Operativos / Windows / Re: Renombrar ficheros en: 19 Agosto 2014, 13:35 pm
Si tienes una colección de cientos o miles de canciones entonces hay bastantes probabilidades de que el campo "ARTISTA" contenga guiones (ej: "Pepito De-Maria - Canción del verano"), y eso imposibilitaría un renombrado correcto porque es imposible saber cuantos guiones existen antes del quión que realmente separa el título del artista, así que prefiero evitar darte una solución sencilla (un script) y sugerirte que utilices la aplicación Renamer Pro: http://www.den4b.com/?x=products&product=renamer (el cual es muy sencillo de usar)

Junto a este preset que acabo de hacer para la ocasión:

ARTIST - Title Words.rnp
Código:
[Rule0]
ID=Case
Config=WHAT:3;SKIPEXTENSION:0;EXTENSIONALWAYSLOWERCASE:1;EXTENSIONALWAYSUPPERCASE:0;FORCECASE:0;FRAGMENTSTEXT:
Marked=1

[Rule1]
ID=RegEx
Config=expression:%28%2E%2B%29%5C%2D;REPLACE:%5CU%241%2D;CASESENSITIVE:0;SKIPEXTENSION:1
Marked=1

Primero capitalizo cada palabra del string, y luego utilizo la siguiente expresión regular para poner el campo "artista" en UPPERCASE:

Patrón de búsqueda: (.+)-
Reemplazamiento...: \U$1-


Todo esto lo puedes hacer en cualquier lenguaje de programación, pero te sugiero utilizar este programa para tener mayor control de las reglas de renombrado y sobretodo para poder visualizar una Preview del resultado antes de renombrar.



Saludos!
6987  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 19 Agosto 2014, 12:02 pm
Me encontré por ahí un ErrorProvider extendido, ya no recuerdo donde lo encontré, y la documentación es... bueno, muy pobre, pero es facil de usar y sencillo de entender a pesar de ello:

'Following class is inherited from basic ErrorProvider class
#Region "Error Provider Extended"
Public Class ErrorProviderExtended
    Inherits System.Windows.Forms.ErrorProvider
    Private _validationcontrols As New ValidationControlCollection
    Private _summarymessage As String = "Please enter following mandatory fields,"

    'This property will be used for displaying a summary message about all empty fields
    'Default value is "Please enter following mandatory fields,". You can set any other
    'message using this property.
    Public Property SummaryMessage() As String
        Get
            Return _summarymessage
        End Get
        Set(ByVal Value As String)
            _summarymessage = Value
        End Set
    End Property

    'Controls property is of type ValidationControlCollection which is inherited from CollectionBase
    'Controls holds all those objects which should be validated.
    Public Property Controls() As ValidationControlCollection
        Get
            Return _validationcontrols
        End Get
        Set(ByVal Value As ValidationControlCollection)
            _validationcontrols = Value
        End Set
    End Property

    'Following function returns true if all fields on form are entered.
    'If not all fields are entered, this function displays a message box which contains all those field names
    'which are empty and returns FALSE.
    Public Function CheckAndShowSummaryErrorMessage() As Boolean
        If Controls.Count <= 0 Then
            Return True
        End If
        Dim i As Integer
        Dim msg As String = SummaryMessage + vbNewLine + vbNewLine
        Dim berrors As Boolean = False
        For i = 0 To Controls.Count - 1
            If Controls(i).Validate Then
                If Trim(Controls(i).ControlObj.text) = "" Then
                    msg &= "> " & Controls(i).DisplayName & vbNewLine
                    SetError(Controls(i).ControlObj, Controls(i).ErrorMessage)
                    berrors = True
                Else
                    SetError(Controls(i).ControlObj, "")
                End If
            Else
                SetError(Controls(i).ControlObj, "")
            End If
        Next
        If berrors Then
            System.Windows.Forms.MessageBox.Show(msg, "Missing Information", Windows.Forms.MessageBoxButtons.OK, Windows.Forms.MessageBoxIcon.Stop)
            Return False
        Else
            Return True
        End If
    End Function

    'Following function clears error messages from all controls.
    Public Sub ClearAllErrorMessages()
        Dim i As Integer
        For i = 0 To Controls.Count - 1
            SetError(Controls(i).ControlObj, "")
        Next
    End Sub

    'This function hooks validation event with all controls.
    Public Sub SetErrorEvents()
        Dim i As Integer
        For i = 0 To Controls.Count - 1
            AddHandler CType(Controls(i).ControlObj, System.Windows.Forms.Control).Validating, AddressOf Validation_Event
        Next
    End Sub

    'Following event is hooked for all controls, it sets an error message with the use of ErrorProvider.
    Private Sub Validation_Event(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) 'Handles txtCompanyName.Validating
        If Controls(sender).Validate Then
            If Trim(sender.Text) = "" Then
                MyBase.SetError(sender, Controls(sender).ErrorMessage)
            Else
                MyBase.SetError(sender, "")
            End If
        End If
    End Sub
End Class
#End Region

'Following class is inherited from CollectionBase class. It is used for holding all Validation Controls.
'This class is collection of ValidationControl class objects.
'This class is used by ErrorProviderExtended class.
#Region "ValidationControlCollection"
Public Class ValidationControlCollection
    Inherits CollectionBase
    Default Public Property Item(ByVal ListIndex As Integer) As ValidationControl
        Get
            Return Me.List(ListIndex)
        End Get
        Set(ByVal Value As ValidationControl)
            Me.List(ListIndex) = Value
        End Set
    End Property


    Default Public Property Item(ByVal pControl As Object) As ValidationControl
        Get
            If IsNothing(pControl) Then
                Return Nothing
            End If

            If GetIndex(pControl.Name) < 0 Then
                Return New ValidationControl
            End If
            Return Me.List(GetIndex(pControl.Name))
        End Get
        Set(ByVal Value As ValidationControl)
            If IsNothing(pControl) Then Exit Property
            If GetIndex(pControl.Name) < 0 Then
                Exit Property
            End If
            Me.List(GetIndex(pControl.Name)) = Value
        End Set
    End Property
    Function GetIndex(ByVal ControlName As String) As Integer
        Dim i As Integer
        For i = 0 To Count - 1
            If Item(i).ControlObj.name.toupper = ControlName.ToUpper Then
                Return i
            End If
        Next
        Return -1
    End Function
    Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String)
        If IsNothing(pControl) Then Exit Sub
        Dim obj As New ValidationControl
        obj.ControlObj = pControl
        obj.DisplayName = pDisplayName
        obj.ErrorMessage = "Please enter " + pDisplayName
        Me.List.Add(obj)
    End Sub

    Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String, ByVal pErrorMessage As String)
        If IsNothing(pControl) Then Exit Sub
        Dim obj As New ValidationControl
        obj.ControlObj = pControl
        obj.DisplayName = pDisplayName
        obj.ErrorMessage = pErrorMessage
        Me.List.Add(obj)
    End Sub
    Public Sub Add(ByRef pControl As Object)
        If IsNothing(pControl) Then Exit Sub
        Dim obj As New ValidationControl
        obj.ControlObj = pControl
        obj.DisplayName = pControl.Name
        obj.ErrorMessage = "Please enter " + pControl.Name
        Me.List.Add(obj)
    End Sub
    Public Sub Add(ByVal pControl As ValidationControl)
        If IsNothing(pControl) Then Exit Sub
        Me.List.Add(pControl)
    End Sub
    Public Sub Remove(ByVal pControl As Object)
        If IsNothing(pControl) Then Exit Sub
        Dim i As Integer = Me.GetIndex(pControl.Name)
        If i >= 0 Then
            Me.List.RemoveAt(i)
        End If
    End Sub
End Class
#End Region

'ValidationControl class is used to hold any control from windows form.
'It holds any control in ControlObj property.
#Region "ValidationControl"
Public Class ValidationControl
    Private _control As Object
    Private _displayname As String
    Private _errormessage As String
    Private _validate As Boolean = True

    'Validate property decides weather control is to be validated. Default value is TRUE.
    Public Property Validate() As Boolean
        Get
            Return _validate
        End Get
        Set(ByVal Value As Boolean)
            _validate = Value
        End Set
    End Property

    'ControlObj is a control from windows form which is to be validated.
    'For example txtStudentName
    Public Property ControlObj() As Object
        Get
            Return _control
        End Get
        Set(ByVal Value As Object)
            _control = Value
        End Set
    End Property

    'DisplayName property is used for displaying summary message to user.
    'For example, for txtStudentName you can set 'Student Full Name' as field name.
    'This field name will be displayed in summary message.
    Public Property DisplayName() As String
        Get
            Return _displayname
        End Get
        Set(ByVal Value As String)
            _displayname = Value
        End Set
    End Property

    'ErrorMessage is also used for displaying summary message.
    'For example, you can enter 'Student Name is mandatory' as an error message.
    Public Property ErrorMessage() As String
        Get
            Return _errormessage
        End Get
        Set(ByVal Value As String)
            _errormessage = Value
        End Set
    End Property
End Class
#End Region



EDITO: Ya lo he documentado yo así rapidamente:

Código
  1. #Region "Error Provider Extended"
  2.  
  3. ''' <summary>
  4. ''' Provides a user interface for indicating that a control on a form has an error associated with it.
  5. ''' </summary>
  6. Public Class ErrorProviderExtended
  7.  
  8.    Inherits System.Windows.Forms.ErrorProvider
  9.    Private _validationcontrols As New ValidationControlCollection
  10.    Private _summarymessage As String = "Please enter following mandatory fields,"
  11.  
  12.    ''' <summary>
  13.    ''' Gets or sets the summary message.
  14.    ''' This property will be used for displaying a summary message about all empty fields.
  15.    ''' Default value is "Please enter following mandatory fields,".
  16.    ''' You can set any other message using this property.
  17.    ''' </summary>
  18.    ''' <value>The summary message.</value>
  19.    Public Property SummaryMessage() As String
  20.        Get
  21.            Return _summarymessage
  22.        End Get
  23.        Set(ByVal Value As String)
  24.            _summarymessage = Value
  25.        End Set
  26.    End Property
  27.  
  28.    ''' <summary>
  29.    ''' Gets or sets the controls which should be validated.
  30.    ''' </summary>
  31.    ''' <value>The controls.</value>
  32.    Public Property Controls() As ValidationControlCollection
  33.        Get
  34.            Return _validationcontrols
  35.        End Get
  36.        Set(ByVal Value As ValidationControlCollection)
  37.            _validationcontrols = Value
  38.        End Set
  39.    End Property
  40.  
  41.    ''' <summary>
  42.    ''' Checks the and show summary error message.
  43.    ''' </summary>
  44.    ''' <param name="ShowMessage">
  45.    ''' If set to <c>true</c>, This function displays a message box which contains all the field names which are empty.
  46.    ''' </param>
  47.    ''' <returns><c>true</c> if all fields on form are entered, <c>false</c> otherwise.</returns>
  48.    Public Function CheckAndShowSummaryErrorMessage(Optional ByVal ShowMessage As Boolean = False) As Boolean
  49.  
  50.        If Controls.Count <= 0 Then
  51.            Return True
  52.        End If
  53.  
  54.        Dim i As Integer
  55.        Dim msg As String = SummaryMessage + vbNewLine + vbNewLine
  56.        Dim berrors As Boolean = False
  57.  
  58.        For i = 0 To Controls.Count - 1
  59.  
  60.            If Controls(i).Validate Then
  61.                If Trim(Controls(i).ControlObj.text) = "" Then
  62.                    If ShowMessage Then
  63.                        msg &= "> " & Controls(i).DisplayName & vbNewLine
  64.                    End If
  65.                    SetError(Controls(i).ControlObj, Controls(i).ErrorMessage)
  66.                    berrors = True
  67.                Else
  68.                    SetError(Controls(i).ControlObj, "")
  69.                End If
  70.            Else
  71.                SetError(Controls(i).ControlObj, "")
  72.            End If
  73.  
  74.        Next i
  75.  
  76.        If berrors Then
  77.            If ShowMessage Then
  78.                MessageBox.Show(msg, "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Stop)
  79.            End If
  80.            Return False
  81.        Else
  82.            Return True
  83.        End If
  84.  
  85.    End Function
  86.  
  87.    ''' <summary>
  88.    ''' Clears error messages from all controls.
  89.    ''' </summary>
  90.    Public Sub ClearAllErrorMessages()
  91.  
  92.        Dim i As Integer
  93.        For i = 0 To Controls.Count - 1
  94.            SetError(Controls(i).ControlObj, "")
  95.        Next
  96.  
  97.    End Sub
  98.  
  99.    ''' <summary>
  100.    ''' Hooks validation event with all controls.
  101.    ''' </summary>
  102.    Public Sub SetErrorEvents()
  103.  
  104.        Dim i As Integer
  105.        For i = 0 To Controls.Count - 1
  106.            AddHandler CType(Controls(i).ControlObj, System.Windows.Forms.Control).Validating, AddressOf Validation_Event
  107.        Next
  108.  
  109.    End Sub
  110.  
  111.    ''' <summary>
  112.    ''' Handles the Event event of the Validation control.
  113.    ''' This event is hooked for all controls,
  114.    ''' it sets an error message with the use of ErrorProvider
  115.    ''' </summary>
  116.    ''' <param name="sender">The source of the event.</param>
  117.    ''' <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
  118.    Private Sub Validation_Event(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
  119.  
  120.        If Controls(sender).Validate Then
  121.            If Trim(sender.Text) = "" Then
  122.                MyBase.SetError(sender, Controls(sender).ErrorMessage)
  123.            Else
  124.                MyBase.SetError(sender, "")
  125.            End If
  126.        End If
  127.  
  128.    End Sub
  129.  
  130. End Class
  131.  
  132. #End Region
  133.  
  134. #Region "ValidationControlCollection"
  135.  
  136. ''' <summary>
  137. ''' This class is used for holding all Validation Controls.
  138. ''' This class is collection of 'ValidationControl' class objects.
  139. ''' This class is used by 'ErrorProviderExtended' class.
  140. ''' </summary>
  141. Public Class ValidationControlCollection : Inherits CollectionBase
  142.  
  143.    Default Public Property Item(ByVal ListIndex As Integer) As ValidationControl
  144.        Get
  145.            Return Me.List(ListIndex)
  146.        End Get
  147.        Set(ByVal Value As ValidationControl)
  148.            Me.List(ListIndex) = Value
  149.        End Set
  150.    End Property
  151.  
  152.    Default Public Property Item(ByVal pControl As Object) As ValidationControl
  153.        Get
  154.            If IsNothing(pControl) Then
  155.                Return Nothing
  156.            End If
  157.  
  158.            If GetIndex(pControl.Name) < 0 Then
  159.                Return New ValidationControl
  160.            End If
  161.            Return Me.List(GetIndex(pControl.Name))
  162.        End Get
  163.        Set(ByVal Value As ValidationControl)
  164.            If IsNothing(pControl) Then Exit Property
  165.            If GetIndex(pControl.Name) < 0 Then
  166.                Exit Property
  167.            End If
  168.            Me.List(GetIndex(pControl.Name)) = Value
  169.        End Set
  170.    End Property
  171.  
  172.    Function GetIndex(ByVal ControlName As String) As Integer
  173.        Dim i As Integer
  174.        For i = 0 To Count - 1
  175.            If Item(i).ControlObj.name.toupper = ControlName.ToUpper Then
  176.                Return i
  177.            End If
  178.        Next
  179.        Return -1
  180.    End Function
  181.  
  182.    Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String)
  183.        If IsNothing(pControl) Then Exit Sub
  184.        Dim obj As New ValidationControl
  185.        obj.ControlObj = pControl
  186.        obj.DisplayName = pDisplayName
  187.        obj.ErrorMessage = "Please enter " + pDisplayName
  188.        Me.List.Add(obj)
  189.    End Sub
  190.  
  191.    Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String, ByVal pErrorMessage As String)
  192.        If IsNothing(pControl) Then Exit Sub
  193.        Dim obj As New ValidationControl
  194.        obj.ControlObj = pControl
  195.        obj.DisplayName = pDisplayName
  196.        obj.ErrorMessage = pErrorMessage
  197.        Me.List.Add(obj)
  198.    End Sub
  199.  
  200.    Public Sub Add(ByRef pControl As Object)
  201.        If IsNothing(pControl) Then Exit Sub
  202.        Dim obj As New ValidationControl
  203.        obj.ControlObj = pControl
  204.        obj.DisplayName = pControl.Name
  205.        obj.ErrorMessage = "Please enter " + pControl.Name
  206.        Me.List.Add(obj)
  207.    End Sub
  208.  
  209.    Public Sub Add(ByVal pControl As ValidationControl)
  210.        If IsNothing(pControl) Then Exit Sub
  211.        Me.List.Add(pControl)
  212.    End Sub
  213.  
  214.    Public Sub Remove(ByVal pControl As Object)
  215.        If IsNothing(pControl) Then Exit Sub
  216.        Dim i As Integer = Me.GetIndex(pControl.Name)
  217.        If i >= 0 Then
  218.            Me.List.RemoveAt(i)
  219.        End If
  220.    End Sub
  221. End Class
  222.  
  223. #End Region
  224.  
  225. #Region "ValidationControl"
  226.  
  227. ''' <summary>
  228. ''' ValidationControl class is used to hold any control from windows form.
  229. ''' 'It holds any control in 'ControlObj' property.
  230. ''' </summary>
  231. Public Class ValidationControl
  232.  
  233.    Private _control As Object
  234.    Private _displayname As String
  235.    Private _errormessage As String
  236.    Private _validate As Boolean = True
  237.  
  238.    ''' <summary>
  239.    ''' Decides weather control is to be validated. Default value is TRUE.
  240.    ''' </summary>
  241.    ''' <value><c>true</c> if validate; otherwise, <c>false</c>.</value>
  242.    Public Property Validate() As Boolean
  243.        Get
  244.            Return _validate
  245.        End Get
  246.        Set(ByVal Value As Boolean)
  247.            _validate = Value
  248.        End Set
  249.    End Property
  250.  
  251.    ''' <summary>
  252.    ''' ControlObj is a Control from windows form which is to be validated.
  253.    ''' </summary>
  254.    ''' <value>The control object.</value>
  255.    Public Property ControlObj() As Object
  256.        Get
  257.            Return _control
  258.        End Get
  259.        Set(ByVal Value As Object)
  260.            _control = Value
  261.        End Set
  262.    End Property
  263.  
  264.    ''' <summary>
  265.    ''' DisplayName property is used for displaying summary message to user.
  266.    ''' This field name will be displayed in summary message.
  267.    ''' </summary>
  268.    ''' <value>The display name.</value>
  269.    Public Property DisplayName() As String
  270.        Get
  271.            Return _displayname
  272.        End Get
  273.        Set(ByVal Value As String)
  274.            _displayname = Value
  275.        End Set
  276.    End Property
  277.  
  278.    ''' <summary>
  279.    ''' ErrorMessage is also used for displaying summary message.
  280.    ''' </summary>
  281.    ''' <value>The error message.</value>
  282.    Public Property ErrorMessage() As String
  283.        Get
  284.            Return _errormessage
  285.        End Get
  286.        Set(ByVal Value As String)
  287.            _errormessage = Value
  288.        End Set
  289.    End Property
  290.  
  291. End Class
  292.  
  293. #End Region

Escribí este Form para probar su utilidad:



Código
  1. Public Class ErrorProviderExtended_TestForm
  2.  
  3.    ''' <summary>
  4.    ''' The ErrorProviderExtended instance.
  5.    ''' </summary>
  6.    Private WithEvents MyErrorProvider As New ErrorProviderExtended
  7.  
  8.    ''' <summary>
  9.    ''' Control to validate its content.
  10.    ''' </summary>
  11.    Private WithEvents tbValue As New TextBox
  12.  
  13.    ''' <summary>
  14.    ''' Control that validates general errors.
  15.    ''' </summary>
  16.    Private WithEvents btValidator As New Button
  17.  
  18.    ''' <summary>
  19.    ''' Control that reports the current error message.
  20.    ''' </summary>
  21.    Private lblError As New Label
  22.  
  23.    ''' <summary>
  24.    ''' Control used to indicate a textbox hint.
  25.    ''' </summary>
  26.    Private lblHint As New Label
  27.  
  28.    ''' <summary>
  29.    ''' This value determines whether exists errors that need to be fixed.
  30.    ''' </summary>
  31.    Dim ErrorExists As Boolean = False
  32.  
  33.    Public Sub New()
  34.  
  35.        ' This call is required by the designer.
  36.        InitializeComponent()
  37.  
  38.        With Me.lblHint
  39.            .Location = New Point(10, 10)
  40.            .Text = "Type an 'Int32' value:"
  41.            .ForeColor = Color.WhiteSmoke
  42.            .AutoSize = True
  43.        End With
  44.  
  45.        With Me.tbValue
  46.            .Location = New Point(15, 25)
  47.            .Size = New Size(100, Me.tbValue.Height)
  48.        End With
  49.  
  50.        With Me.lblError
  51.            .Location = New Point(10, 50)
  52.            .Text = ""
  53.            .ForeColor = Color.WhiteSmoke
  54.            .AutoSize = True
  55.        End With
  56.  
  57.        With Me.btValidator
  58.            .Location = New Point(Me.lblError.Location.X, Me.lblError.Location.Y + 20)
  59.            .Text = "Validate"
  60.            .FlatStyle = FlatStyle.System
  61.        End With
  62.  
  63.        With Me
  64.            .MaximizeBox = False
  65.            .StartPosition = FormStartPosition.CenterScreen
  66.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  67.            .Size = New Point(220, 150)
  68.            .BackColor = Color.FromArgb(34, 34, 36)
  69.            .Controls.AddRange({Me.lblHint, Me.lblError, Me.tbValue, Me.btValidator})
  70.        End With
  71.  
  72.    End Sub
  73.  
  74.    Private Sub Test_Load() Handles Me.Load
  75.  
  76.        With MyErrorProvider
  77.            .Controls.Add(Me.tbValue, "Int32")
  78.            .Controls(Me.tbValue).Validate = True
  79.            .SummaryMessage = "Following fields are mandatory."
  80.        End With
  81.  
  82.        ' Change the textbox text to produce an intentional error.
  83.        tbValue.AppendText(" ")
  84.        tbValue.Clear()
  85.  
  86.    End Sub
  87.  
  88.    Private Sub Button1_Click() _
  89.    Handles btValidator.Click
  90.  
  91.        ' The following function checks all empty fields and returns TRUE if all fields are entered.
  92.        ' If any mandotary field is empty this function displays a message and returns FALSE.
  93.        If MyErrorProvider.CheckAndShowSummaryErrorMessage(ShowMessage:=True) Then
  94.  
  95.            If Not Me.ErrorExists Then
  96.                MessageBox.Show("Data submited successfully.", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
  97.            Else
  98.                MessageBox.Show("Data cannot be submited, fix the error(s).", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
  99.            End If
  100.  
  101.        End If
  102.  
  103.    End Sub
  104.  
  105.    ''' <summary>
  106.    ''' Handles the TextChanged event of the tbValue control.
  107.    ''' </summary>
  108.    Private Sub tbValue_TextChanged(sender As Object, e As EventArgs) _
  109.    Handles tbValue.TextChanged
  110.  
  111.        Dim Value As String = sender.text
  112.  
  113.        If String.IsNullOrEmpty(Value) Then
  114.            MyErrorProvider.SetError(sender, "TextBox is empty.")
  115.  
  116.        ElseIf Not Single.TryParse(Value, New Single) Then
  117.            MyErrorProvider.SetError(sender, "The value cannot contain letters.")
  118.  
  119.        ElseIf Single.TryParse(Value, New Single) Then
  120.  
  121.            If Value > Integer.MaxValue Then
  122.                MyErrorProvider.SetError(sender, "Value is greater than " & CStr(Integer.MaxValue))
  123.            Else ' Remove the error.
  124.                MyErrorProvider.SetError(sender, String.Empty)
  125.            End If
  126.  
  127.        Else ' Remove the error.
  128.            MyErrorProvider.SetError(sender, String.Empty)
  129.  
  130.        End If
  131.  
  132.        Me.lblError.Text = MyErrorProvider.GetError(sender)
  133.  
  134.        If String.IsNullOrEmpty(Me.lblError.Text) Then
  135.            Me.lblError.Text = "No errors :)"
  136.            Me.ErrorExists = False
  137.        Else
  138.            Me.ErrorExists = True
  139.        End If
  140.  
  141.    End Sub
  142.  
  143. End Class
  144.  
  145.  
  146.  
6988  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 19 Agosto 2014, 10:37 am
Obtiene las expresiones XPath de un documento Html, usando la librería HtmlAgilityPack.

PD: Si encuentran algún fallo porfavor reportármelo, no conozco mucho el tema de los XPath.



Código
  1.    ' Get Html XPaths
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    '
  6.    ' Dim Document As New HtmlAgilityPack.HtmlDocument
  7.    ' Document.LoadHtml(IO.File.ReadAllText("C:\File.html"))
  8.    ' Dim XpathList As List(Of String) = GetHtmlXPaths(Document)
  9.    ' ListBox1.Items.AddRange((From XPath As String In XpathList Select XPath).ToArray)
  10.  
  11.    ''' <summary>
  12.    ''' Gets all the XPath expressions of an <see cref="HtmlAgilityPack.HtmlDocument"/> document.
  13.    ''' </summary>
  14.    ''' <param name="Document">Indicates the <see cref="HtmlAgilityPack.HtmlDocument"/> document.</param>
  15.    ''' <returns>List(Of System.String).</returns>
  16.    Public Function GetHtmlXPaths(ByVal Document As HtmlAgilityPack.HtmlDocument) As List(Of String)
  17.  
  18.        Dim XPathList As New List(Of String)
  19.        Dim XPath As String = String.Empty
  20.  
  21.        For Each Child As HtmlAgilityPack.HtmlNode In Document.DocumentNode.ChildNodes
  22.  
  23.            If Child.NodeType = HtmlAgilityPack.HtmlNodeType.Element Then
  24.                GetHtmlXPaths(Child, XPathList, XPath)
  25.            End If
  26.  
  27.        Next Child
  28.  
  29.        Return XPathList
  30.  
  31.    End Function
  32.  
  33.    ''' <summary>
  34.    ''' Gets all the XPath expressions of an <see cref="HtmlAgilityPack.HtmlNode"/>.
  35.    ''' </summary>
  36.    ''' <param name="Node">Indicates the <see cref="HtmlAgilityPack.HtmlNode"/>.</param>
  37.    ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
  38.    ''' <param name="XPath">Indicates the current XPath.</param>
  39.    Private Sub GetHtmlXPaths(ByVal Node As HtmlAgilityPack.HtmlNode,
  40.                              ByRef XPathList As List(Of String),
  41.                              Optional ByVal XPath As String = Nothing)
  42.  
  43.        XPath &= Node.XPath.Substring(Node.XPath.LastIndexOf("/"c))
  44.  
  45.        Const ClassNameFilter As String = "[@class='{0}']"
  46.        Dim ClassName As String = Node.GetAttributeValue("class", String.Empty)
  47.  
  48.        If Not String.IsNullOrEmpty(ClassName) Then
  49.            XPath &= String.Format(ClassNameFilter, ClassName)
  50.        End If
  51.  
  52.        If Not XPathList.Contains(XPath) Then
  53.            XPathList.Add(XPath)
  54.        End If
  55.  
  56.        For Each Child As HtmlAgilityPack.HtmlNode In Node.ChildNodes
  57.  
  58.            If Child.NodeType = HtmlAgilityPack.HtmlNodeType.Element Then
  59.                GetHtmlXPaths(Child, XPathList, XPath)
  60.            End If
  61.  
  62.        Next Child
  63.  
  64.    End Sub
  65.  
6989  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 19 Agosto 2014, 04:33 am
Convierte un String a HTMLDocument

Código
  1.    ' String To HtmlDocument
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    ' Dim Document As HtmlDocument = StringToHtmlDocument(IO.File.ReadAllText("C:\File.html", Text.Encoding.Default))
  6.    '
  7.    ''' <summary>
  8.    ''' Converts a <see cref="String"/> to an <see cref="HTMLDocument"/>.
  9.    ''' </summary>
  10.    ''' <param name="str">Indicates the string.</param>
  11.    ''' <returns>The <see cref="HTMLDocument"/> object.</returns>
  12.    Public Function StringToHtmlDocument(ByVal str As String) As HtmlDocument
  13.  
  14.        Using wb As New WebBrowser
  15.  
  16.            wb.ScriptErrorsSuppressed = True
  17.            wb.DocumentText = ""
  18.            wb.Document.OpenNew(replaceInHistory:=True)
  19.            wb.Document.Write(str)
  20.            Return wb.Document
  21.  
  22.        End Using
  23.  
  24.    End Function



Obtiene los XPaths de un XMLDocument:



Código
  1.    ' Get XPaths
  2.    ' By Elektro
  3.    '
  4.    ' Example Usage:
  5.    '
  6.    ' Dim xDoc As New Xml.XmlDocument
  7.    ' xDoc.Load("C:\File.xml")
  8.    ' Dim XPathList As List(Of String) = GetXPaths(xDoc)
  9.    ' ListBox1.Items.AddRange((From XPath As String In XPathList Select XPath).ToArray)
  10.  
  11.    ''' <summary>
  12.    ''' Gets all the XPath expressions of an XML Document.
  13.    ''' </summary>
  14.    ''' <param name="Document">Indicates the XML document.</param>
  15.    ''' <returns>List(Of System.String).</returns>
  16.    Public Function GetXPaths(ByVal Document As Xml.XmlDocument) As List(Of String)
  17.  
  18.        Dim XPathList As New List(Of String)
  19.  
  20.        Dim XPath As String = String.Empty
  21.  
  22.        For Each Child As Xml.XmlNode In Document.ChildNodes
  23.  
  24.            If Child.NodeType = Xml.XmlNodeType.Element Then
  25.                GetXPaths(Child, XPathList, XPath)
  26.            End If
  27.  
  28.        Next ' child
  29.  
  30.        Return XPathList
  31.  
  32.    End Function
  33.  
  34.    ''' <summary>
  35.    ''' Gets all the XPath expressions of an XML Node.
  36.    ''' </summary>
  37.    ''' <param name="Node">Indicates the XML node.</param>
  38.    ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
  39.    ''' <param name="XPath">Indicates the current XPath.</param>
  40.    Private Sub GetXPaths(ByVal Node As Xml.XmlNode,
  41.                          ByRef XPathList As List(Of String),
  42.                          Optional ByVal XPath As String = Nothing)
  43.  
  44.        XPath &= "/" & Node.Name
  45.  
  46.        If Not XPathList.Contains(XPath) Then
  47.            XPathList.Add(XPath)
  48.        End If
  49.  
  50.        For Each Child As Xml.XmlNode In Node.ChildNodes
  51.  
  52.            If Child.NodeType = Xml.XmlNodeType.Element Then
  53.                GetXPaths(Child, XPathList, XPath)
  54.            End If
  55.  
  56.        Next ' child
  57.  
  58.    End Sub
  59.  
6990  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 19 Agosto 2014, 02:28 am
Citar
asumo que el programa lee que son números desde el 01 al 30 correlativamente ?

Tu input, del 1 al 30:
input
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Mi input, del 1 al 30:
Citar
Código
  1. Enumerable.Range(1I, 30I).ToArray ' 1 to 30

Recuerda que el código que te he ofrecido solo es un algoritmo que mimica los pasos que has explicado en tu ejemplo, es decir: 30 combinaciones del 1 al 30, dando saltos de 3 posiciones, los combos de 10 numeros de longitud cada combo, y con numeros aleatorios dentro de un rango específico en los espacios libres a rellenar.



Citar
no es la idea
¿Que te impide modificar manualmente el array?:

Código
  1. ReadOnly FixedValues As Integer() = {1, 5, 19, 22, 34, 55, 66, 88, 99, etc...}

El código actuará (o debería actuar) de la misma manera.



Citar
donde muestro los resultados  estoy poniendo esto pero solo me sale  " colección "

Es que le estás intentando pasar una colección que tiene más colecciones dentro, es decir, una Lista de Listas (List(Of List(Of Integer))), debes pasarle solo las colecciones del interior, las sub-listas de la lista (List(Of Integer)) y tienes que pasarselas como String.

Puedes hacerlo por ejemplo de una de estas dos maneras:

1.
Código
  1.        Combos.ForEach(Sub(comb As List(Of Integer))
  2.                           ListBox1.Items.Add(String.Join(", ", comb))
  3.                       End Sub)
  4.  

2.
Código
  1.        ListBox1.Items.AddRange(
  2.            (From comb As List(Of Integer) In Combos
  3.             Select String.Join(", ", comb)).ToArray
  4.         )
  5.  



De todas formas habia un fallo con la colección Combos (al utilizar el método Combo.Clear se limpiaba también la referencia del Combo que habia dentro de Combos, por ende al final Combos resultaba ser una colección de listas vacías) así que te dejo esta nueva versión corregida y con el ejemplo del Listbox:

Código
  1. Public Class LuisClass_v2
  2.  
  3.    ReadOnly Randomizer As New Random
  4.  
  5.    ReadOnly FixedValues As Integer() =
  6.        Enumerable.Range(1I, 30I).ToArray ' 1 to 30
  7.  
  8.    ReadOnly RandomValues As Integer() =
  9.        Enumerable.Range(FixedValues.First, FixedValues.Last).ToArray ' 1 to 30
  10.  
  11.    Dim Combo As List(Of Integer) = Nothing
  12.    Dim Combos As New List(Of List(Of Integer))
  13.  
  14.    Private Sub Test() Handles MyBase.Shown
  15.  
  16.        Dim IndexCounter As Integer = FixedValues.First ' 1
  17.        Dim LenCounter As Integer = 0I
  18.  
  19.        Const NumStep As Integer = 3I
  20.        Const NumLen As Integer = 10I
  21.  
  22.        Do Until IndexCounter > FixedValues.Last ' IndexCounter > 30
  23.  
  24.            Combo = New List(Of Integer)
  25.  
  26.            For Num As Integer = IndexCounter To (FixedValues.Count) Step NumStep ' 1 to 30 Step 3
  27.  
  28.                Combo.Add(Num)
  29.                LenCounter += 1I
  30.  
  31.                If LenCounter >= NumLen Then
  32.                    Exit For
  33.                End If
  34.  
  35.            Next ' Num
  36.  
  37.            If LenCounter < NumLen Then ' If LenCounter < 10
  38.  
  39.                For RandomNum As Integer = 1I To (NumLen - LenCounter)
  40.  
  41.                    Dim n As Integer = Randomizer.Next(RandomValues.First, RandomValues.Last)
  42.  
  43.                    Do Until Not Combo.Contains(n)
  44.                        n = Randomizer.Next(RandomValues.First, RandomValues.Last)
  45.                    Loop
  46.  
  47.                    Combo.Add(n)
  48.  
  49.                Next ' RandomNum
  50.  
  51.            End If ' LenCounter < NumLen
  52.  
  53. #If DEBUG Then ' #Debug
  54.            Debug.WriteLine(String.Join(", ", Combo))
  55.            ' Stop
  56. #End If
  57.  
  58.            Combos.Add(Combo)
  59.            IndexCounter += 1I
  60.            LenCounter = 0I
  61.  
  62.        Loop ' IndexCounter >= FixedValues.Last
  63.  
  64.        ' ********
  65.        ' Listbox:
  66.        ' ********
  67.        Combos.ForEach(Sub(comb As List(Of Integer))
  68.  
  69.                           ' Convierto la Lista a 'String', le añado los ceros, y añado el string formateado al Listbox.
  70.                           ListBox1.Items.Add(String.Join(", ",
  71.                                                          From value As String In comb
  72.                                                          Select If(value.Length = 1I,
  73.                                                                    value.Insert(0I, "0"c),
  74.                                                                    value)))
  75.  
  76.                       End Sub)
  77.  
  78.    End Sub ' Test
  79.  
  80. End Class
Páginas: 1 ... 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 [699] 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 ... 1254
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines