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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Mensajes
Páginas: 1 ... 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 [682] 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 ... 1236
6811  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!
6812  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.  
6813  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.  
6814  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.  
6815  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
6816  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 18 Agosto 2014, 15:02 pm
Este código es parecido al ejemplo que mostré de como implementar una prevención de múltiples instancias, pero la diferencia de este código es que se puede especificar un máximo de instancias múltiples (en la propiedad 'SemaphID')



Código
  1. ' Multi-Instance Limit Example
  2. ' By Elektro
  3.  
  4. ' Instructions:
  5. ' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
  6. ' 2. Copy and paste this code to replace the 'MyApplication' class contents.
  7. ' 3. Define a proper identifier for 'SemaphID' property.
  8.  
  9. Namespace My
  10.  
  11.    Partial Friend Class MyApplication
  12.  
  13.        ''' <summary>
  14.        ''' The semaphore object used to limit the number of instances.
  15.        ''' </summary>
  16.        Private Semaph As Threading.Semaphore = Nothing
  17.  
  18.        ''' <summary>
  19.        ''' Gets the current semaphore object identifier.
  20.        ''' </summary>
  21.        ''' <value>The current process semaphore identifier.</value>
  22.        ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
  23.        Private ReadOnly Property SemaphID As String
  24.            Get
  25.  
  26.                ' Define a Golabl Unique Identifier to name the semaphore object.
  27.                Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"
  28.  
  29.                If Guid.TryParse(input:=Id, result:=New Guid) Then
  30.                    Return Id
  31.                Else
  32.                    Throw New FormatException("The specified value is not in a valid GUID format.")
  33.                End If
  34.  
  35.            End Get
  36.        End Property
  37.  
  38.        ''' <summary>
  39.        ''' Gets the maximum instances allowed for this process.
  40.        ''' </summary>
  41.        ''' <value>The maximum instances allowed for this process.</value>
  42.        Private ReadOnly Property MaxInstances As Integer
  43.            Get
  44.                Return 3
  45.            End Get
  46.        End Property
  47.  
  48.        ''' <summary>
  49.        ''' Determines whether the semaphore can receive a signal.
  50.        ''' </summary>
  51.        ''' <returns><c>true</c> if this instance [can set semaphore]; otherwise, <c>false</c>.</returns>
  52.        Private Function CanSetSemaphore() As Boolean
  53.  
  54.            Semaph = New Threading.Semaphore(initialCount:=Me.MaxInstances,
  55.                                             maximumCount:=Me.MaxInstances,
  56.                                             name:=Me.SemaphID)
  57.  
  58.            Return Semaph.WaitOne(100I)
  59.  
  60.        End Function
  61.  
  62.        ''' <summary>
  63.        ''' This occurs when the application starts, before the startup Form is created.
  64.        ''' </summary>
  65.        ''' <param name="sender">The source of the event.</param>
  66.        ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
  67.        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
  68.        Handles Me.Startup
  69.  
  70.            ' If there is more than the maximum allowed instances running with the same id then...
  71.            If Not Me.CanSetSemaphore Then ' Prevent multi-instancing.
  72.  
  73.                MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
  74.                               Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
  75.  
  76.                ' Cancel the application Startup to terminate the process.
  77.                e.Cancel = True
  78.  
  79.            End If
  80.  
  81.        End Sub
  82.  
  83.        ''' <summary>
  84.        ''' This occurs when the application shuts down.
  85.        ''' </summary>
  86.        ''' <param name="sender">The source of the event.</param>
  87.        ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  88.        Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As EventArgs) _
  89.        Handles Me.Shutdown
  90.  
  91.            If Semaph IsNot Nothing Then
  92.  
  93.                ' Free the semaphore to allow next app runs.
  94.                Semaph.Release()
  95.                Semaph.Close()
  96.                Semaph = Nothing
  97.  
  98.            End If ' semaph IsNot Nothing
  99.  
  100.        End Sub
  101.  
  102.    End Class ' MyApplication
  103.  
  104. End Namespace
6817  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 18 Agosto 2014, 12:08 pm
Un ejemplo de como añadir y usar un control WPF (no un proyecto) en Winforms, en tiempo de ejecución.

En este ejemplo uso un control simple que imita el indicador de progreso de Windows 8:



Código
  1. ' Example of how to add an WPF Control in a WinForms project at execution time.
  2. ' By Elektro
  3.  
  4. ' Instructions:
  5. ' 1. Compile your own WPF user-control or download this one: http://www.codeproject.com/Articles/700185/Windows-Progress-Ring?msg=4884207#xx4884207xx
  6. ' 2. Add a reference to 'WindowsformsIntegration', 'PresentationFramework', 'PresentationCore', 'WindowsBase' and 'System.Xaml'.
  7. ' 3. Add a reference to our WPF library, in this example is: 'WindowsProgressRing.dll'
  8. ' 4. If the 'WindowsProgressRing.dll' user-control doesnt's load properly, set the targeting Framework to '4.5'.
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.Windows.Forms.Integration ' ElementHost
  13.  
  14. #End Region
  15.  
  16. #Region " WPFControl_TestClass "
  17.  
  18. Public Class WPFControl_TestClass
  19.  
  20.    ''' <summary>
  21.    ''' The ElementHost instance that will host the WPF user-control.
  22.    ''' </summary>
  23.    Dim WPFHost As New ElementHost With {.Dock = DockStyle.Fill}
  24.  
  25.    ''' <summary>
  26.    ''' The WPF user-control instance.
  27.    ''' </summary>
  28.    Dim WPFControl As New NMT.Wpf.Controls.WindowsProgressRing
  29.  
  30.    ''' <summary>
  31.    ''' Initializes a new instance of the <see cref="WPFControl_TestClass"/> class.
  32.    ''' </summary>
  33.    Public Sub New()
  34.  
  35.        ' This call is required by the designer.
  36.        InitializeComponent()
  37.  
  38.        With Me ' Set the Form properties.
  39.            .StartPosition = FormStartPosition.CenterScreen
  40.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  41.            .MaximizeBox = False
  42.            .ShowIcon = False
  43.            .BackColor = Color.Black
  44.            .Size = New Drawing.Size(320I, 320I)
  45.  
  46.            .Controls.Add(WPFHost) ' Add the ElementHost.
  47.        End With ' Me
  48.  
  49.        With WPFHost ' Set the ElementHost properties.
  50.            .Width = 120I
  51.            .Height = 120I
  52.            WPFHost.Child = WPFControl ' Add the WPF Control.
  53.        End With ' WPFHost
  54.  
  55.        With WPFControl ' Set the WPF Control properties.
  56.            .Items = 60I
  57.            .Width = 120.0R
  58.            .Height = 120.0R
  59.            .Speed = New Windows.Duration(TimeSpan.FromSeconds(2.5R))
  60.            .Background = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.Black.R, Color.Black.G, Color.Black.B))
  61.            .Foreground = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.DodgerBlue.R, Color.DodgerBlue.G, Color.DodgerBlue.B))
  62.        End With ' WPFControl
  63.  
  64.    End Sub
  65.  
  66. End Class ' WPFControl_TestClass
  67.  
  68. #End Region
