|
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): ' Draw Grid ' By Elektro ' ''' <summary> ''' Draws a grid in the specified <see cref="System.Drawing.Graphics"/> space. ''' </summary> ''' <param name="g">Indicates the <see cref="System.Drawing.Graphics"/> object.</param> ''' <param name="GridSize">Indicates the size of the grid.</param> ''' <param name="Columns">Indicates the amount of columns to draw.</param> ''' <param name="Rows">Indicates the amount of rows to draw.</param> ''' <param name="ColorColumns">Indicates the columns color.</param> ''' <param name="ColorRows">Indicates the rows color.</param> ''' <param name="DrawBorder">If set to <c>true</c>, a border is drawn on the grid edges.</param> ''' <param name="ColorBorder">Indicates the border color. Default value is the same color as <param ref="ColorColumns"/></param> ''' <param name="ColorStyle">Indicates the colors <see cref="System.Drawing.Drawing2D.DashStyle"/>.</param> ''' <exception cref="System.ArgumentException"> ''' GridSize.Width is not divisible by the specified number of columns. ''' or ''' GridSize.Height is not divisible by the specified number of rows. ''' </exception> Private Sub DrawGrid(ByVal g As Graphics, ByVal GridSize As Size, ByVal Columns As Integer, ByVal Rows As Integer, ByVal ColorColumns As Color, ByVal ColorRows As Color, Optional ByVal DrawBorder As Boolean = True, Optional ByVal ColorBorder As Color = Nothing, Optional ByVal ColorStyle As Drawing2D.DashStyle = Drawing2D.DashStyle.Solid) If Not (GridSize.Width Mod Columns = 0I) Then Throw New ArgumentException( "GridSize.Width is not divisible by the specified number of columns.", "GridSize") Exit Sub ElseIf Not (GridSize.Height Mod Rows = 0I) Then Throw New ArgumentException( "GridSize.Height is not divisible by the specified number of rows.", "GridSize") Exit Sub End If Dim SectorWidth As Integer = (GridSize.Width \ Columns) Dim SectorHeight As Integer = (GridSize.Height \ Rows) Using PenRow As New Pen(ColorRows) With {.DashStyle = ColorStyle} Using PenCol As New Pen(ColorColumns) With {.DashStyle = ColorStyle} For row As Integer = 0I To GridSize.Height - 1 Step (SectorHeight) For col As Integer = 0I To GridSize.Width - 1 Step SectorWidth ' Draw the vertical grid-lines. g.DrawLine(PenCol, New Point(x:=col - 1, y:=0I), New Point(x:=col - 1, y:=GridSize.Height)) Next col ' Draw the horizontal grid-lines. g.DrawLine(PenRow, New Point(x:=0I, y:=row - 1), New Point(x:=GridSize.Width, y:=row - 1)) Next row If DrawBorder Then Using PenBorder As New Pen(If(ColorBorder = Nothing, ColorColumns, ColorBorder)) With {.DashStyle = ColorStyle} ' Draw the vertical left grid-line. g.DrawLine(PenBorder, New Point(x:=0, y:=0I), New Point(x:=0, y:=GridSize.Height)) ' Draw the vertical right grid-line. g.DrawLine(PenBorder, New Point(x:=(GridSize.Width - 1I), y:=0I), New Point(x:=(GridSize.Width - 1I), y:=GridSize.Height)) ' Draw the horizontal top grid-line. g.DrawLine(PenBorder, New Point(x:=0I, y:=0I), New Point(x:=GridSize.Width, y:=0I)) ' Draw the horizontal bottom grid-line. g.DrawLine(PenBorder, New Point(x:=0I, y:=(GridSize.Height - 1I)), New Point(x:=GridSize.Width, y:=(GridSize.Height - 1I))) End Using ' PenBorder End If ' DrawBorder End Using ' PenCol End Using ' PenRow End Sub
Y este método lo escribí para obtener los rectangles de la rejilla: ' Get Grid ' By Elektro ' ''' <summary> ''' Calculates the drawing of a grid with the specified size, ''' and returns a<see cref="List(Of Rectangle)"/> that contains the grid-sector specifications. ''' </summary> ''' <param name="GridSize">Indicates the grid size.</param> ''' <param name="Columns">Indicates the amount of columns.</param> ''' <param name="Rows">Indicates the amount of rows.</param> ''' <returns>A <see cref="List(Of Rectangle)"/> that contains the grid-sector specifications.</returns> ''' <exception cref="System.ArgumentException"> ''' GridSize.Width is not divisible by the specified number of columns. ''' or ''' GridSize.Height is not divisible by the specified number of rows. ''' </exception> Private Function GetGrid(ByVal GridSize As Size, ByVal Columns As Integer, ByVal Rows As Integer) As List(Of Rectangle) If Not (GridSize.Width Mod Columns = 0I) Then Throw New ArgumentException( "GridSize.Width is not divisible by the specified number of columns.", "GridSize") Return Nothing ElseIf Not (GridSize.Height Mod Rows = 0I) Then Throw New ArgumentException( "GridSize.Height is not divisible by the specified number of rows.", "GridSize") Return Nothing End If Dim Sectors As New List(Of Rectangle) Dim SectorWidth As Integer = GridSize.Width \ Columns Dim SectorHeight As Integer = GridSize.Height \ Rows For row As Integer = 0I To GridSize.Height - 1 Step (SectorHeight) For col As Integer = 0I To GridSize.Width - 1 Step SectorWidth Sectors.Add(New Rectangle(col, row, SectorWidth, SectorHeight)) Next col Next row Return Sectors 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 ) Public Property currentsector As Integer = 0 Public Property currentcolor As Color = Color.Gray Public ReadOnly Property GridSectors As List(Of Rectangle) Get Return Me.GetGrid(GridSize:=PictureBox1.ClientRectangle.Size, Columns:=5, Rows:=5) End Get End Property Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown Label1.Text = "Sectors: " & GridSectors.Count End Sub Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _ Handles PictureBox1.Paint Me.DrawGrid(g:=e.Graphics, GridSize:=sender.ClientRectangle.Size, Columns:=5, Rows:=5, ColorColumns:=Color.YellowGreen, ColorRows:=Color.YellowGreen, DrawBorder:=True, ColorBorder:=Nothing, ColorStyle:=Drawing2D.DashStyle.Solid) End Sub Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove Dim Sectors As List(Of Rectangle) = Me.GridSectors For X As Integer = 0I To (Sectors.Count - 1I) If Sectors(X).Contains(sender.PointToClient(MousePosition)) Then Dim myBrush As New SolidBrush(currentcolor) Using formGraphics As Graphics = sender.CreateGraphics() formGraphics.FillRectangle(myBrush, New Rectangle(Sectors(X).X + 1, Sectors(X).Y + 1, Sectors(X).Width - 2, Sectors(X).Height - 2)) myBrush.Dispose() End Using ' formGraphics currentsector = X + 1 Label2.Text = "Current sector: " & currentsector Else Dim myBrush As New SolidBrush(Color.Black) Using formGraphics As Graphics = sender.CreateGraphics() formGraphics.FillRectangle(myBrush, New Rectangle(Sectors(X).X + 1, Sectors(X).Y + 1, Sectors(X).Width - 2, Sectors(X).Height - 2)) myBrush.Dispose() End Using ' formGraphics End If ' Sectors(X).Contains(...) Next X End Sub Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.MouseDown Label3.Text = "Last Sector Clicked: " & currentsector ' Dim sector As Rectangle = Me.GridSectors(currentsector - 1) currentcolor = Color.Red PictureBox1.Cursor = Cursors.Hand PictureBox1.Update() 'Dim myBrush As New SolidBrush(Color.Red) 'Using formGraphics As Graphics = PictureBox1.CreateGraphics() ' formGraphics.FillRectangle(myBrush, New Rectangle(sector.X + 1, sector.Y + 1, sector.Width - 2, sector.Height - 2)) ' myBrush.Dispose() 'End Using ' formGraphics End Sub Private Sub PictureBox1_Clic(sender As Object, e As EventArgs) Handles PictureBox1.MouseUp Label3.Text = "Last Sector Clicked: " & currentsector ' Dim sector As Rectangle = Me.GridSectors(currentsector - 1) currentcolor = Color.Gray PictureBox1.Cursor = Cursors.Default PictureBox1.Update() 'Dim myBrush As New SolidBrush(Color.Red) 'Using formGraphics As Graphics = PictureBox1.CreateGraphics() ' formGraphics.FillRectangle(myBrush, New Rectangle(sector.X + 1, sector.Y + 1, sector.Width - 2, sector.Height - 2)) ' myBrush.Dispose() 'End Using ' formGraphics 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
|
|
|
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: ' Example of sharing memory across different running applications. ' By Elektro ' ' ************************* ' This is the Application 1 ' ************************* #Region " Imports " Imports System.IO.MemoryMappedFiles #End Region #Region " Application 2 " ''' <summary> ''' Class MemoryMappedFile_Form1. ''' This should be the Class used to compile our first application. ''' </summary> Public Class MemoryMappedFile_Form1 ' The controls to create on execution-time. Dim WithEvents btMakeFile As New Button ' Writes the memory. Dim WithEvents btReadFile As New Button ' Reads the memory. Dim tbMessage As New TextBox ' Determines the string to map into memory. Dim tbReceptor As New TextBox ' Print the memory read's result. Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons. Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'. ''' <summary> ''' Indicates the name of our memory-file. ''' </summary> Private ReadOnly MemoryName As String = "My Memory-File Name" ''' <summary> ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes. ''' </summary> Private ReadOnly MemoryBufferSize As Integer = 1024I ''' <summary> ''' Indicates the string to map in memory. ''' </summary> Private ReadOnly Property strMessage As String Get Return tbMessage.Text End Get End Property ''' <summary> ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form1"/> class. ''' </summary> Public Sub New() ' This call is required by the designer. InitializeComponent() ' Set the properties of the controls. With lbInfotbMessage .Location = New Point(20, 10) .Text = "Type in this TextBox the message to write in memory:" .AutoSize = True ' .Size = tbReceptor.Size End With With tbMessage .Text = "Hello world from application one!" .Location = New Point(20, 30) .Size = New Size(310, Me.tbMessage.Height) End With With btMakeFile .Text = "Write Memory" .Size = New Size(130, 45) .Location = New Point(20, 50) End With With btReadFile .Text = "Read Memory" .Size = New Size(130, 45) .Location = New Point(200, 50) End With With tbReceptor .Location = New Point(20, 130) .Size = New Size(310, 100) .Multiline = True End With With lbInfoButtons .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30) .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications." .AutoSize = False .Size = tbReceptor.Size End With ' Set the Form properties. With Me .Text = "Application 1" .Size = New Size(365, 300) .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle .MaximizeBox = False .StartPosition = FormStartPosition.CenterScreen End With ' Add the controls on the UI. Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons}) End Sub ''' <summary> ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>. ''' </summary> ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param> ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param> ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param> Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte()) ' Create or open the memory-mapped file. Dim MessageFile As MemoryMappedFile = MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite) ' Write the byte-sequence into memory. Using Writer As MemoryMappedViewAccessor = MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite) ' Firstly fill with null all the buffer. Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize) ' Secondly write the byte-data. Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length) End Using ' Writer End Sub ''' <summary> ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>. ''' </summary> ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param> ''' <param name="BufferLength">The buffer-length to read in.</param> ''' <returns>System.Byte().</returns> Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte() Try Using MemoryFile As MemoryMappedFile = MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read) Using Reader As MemoryMappedViewAccessor = MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read) Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {} Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length) Return ReadBytes End Using ' Reader End Using ' MemoryFile Catch ex As IO.FileNotFoundException Throw Return Nothing End Try End Function ''' <summary> ''' Handles the 'Click' event of the 'btMakeFile' control. ''' </summary> Private Sub btMakeFile_Click() Handles btMakeFile.Click ' Get the byte-data to create the memory-mapped file. Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage) ' Create the memory-mapped file. Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData) End Sub ''' <summary> ''' Handles the 'Click' event of the 'btReadFile' control. ''' </summary> Private Sub btReadFile_Click() Handles btReadFile.Click Dim ReadBytes As Byte() Try ' Read the byte-sequence from memory. ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize) Catch ex As IO.FileNotFoundException Me.tbReceptor.Text = "Memory-mapped file does not exist." Exit Sub End Try ' Convert the bytes to String. Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray) ' Remove null chars (leading zero-bytes) Message = Message.Trim({ControlChars.NullChar}) ' Print the message. tbReceptor.Text = Message End Sub End Class #End Region
Esta sería la aplicación número 2, creen un nuevo proyecto, copien y compilen este Form: ' Example of sharing memory across different running applications. ' By Elektro ' ' ************************* ' This is the Application 2 ' ************************* #Region " Imports " Imports System.IO.MemoryMappedFiles #End Region #Region " Application 2 " ''' <summary> ''' Class MemoryMappedFile_Form2. ''' This should be the Class used to compile our first application. ''' </summary> Public Class MemoryMappedFile_Form2 ' The controls to create on execution-time. Dim WithEvents btMakeFile As New Button ' Writes the memory. Dim WithEvents btReadFile As New Button ' Reads the memory. Dim tbMessage As New TextBox ' Determines the string to map into memory. Dim tbReceptor As New TextBox ' Print the memory read's result. Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons. Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'. ''' <summary> ''' Indicates the name of our memory-file. ''' </summary> Private ReadOnly MemoryName As String = "My Memory-File Name" ''' <summary> ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes. ''' </summary> Private ReadOnly MemoryBufferSize As Integer = 1024I ''' <summary> ''' Indicates the string to map in memory. ''' </summary> Private ReadOnly Property strMessage As String Get Return tbMessage.Text End Get End Property ''' <summary> ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form2"/> class. ''' </summary> Public Sub New() ' This call is required by the designer. InitializeComponent() ' Set the properties of the controls. With lbInfotbMessage .Location = New Point(20, 10) .Text = "Type in this TextBox the message to write in memory:" .AutoSize = True ' .Size = tbReceptor.Size End With With tbMessage .Text = "Hello world from application two!" .Location = New Point(20, 30) .Size = New Size(310, Me.tbMessage.Height) End With With btMakeFile .Text = "Write Memory" .Size = New Size(130, 45) .Location = New Point(20, 50) End With With btReadFile .Text = "Read Memory" .Size = New Size(130, 45) .Location = New Point(200, 50) End With With tbReceptor .Location = New Point(20, 130) .Size = New Size(310, 100) .Multiline = True End With With lbInfoButtons .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30) .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications." .AutoSize = False .Size = tbReceptor.Size End With ' Set the Form properties. With Me .Text = "Application 2" .Size = New Size(365, 300) .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle .MaximizeBox = False .StartPosition = FormStartPosition.CenterScreen End With ' Add the controls on the UI. Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons}) End Sub ''' <summary> ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>. ''' </summary> ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param> ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param> ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param> Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte()) ' Create or open the memory-mapped file. Dim MessageFile As MemoryMappedFile = MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite) ' Write the byte-sequence into memory. Using Writer As MemoryMappedViewAccessor = MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite) ' Firstly fill with null all the buffer. Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize) ' Secondly write the byte-data. Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length) End Using ' Writer End Sub ''' <summary> ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>. ''' </summary> ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param> ''' <param name="BufferLength">The buffer-length to read in.</param> ''' <returns>System.Byte().</returns> Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte() Try Using MemoryFile As MemoryMappedFile = MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read) Using Reader As MemoryMappedViewAccessor = MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read) Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {} Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length) Return ReadBytes End Using ' Reader End Using ' MemoryFile Catch ex As IO.FileNotFoundException Throw Return Nothing End Try End Function ''' <summary> ''' Handles the 'Click' event of the 'btMakeFile' control. ''' </summary> Private Sub btMakeFile_Click() Handles btMakeFile.Click ' Get the byte-data to create the memory-mapped file. Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage) ' Create the memory-mapped file. Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData) End Sub ''' <summary> ''' Handles the 'Click' event of the 'btReadFile' control. ''' </summary> Private Sub btReadFile_Click() Handles btReadFile.Click Dim ReadBytes As Byte() Try ' Read the byte-sequence from memory. ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize) Catch ex As IO.FileNotFoundException Me.tbReceptor.Text = "Memory-mapped file does not exist." Exit Sub End Try ' Convert the bytes to String. Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray) ' Remove null chars (leading zero-bytes) Message = Message.Trim({ControlChars.NullChar}) ' Print the message. tbReceptor.Text = Message End Sub End Class #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.  Public Class MagicGraphics_Test Private WithEvents RotationTimer As New Timer With {.Enabled = True, .Interval = 25} Dim SC As MagicGraphics.ShapeContainer Private Sub Tst_Shown() Handles MyBase.Shown SC = New MagicGraphics.ShapeContainer(PictureBox1.CreateGraphics, PictureBox1.Width, PictureBox1.Height, Color.Black, PictureBox1.Image) PictureBox1.Image = SC.BMP SC.AutoFlush = False Dim Sq As New MagicGraphics.Rectangle(New Pen(Color.Black, 3), Brushes.Aqua, 60, 20, 50, 50) Sq.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(60, 0), Color.Yellow, Color.Red) SC.AddShape(Sq) Dim El As New MagicGraphics.Ellipse(New Pen(Color.Black, 3), Brushes.Olive, 60, 88, 50, 71) El.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(30, 0), Color.Red, Color.SteelBlue) SC.AddShape(El) RotationTimer.Start() End Sub Private Sub RotationTimer_Tick() Handles RotationTimer.Tick Static Direction As Integer = 1I ' 0 = Left, 1 = Right For X As Integer = 0I To (SC.ShapesL.Count - 1) Dim shp As MagicGraphics.Shape = SC.ShapesL(X) shp.Rotate(-8) If shp.Location.X > (PictureBox1.Width - shp.Width) Then Direction = 1I ' Right ElseIf shp.Location.X < PictureBox1.Location.X Then Direction = 0I ' Left End If If Direction = 0 Then shp.Move(shp.Location.X + 2, shp.Location.Y) Else shp.Move(shp.Location.X - 2, shp.Location.Y) End If ' Debug.WriteLine(String.Format("Shape {0} Rotation: {1}", CStr(X), shp.Rotation)) Next X SC.Flush() End Sub End Class
|
|
|
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 ? 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?  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 esoPD: Por si acaso te recuerdo que para ordenar de mayor a menor lo tienes facil usando una LINQ-query: 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[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 RegionEDITO: Ya lo he documentado yo así rapidamente: #Region "Error Provider Extended" ''' <summary> ''' Provides a user interface for indicating that a control on a form has an error associated with it. ''' </summary> Public Class ErrorProviderExtended Inherits System.Windows.Forms.ErrorProvider Private _validationcontrols As New ValidationControlCollection Private _summarymessage As String = "Please enter following mandatory fields," ''' <summary> ''' Gets or sets the summary message. ''' 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. ''' </summary> ''' <value>The summary message.</value> Public Property SummaryMessage() As String Get Return _summarymessage End Get Set(ByVal Value As String) _summarymessage = Value End Set End Property ''' <summary> ''' Gets or sets the controls which should be validated. ''' </summary> ''' <value>The controls.</value> Public Property Controls() As ValidationControlCollection Get Return _validationcontrols End Get Set(ByVal Value As ValidationControlCollection) _validationcontrols = Value End Set End Property ''' <summary> ''' Checks the and show summary error message. ''' </summary> ''' <param name="ShowMessage"> ''' If set to <c>true</c>, This function displays a message box which contains all the field names which are empty. ''' </param> ''' <returns><c>true</c> if all fields on form are entered, <c>false</c> otherwise.</returns> Public Function CheckAndShowSummaryErrorMessage(Optional ByVal ShowMessage As Boolean = False) 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 If ShowMessage Then msg &= "> " & Controls(i).DisplayName & vbNewLine End If SetError(Controls(i).ControlObj, Controls(i).ErrorMessage) berrors = True Else SetError(Controls(i).ControlObj, "") End If Else SetError(Controls(i).ControlObj, "") End If Next i If berrors Then If ShowMessage Then MessageBox.Show(msg, "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Stop) End If Return False Else Return True End If End Function ''' <summary> ''' Clears error messages from all controls. ''' </summary> Public Sub ClearAllErrorMessages() Dim i As Integer For i = 0 To Controls.Count - 1 SetError(Controls(i).ControlObj, "") Next End Sub ''' <summary> ''' Hooks validation event with all controls. ''' </summary> 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 ''' <summary> ''' Handles the Event event of the Validation control. ''' This event is hooked for all controls, ''' it sets an error message with the use of ErrorProvider ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param> Private Sub Validation_Event(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) 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 #Region "ValidationControlCollection" ''' <summary> ''' This class is used for holding all Validation Controls. ''' This class is collection of 'ValidationControl' class objects. ''' This class is used by 'ErrorProviderExtended' class. ''' </summary> 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 #Region "ValidationControl" ''' <summary> ''' ValidationControl class is used to hold any control from windows form. ''' 'It holds any control in 'ControlObj' property. ''' </summary> Public Class ValidationControl Private _control As Object Private _displayname As String Private _errormessage As String Private _validate As Boolean = True ''' <summary> ''' Decides weather control is to be validated. Default value is TRUE. ''' </summary> ''' <value><c>true</c> if validate; otherwise, <c>false</c>.</value> Public Property Validate() As Boolean Get Return _validate End Get Set(ByVal Value As Boolean) _validate = Value End Set End Property ''' <summary> ''' ControlObj is a Control from windows form which is to be validated. ''' </summary> ''' <value>The control object.</value> Public Property ControlObj() As Object Get Return _control End Get Set(ByVal Value As Object) _control = Value End Set End Property ''' <summary> ''' DisplayName property is used for displaying summary message to user. ''' This field name will be displayed in summary message. ''' </summary> ''' <value>The display name.</value> Public Property DisplayName() As String Get Return _displayname End Get Set(ByVal Value As String) _displayname = Value End Set End Property ''' <summary> ''' ErrorMessage is also used for displaying summary message. ''' </summary> ''' <value>The error message.</value> 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
Escribí este Form para probar su utilidad:  Public Class ErrorProviderExtended_TestForm ''' <summary> ''' The ErrorProviderExtended instance. ''' </summary> Private WithEvents MyErrorProvider As New ErrorProviderExtended ''' <summary> ''' Control to validate its content. ''' </summary> Private WithEvents tbValue As New TextBox ''' <summary> ''' Control that validates general errors. ''' </summary> Private WithEvents btValidator As New Button ''' <summary> ''' Control that reports the current error message. ''' </summary> Private lblError As New Label ''' <summary> ''' Control used to indicate a textbox hint. ''' </summary> Private lblHint As New Label ''' <summary> ''' This value determines whether exists errors that need to be fixed. ''' </summary> Dim ErrorExists As Boolean = False Public Sub New() ' This call is required by the designer. InitializeComponent() With Me.lblHint .Location = New Point(10, 10) .Text = "Type an 'Int32' value:" .ForeColor = Color.WhiteSmoke .AutoSize = True End With With Me.tbValue .Location = New Point(15, 25) .Size = New Size(100, Me.tbValue.Height) End With With Me.lblError .Location = New Point(10, 50) .Text = "" .ForeColor = Color.WhiteSmoke .AutoSize = True End With With Me.btValidator .Location = New Point(Me.lblError.Location.X, Me.lblError.Location.Y + 20) .Text = "Validate" .FlatStyle = FlatStyle.System End With With Me .MaximizeBox = False .StartPosition = FormStartPosition.CenterScreen .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle .Size = New Point(220, 150) .BackColor = Color.FromArgb(34, 34, 36) .Controls.AddRange({Me.lblHint, Me.lblError, Me.tbValue, Me.btValidator}) End With End Sub Private Sub Test_Load() Handles Me.Load With MyErrorProvider .Controls.Add(Me.tbValue, "Int32") .Controls(Me.tbValue).Validate = True .SummaryMessage = "Following fields are mandatory." End With ' Change the textbox text to produce an intentional error. tbValue.AppendText(" ") tbValue.Clear() End Sub Private Sub Button1_Click() _ Handles btValidator.Click ' The following function checks all empty fields and returns TRUE if all fields are entered. ' If any mandotary field is empty this function displays a message and returns FALSE. If MyErrorProvider.CheckAndShowSummaryErrorMessage(ShowMessage:=True) Then If Not Me.ErrorExists Then MessageBox.Show("Data submited successfully.", "", MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Data cannot be submited, fix the error(s).", "", MessageBoxButtons.OK, MessageBoxIcon.Error) End If End If End Sub ''' <summary> ''' Handles the TextChanged event of the tbValue control. ''' </summary> Private Sub tbValue_TextChanged(sender As Object, e As EventArgs) _ Handles tbValue.TextChanged Dim Value As String = sender.text If String.IsNullOrEmpty(Value) Then MyErrorProvider.SetError(sender, "TextBox is empty.") ElseIf Not Single.TryParse(Value, New Single) Then MyErrorProvider.SetError(sender, "The value cannot contain letters.") ElseIf Single.TryParse(Value, New Single) Then If Value > Integer.MaxValue Then MyErrorProvider.SetError(sender, "Value is greater than " & CStr(Integer.MaxValue)) Else ' Remove the error. MyErrorProvider.SetError(sender, String.Empty) End If Else ' Remove the error. MyErrorProvider.SetError(sender, String.Empty) End If Me.lblError.Text = MyErrorProvider.GetError(sender) If String.IsNullOrEmpty(Me.lblError.Text) Then Me.lblError.Text = "No errors :)" Me.ErrorExists = False Else Me.ErrorExists = True End If End Sub End Class
|
|
|
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.  ' Get Html XPaths ' By Elektro ' ' Example Usage: ' ' Dim Document As New HtmlAgilityPack.HtmlDocument ' Document.LoadHtml(IO.File.ReadAllText("C:\File.html")) ' Dim XpathList As List(Of String) = GetHtmlXPaths(Document) ' ListBox1.Items.AddRange((From XPath As String In XpathList Select XPath).ToArray) ''' <summary> ''' Gets all the XPath expressions of an <see cref="HtmlAgilityPack.HtmlDocument"/> document. ''' </summary> ''' <param name="Document">Indicates the <see cref="HtmlAgilityPack.HtmlDocument"/> document.</param> ''' <returns>List(Of System.String).</returns> Public Function GetHtmlXPaths(ByVal Document As HtmlAgilityPack.HtmlDocument) As List(Of String) Dim XPathList As New List(Of String) Dim XPath As String = String.Empty For Each Child As HtmlAgilityPack.HtmlNode In Document.DocumentNode.ChildNodes If Child.NodeType = HtmlAgilityPack.HtmlNodeType.Element Then GetHtmlXPaths(Child, XPathList, XPath) End If Next Child Return XPathList End Function ''' <summary> ''' Gets all the XPath expressions of an <see cref="HtmlAgilityPack.HtmlNode"/>. ''' </summary> ''' <param name="Node">Indicates the <see cref="HtmlAgilityPack.HtmlNode"/>.</param> ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param> ''' <param name="XPath">Indicates the current XPath.</param> Private Sub GetHtmlXPaths(ByVal Node As HtmlAgilityPack.HtmlNode, ByRef XPathList As List(Of String), Optional ByVal XPath As String = Nothing) XPath &= Node.XPath.Substring(Node.XPath.LastIndexOf("/"c)) Const ClassNameFilter As String = "[@class='{0}']" Dim ClassName As String = Node.GetAttributeValue("class", String.Empty) If Not String.IsNullOrEmpty(ClassName) Then XPath &= String.Format(ClassNameFilter, ClassName) End If If Not XPathList.Contains(XPath) Then XPathList.Add(XPath) End If For Each Child As HtmlAgilityPack.HtmlNode In Node.ChildNodes If Child.NodeType = HtmlAgilityPack.HtmlNodeType.Element Then GetHtmlXPaths(Child, XPathList, XPath) End If Next Child End Sub
|
|
|
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 ' String To HtmlDocument ' By Elektro ' ' Example Usage: ' Dim Document As HtmlDocument = StringToHtmlDocument(IO.File.ReadAllText("C:\File.html", Text.Encoding.Default)) ' ''' <summary> ''' Converts a <see cref="String"/> to an <see cref="HTMLDocument"/>. ''' </summary> ''' <param name="str">Indicates the string.</param> ''' <returns>The <see cref="HTMLDocument"/> object.</returns> Public Function StringToHtmlDocument(ByVal str As String) As HtmlDocument Using wb As New WebBrowser wb.ScriptErrorsSuppressed = True wb.DocumentText = "" wb.Document.OpenNew(replaceInHistory:=True) wb.Document.Write(str) Return wb.Document End Using End Function
Obtiene los XPaths de un XMLDocument:  ' Get XPaths ' By Elektro ' ' Example Usage: ' ' Dim xDoc As New Xml.XmlDocument ' xDoc.Load("C:\File.xml") ' Dim XPathList As List(Of String) = GetXPaths(xDoc) ' ListBox1.Items.AddRange((From XPath As String In XPathList Select XPath).ToArray) ''' <summary> ''' Gets all the XPath expressions of an XML Document. ''' </summary> ''' <param name="Document">Indicates the XML document.</param> ''' <returns>List(Of System.String).</returns> Public Function GetXPaths(ByVal Document As Xml.XmlDocument) As List(Of String) Dim XPathList As New List(Of String) Dim XPath As String = String.Empty For Each Child As Xml.XmlNode In Document.ChildNodes If Child.NodeType = Xml.XmlNodeType.Element Then GetXPaths(Child, XPathList, XPath) End If Next ' child Return XPathList End Function ''' <summary> ''' Gets all the XPath expressions of an XML Node. ''' </summary> ''' <param name="Node">Indicates the XML node.</param> ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param> ''' <param name="XPath">Indicates the current XPath.</param> Private Sub GetXPaths(ByVal Node As Xml.XmlNode, ByRef XPathList As List(Of String), Optional ByVal XPath As String = Nothing) XPath &= "/" & Node.Name If Not XPathList.Contains(XPath) Then XPathList.Add(XPath) End If For Each Child As Xml.XmlNode In Node.ChildNodes If Child.NodeType = Xml.XmlNodeType.Element Then GetXPaths(Child, XPathList, XPath) End If Next ' child End Sub
|
|
|
6990
|
Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :(
|
en: 19 Agosto 2014, 02:28 am
|
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: 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.
no es la idea ¿Que te impide modificar manualmente el array?: 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.
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. Combos.ForEach(Sub(comb As List(Of Integer)) ListBox1.Items.Add(String.Join(", ", comb)) End Sub)
2. ListBox1.Items.AddRange( (From comb As List(Of Integer) In Combos Select String.Join(", ", comb)).ToArray )
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: Public Class LuisClass_v2 ReadOnly Randomizer As New Random ReadOnly FixedValues As Integer() = Enumerable.Range(1I, 30I).ToArray ' 1 to 30 ReadOnly RandomValues As Integer() = Enumerable.Range(FixedValues.First, FixedValues.Last).ToArray ' 1 to 30 Dim Combo As List(Of Integer) = Nothing Dim Combos As New List(Of List(Of Integer)) Private Sub Test() Handles MyBase.Shown Dim IndexCounter As Integer = FixedValues.First ' 1 Dim LenCounter As Integer = 0I Const NumStep As Integer = 3I Const NumLen As Integer = 10I Do Until IndexCounter > FixedValues.Last ' IndexCounter > 30 Combo = New List(Of Integer) For Num As Integer = IndexCounter To (FixedValues.Count) Step NumStep ' 1 to 30 Step 3 Combo.Add(Num) LenCounter += 1I If LenCounter >= NumLen Then Exit For End If Next ' Num If LenCounter < NumLen Then ' If LenCounter < 10 For RandomNum As Integer = 1I To (NumLen - LenCounter) Dim n As Integer = Randomizer.Next(RandomValues.First, RandomValues.Last) Do Until Not Combo.Contains(n) n = Randomizer.Next(RandomValues.First, RandomValues.Last) Loop Combo.Add(n) Next ' RandomNum End If ' LenCounter < NumLen Debug. WriteLine(String. Join(", ", Combo )) ' Stop #End If Combos.Add(Combo) IndexCounter += 1I LenCounter = 0I Loop ' IndexCounter >= FixedValues.Last ' ******** ' Listbox: ' ******** Combos.ForEach(Sub(comb As List(Of Integer)) ' Convierto la Lista a 'String', le añado los ceros, y añado el string formateado al Listbox. ListBox1.Items.Add(String.Join(", ", From value As String In comb Select If(value.Length = 1I, value.Insert(0I, "0"c), value))) End Sub) End Sub ' Test End Class
|
|
|
|
|
|
|