|
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[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 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
|
|
|
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. ' 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
|
|
|
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 ' 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
|
|
|
6815
|
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
|
|
|
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') ' Multi-Instance Limit Example ' By Elektro ' Instructions: ' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button. ' 2. Copy and paste this code to replace the 'MyApplication' class contents. ' 3. Define a proper identifier for 'SemaphID' property. Namespace My Partial Friend Class MyApplication ''' <summary> ''' The semaphore object used to limit the number of instances. ''' </summary> Private Semaph As Threading.Semaphore = Nothing ''' <summary> ''' Gets the current semaphore object identifier. ''' </summary> ''' <value>The current process semaphore identifier.</value> ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception> Private ReadOnly Property SemaphID As String Get ' Define a Golabl Unique Identifier to name the semaphore object. Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454" If Guid.TryParse(input:=Id, result:=New Guid) Then Return Id Else Throw New FormatException("The specified value is not in a valid GUID format.") End If End Get End Property ''' <summary> ''' Gets the maximum instances allowed for this process. ''' </summary> ''' <value>The maximum instances allowed for this process.</value> Private ReadOnly Property MaxInstances As Integer Get Return 3 End Get End Property ''' <summary> ''' Determines whether the semaphore can receive a signal. ''' </summary> ''' <returns><c>true</c> if this instance [can set semaphore]; otherwise, <c>false</c>.</returns> Private Function CanSetSemaphore() As Boolean Semaph = New Threading.Semaphore(initialCount:=Me.MaxInstances, maximumCount:=Me.MaxInstances, name:=Me.SemaphID) Return Semaph.WaitOne(100I) End Function ''' <summary> ''' This occurs when the application starts, before the startup Form is created. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param> Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _ Handles Me.Startup ' If there is more than the maximum allowed instances running with the same id then... If Not Me.CanSetSemaphore Then ' Prevent multi-instancing. MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.", Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error) ' Cancel the application Startup to terminate the process. e.Cancel = True End If End Sub ''' <summary> ''' This occurs when the application shuts down. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As EventArgs) _ Handles Me.Shutdown If Semaph IsNot Nothing Then ' Free the semaphore to allow next app runs. Semaph.Release() Semaph.Close() Semaph = Nothing End If ' semaph IsNot Nothing End Sub End Class ' MyApplication 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: ' Example of how to add an WPF Control in a WinForms project at execution time. ' By Elektro ' Instructions: ' 1. Compile your own WPF user-control or download this one: http://www.codeproject.com/Articles/700185/Windows-Progress-Ring?msg=4884207#xx4884207xx ' 2. Add a reference to 'WindowsformsIntegration', 'PresentationFramework', 'PresentationCore', 'WindowsBase' and 'System.Xaml'. ' 3. Add a reference to our WPF library, in this example is: 'WindowsProgressRing.dll' ' 4. If the 'WindowsProgressRing.dll' user-control doesnt's load properly, set the targeting Framework to '4.5'. #Region " Imports " Imports System.Windows.Forms.Integration ' ElementHost #End Region #Region " WPFControl_TestClass " Public Class WPFControl_TestClass ''' <summary> ''' The ElementHost instance that will host the WPF user-control. ''' </summary> Dim WPFHost As New ElementHost With {.Dock = DockStyle.Fill} ''' <summary> ''' The WPF user-control instance. ''' </summary> Dim WPFControl As New NMT.Wpf.Controls.WindowsProgressRing ''' <summary> ''' Initializes a new instance of the <see cref="WPFControl_TestClass"/> class. ''' </summary> Public Sub New() ' This call is required by the designer. InitializeComponent() With Me ' Set the Form properties. .StartPosition = FormStartPosition.CenterScreen .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle .MaximizeBox = False .ShowIcon = False .BackColor = Color.Black .Size = New Drawing.Size(320I, 320I) .Controls.Add(WPFHost) ' Add the ElementHost. End With ' Me With WPFHost ' Set the ElementHost properties. .Width = 120I .Height = 120I WPFHost.Child = WPFControl ' Add the WPF Control. End With ' WPFHost With WPFControl ' Set the WPF Control properties. .Items = 60I .Width = 120.0R .Height = 120.0R .Speed = New Windows.Duration(TimeSpan.FromSeconds(2.5R)) .Background = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.Black.R, Color.Black.G, Color.Black.B)) .Foreground = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.DodgerBlue.R, Color.DodgerBlue.G, Color.DodgerBlue.B)) End With ' WPFControl End Sub End Class ' WPFControl_TestClass #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. ' Single-Instance Application Example ' By Elektro ' Instructions: ' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button. ' 2. Copy and paste this code to replace the 'MyApplication' class contents. ' 3. Define a proper identifier for 'MutexID' property. Namespace My Partial Friend Class MyApplication #Region " Properties " ''' <summary> ''' Gets the current process mutex identifier. ''' </summary> ''' <value>the current process mutex identifier.</value> ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception> Private ReadOnly Property MutexID As String Get ' Define a Golabl Unique Identifier to name the Mutex. Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454" If Guid.TryParse(input:=Id, result:=New Guid) Then Return Id Else Throw New FormatException("The specified value is not in a valid GUID format.") End If End Get End Property #End Region #Region " Private Methods " ''' <summary> ''' Determines whether this is the unique instance that is running for this process. ''' </summary> ''' <returns><c>true</c> if this is the unique instance; otherwise, <c>false</c>.</returns> Private Function IsUniqueInstance() As Boolean Dim mtx As Threading.Mutex = Nothing Try mtx = Threading.Mutex.OpenExisting(name:=Me.MutexID) mtx.Close() mtx = Nothing Catch mtx = New Threading.Mutex(initiallyOwned:=True, name:=Me.MutexID) End Try Return mtx IsNot Nothing End Function #End Region #Region " Event-Handlers " ''' <summary> ''' This occurs when the application starts, before the startup Form is created. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param> Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _ Handles Me.Startup ' If there is more than one instance running of this process with the same mutex then... If Not Me.IsUniqueInstance Then ' Prevent multi-instancing. MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.", Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error) ' Cancel the application execution. e.Cancel = True End If End Sub #End Region End Class ' MyApplication 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: Public Class LuisClass 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 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 Dim Combo As New List(Of Integer) Dim Combos As New List(Of List(Of Integer)) Do Until IndexCounter > FixedValues.Last ' IndexCounter > 30 For Num As Integer = IndexCounter To (FixedValues.Count) Step NumStep ' 1 to 30 Step 3 Combo.Add(Num) LenCounter += 1I If LenCounter >= NumLen Then ' Esto no es necesario en este ejemplo porque siempre dará Falso, pero lo dejo aquí. 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) Combo.Clear() IndexCounter += 1I LenCounter = 0I Loop ' IndexCounter >= FixedValues.Last End Sub ' Test 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?Here's a mathematical explanation: Calculate the number of blocks per 4 year cycle: 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: 50 + 25 + 12.5 + 6.25 + 3.125 + ... = 100 Multiply the two: 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. + 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".
|
|
|
|
|
|
|