6818  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 18 Agosto 2014, 08:40 am
Aquí explico una manera de limitar manualmente la aplicación a única instancia (Single-Instance), mediante el MUTEX.



Código
  1. ' Single-Instance Application Example
  2. ' By Elektro
  3.  
  4. ' Instructions:
  5. ' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
  6. ' 2. Copy and paste this code to replace the 'MyApplication' class contents.
  7. ' 3. Define a proper identifier for 'MutexID' property.
  8.  
  9. Namespace My
  10.  
  11.    Partial Friend Class MyApplication
  12.  
  13. #Region " Properties "
  14.  
  15.        ''' <summary>
  16.        ''' Gets the current process mutex identifier.
  17.        ''' </summary>
  18.        ''' <value>the current process mutex identifier.</value>
  19.        ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
  20.        Private ReadOnly Property MutexID As String
  21.            Get
  22.                ' Define a Golabl Unique Identifier to name the Mutex.
  23.                Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"
  24.  
  25.                If Guid.TryParse(input:=Id, result:=New Guid) Then
  26.                    Return Id
  27.                Else
  28.                    Throw New FormatException("The specified value is not in a valid GUID format.")
  29.                End If
  30.  
  31.            End Get
  32.        End Property
  33.  
  34. #End Region
  35.  
  36. #Region " Private Methods "
  37.  
  38.        ''' <summary>
  39.        ''' Determines whether this is the unique instance that is running for this process.
  40.        ''' </summary>
  41.        ''' <returns><c>true</c> if this is the unique instance; otherwise, <c>false</c>.</returns>
  42.        Private Function IsUniqueInstance() As Boolean
  43.  
  44.            Dim mtx As Threading.Mutex = Nothing
  45.  
  46.            Try
  47.                mtx = Threading.Mutex.OpenExisting(name:=Me.MutexID)
  48.                mtx.Close()
  49.                mtx = Nothing
  50.            Catch
  51.                mtx = New Threading.Mutex(initiallyOwned:=True, name:=Me.MutexID)
  52.            End Try
  53.  
  54.            Return mtx IsNot Nothing
  55.  
  56.        End Function
  57.  
  58. #End Region
  59.  
  60. #Region " Event-Handlers "
  61.  
  62.        ''' <summary>
  63.        ''' This occurs when the application starts, before the startup Form is created.
  64.        ''' </summary>
  65.        ''' <param name="sender">The source of the event.</param>
  66.        ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
  67.        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
  68.        Handles Me.Startup
  69.  
  70.            ' If there is more than one instance running of this process with the same mutex then...
  71.            If Not Me.IsUniqueInstance Then ' Prevent multi-instancing.
  72.  
  73.                MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
  74.                               Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
  75.  
  76.                ' Cancel the application execution.
  77.                e.Cancel = True
  78.  
  79.            End If
  80.  
  81.        End Sub
  82.  
  83. #End Region
  84.  
  85.    End Class ' MyApplication
  86.  
  87. End Namespace
6819  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 18 Agosto 2014, 07:25 am
los números a rellenar no importa estén o no en la variable siempre y cuando no repitan en la misma combinación

Sinceramente, no se si es esto lo que andas buscando, pero es que con todo el material que se te ha ofrecido a lo largo del tiempo (incluyendo el siguiente código), creo que ya debería ser suficiente para que pudieras adaptar el código a tus necesidades haciendole los cambios que creas necesario.

Bueno, a ver si esta vez es la buena,
los números a rellenar no se repiten en la combinación actual, pero como siempre hay un "pero"... quizás te referías a que no se repitiera en ninguna de las combinaciones tampoco, pero eso sería imposible con un rango del 1 al 99 (ya que con los 30 números fijos de tu ejemplo y en combinaciones de 10 dígitos, sería necesario más de 99 números distintos aleatorios para rellenar los interrogantes, así que supongo que no lo habré entendido mal).

Nota: En la lista Combo se va generando la combinación actual, y una vez la combinación se completa ésta se añade a la colección Combos.

El código:

Código
  1. Public Class LuisClass
  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.    Private Sub Test() Handles MyBase.Shown
  12.  
  13.        Dim IndexCounter As Integer = FixedValues.First ' 1
  14.        Dim LenCounter As Integer = 0I
  15.  
  16.        Const NumStep As Integer = 3I
  17.        Const NumLen As Integer = 10I
  18.  
  19.        Dim Combo As New List(Of Integer)
  20.        Dim Combos As New List(Of List(Of Integer))
  21.  
  22.        Do Until IndexCounter > FixedValues.Last ' IndexCounter > 30
  23.  
  24.            For Num As Integer = IndexCounter To (FixedValues.Count) Step NumStep ' 1 to 30 Step 3
  25.  
  26.                Combo.Add(Num)
  27.                LenCounter += 1I
  28.  
  29.                If LenCounter >= NumLen Then ' Esto no es necesario en este ejemplo porque siempre dará Falso, pero lo dejo aquí.
  30.                    Exit For
  31.                End If
  32.  
  33.            Next ' Num
  34.  
  35.            If LenCounter < NumLen Then ' If LenCounter < 10
  36.  
  37.                For RandomNum As Integer = 1I To (NumLen - LenCounter)
  38.  
  39.                    Dim n As Integer = Randomizer.Next(RandomValues.First, RandomValues.Last)
  40.  
  41.                    Do Until Not Combo.Contains(n)
  42.                        n = Randomizer.Next(RandomValues.First, RandomValues.Last)
  43.                    Loop
  44.  
  45.                    Combo.Add(n)
  46.  
  47.                Next ' RandomNum
  48.  
  49.            End If ' LenCounter < NumLen
  50.  
  51. #If DEBUG Then ' #Debug
  52.            Debug.WriteLine(String.Join(", ", Combo))
  53.            ' Stop
  54. #End If
  55.  
  56.            Combos.Add(Combo)
  57.            Combo.Clear()
  58.  
  59.            IndexCounter += 1I
  60.            LenCounter = 0I
  61.  
  62.        Loop ' IndexCounter >= FixedValues.Last
  63.  
  64.    End Sub ' Test
  65.  
  66. End Class



Output (lo he formateado manualmente en el editor de texto con un RegEx para añadirle los "0"):

01, 04, 07, 10, 13, 16, 19, 22, 25, 28
02, 05, 08, 11, 14, 17, 20, 23, 26, 29
03, 06, 09, 12, 15, 18, 21, 24, 27, 30
04, 07, 10, 13, 16, 19, 22, 25, 28, 08
05, 08, 11, 14, 17, 20, 23, 26, 29, 09
06, 09, 12, 15, 18, 21, 24, 27, 30, 22
07, 10, 13, 16, 19, 22, 25, 28, 03, 23
08, 11, 14, 17, 20, 23, 26, 29, 18, 19
09, 12, 15, 18, 21, 24, 27, 30, 14, 22
10, 13, 16, 19, 22, 25, 28, 17, 08, 14
11, 14, 17, 20, 23, 26, 29, 02, 24, 07
12, 15, 18, 21, 24, 27, 30, 04, 22, 13
13, 16, 19, 22, 25, 28, 20, 27, 04, 01
14, 17, 20, 23, 26, 29, 21, 09, 02, 10
15, 18, 21, 24, 27, 30, 29, 26, 08, 13
16, 19, 22, 25, 28, 11, 20, 03, 04, 10
17, 20, 23, 26, 29, 28, 02, 03, 21, 09
18, 21, 24, 27, 30, 01, 26, 13, 17, 25
19, 22, 25, 28, 20, 16, 29, 08, 21, 15
20, 23, 26, 29, 10, 09, 01, 08, 07, 05
21, 24, 27, 30, 03, 28, 23, 22, 18, 17
22, 25, 28, 14, 15, 18, 13, 29, 24, 10
23, 26, 29, 21, 13, 18, 05, 07, 22, 14
24, 27, 30, 04, 29, 17, 23, 02, 28, 25
25, 28, 24, 11, 19, 07, 21, 08, 02, 03
26, 29, 15, 09, 25, 18, 11, 28, 20, 06
27, 30, 18, 19, 03, 06, 24, 16, 21, 23
28, 14, 04, 19, 21, 18, 26, 24, 01, 03
29, 09, 08, 14, 02, 19, 28, 07, 17, 27
30, 04, 05, 01, 18, 21, 16, 11, 14, 02
6820  Foros Generales / Noticias / Re: ¿Es rentable minar monedas Bitcoin? ¿Cómo se hace? ¿Por qué? en: 18 Agosto 2014, 01:12 am
¿alguien sabe por qué sólo habrá 21 millones?

Why was 21 million picked as the number of bitcoins to be created?

Citar
Here's a mathematical explanation:

Calculate the number of blocks per 4 year cycle:
Código:
6 blocks per hour
* 24 hours per day
* 365 days per year
* 4 years per cycle
= 210,240
~= 210,000

Sum all the block reward sizes:
Código:
50 + 25 + 12.5 + 6.25 + 3.125 + ... = 100

Multiply the two:
Código:
210,000 * 100 = 21 million.

Economically, because the currency is effectively infinitely divisible, then the precise amount doesn't matter, as long as the limit remains fixed.

+

Citar
I think we best conclude that nobody knows why Satoshi chose for 21 million or 4 years per cycle. But I would not recommend accepting this answer as correct. In fact it only answers "What's the maximum amount of bitcoins that can exist?"

Conslusión: la mayoría de las personas (me inclluyo a mi mismo) siguen sin tener claro nada acerca de este sistema monetario tan "prometedor" y "transparente".
Páginas: 1 ... 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 [682] 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines