Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 3 Visitantes están viendo este tema.

Eleкtro

#310
Este código reemplaza una palabra en un string, por una secuencia numérica:

Código (vbnet) [Seleccionar]
#Region " Replace Word (Increment method) "

   ' [ Replace Word (Increment method) ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' MsgBox(Replace_Word_By_Increment("Hello World!, Hello World!", "Hello", , 3)) ' Result: 001 World!, 002 World!

   Private Function Replace_Word_By_Increment(ByVal str As String, _
                                              ByVal replace As String, _
                                              Optional ByVal IgnoreCase As System.StringComparison = StringComparison.CurrentCulture, _
                                              Optional ByVal DigitLength As Long = 0) As String

       Dim str_split() As String = str.Split
       Dim replacement As String = Nothing
       Dim IndexCount As Long = 0

       DigitLength = If(DigitLength = 0, replace.Length, DigitLength)

       For Item As Long = 0 To str_split.LongCount - 1

           If str_split(Item).Equals(replace, IgnoreCase) Then

               replacement &= Threading.Interlocked.Increment(IndexCount).ToString

               While Not replacement.Length >= DigitLength
                   replacement = replacement.Insert(0, "0")
               End While

               str_split(Item) = replacement
               replacement = Nothing

           End If

       Next Item

       Return String.Join(Convert.ToChar(Keys.Space), str_split)

   End Function

#End Region



Este código reemplaza un patrón de búsqueda en un string, por una secuencia numérica:

Código (vbnet) [Seleccionar]
#Region " Replace String (Increment method) "

   ' [ Replace String (Increment method) ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' MsgBox(Replace_String_By_Increment("Hello World!, Hello World!", New System.Text.RegularExpressions.Regex("Hello\sWorld", RegexOptions.IgnoreCase), 3)) ' Result: 001!, 002!

   Private Function Replace_String_By_Increment(ByVal str As String, _
                                                ByVal replace As System.Text.RegularExpressions.Regex, _
                                                Optional ByVal DigitLength As Long = 0) As String

       DigitLength = If(DigitLength = 0, replace.ToString.Length, DigitLength)

       Dim IndexCount As Integer = 0
       Dim replacement As String = Nothing
       Dim matches As System.Text.RegularExpressions.MatchCollection = replace.Matches(str)

       For Each match As System.Text.RegularExpressions.Match In matches

           replacement &= Threading.Interlocked.Increment(IndexCount).ToString

           While Not replacement.Length >= DigitLength
               replacement = replacement.Insert(0, "0")
           End While

           str = replace.Replace(str, replacement, 1, match.Index - (match.Length * (IndexCount - 1)))
           replacement = Nothing

       Next

       matches = Nothing
       replacement = Nothing
       IndexCount = 0
       Return str

   End Function

#End Region


EDITO:

Un sencillo proyecto para testear:

   

Descarga: http://www.mediafire.com/?6b6qdy9iyigm63v








Eleкtro

He descubierto este mensaje de Windows para mover el ScrollBar de un control pudiendo especificar la cantidad de lineas a mover, y la dirección.

Código (vbnet) [Seleccionar]
    <System.Runtime.InteropServices.DllImport("user32.dll")> _
    Private Shared Function SendMessage(hWnd As IntPtr, wMsg As UInteger, wParam As UIntPtr, lParam As IntPtr) As Integer
    End Function

    ' Examples:
    '
    ' SendMessage(RichTextBox1.Handle, &HB6, 0, 1)  ' Move 1 line to down
    ' SendMessage(RichTextBox1.Handle, &HB6, 0, 5)  ' Move 5 lines to down
    ' SendMessage(RichTextBox1.Handle, &HB6, 0, -1) ' Move 1 line to up
    ' SendMessage(RichTextBox1.Handle, &HB6, 0, -5) ' Move 5 lines to up








Eleкtro

#312
Con estas funciones podemos acceder a la información de la ScrollBar integrada de un control (la scrollbar vertical de un RichTextBox por ejemplo), para averiguar si la barra está scrolleada hacia abajo del todo, o hacia arriba del todo, o si ha sobrepasado el límite de abajo/arriba (aunque esto último creo que no pede suceder, pero bueno).

Esto es útil para prevenir el molesto efecto de "rebote" del método ScrollToCaret cuando intentamos scrollear la ScrollBar de un richtextbox cuando ha llegado al límite.

Ejemplo de uso:
Código (vbnet) [Seleccionar]
       RichTextBox1.Select(RichTextBox1.TextLength - 1, 1)
       If Not ScrollBarInfo.IsAtBottom(RichTextBox1) Then
           RichTextBox1.ScrollToCaret()
       End If



Código (vbnet) [Seleccionar]
Public Class ScrollBarInfo

   <System.Runtime.InteropServices.DllImport("user32")> _
   Private Shared Function GetScrollInfo(hwnd As IntPtr, nBar As Integer, ByRef scrollInfo As SCROLLINFO) As Integer
   End Function

   Private Shared scrollInf As New SCROLLINFO()

   Private Structure SCROLLINFO
       Public cbSize As Integer
       Public fMask As Integer
       Public min As Integer
       Public max As Integer
       Public nPage As Integer
       Public nPos As Integer
       Public nTrackPos As Integer
   End Structure

   Private Shared Sub Get_ScrollInfo(control As Control)
       scrollInf = New SCROLLINFO()
       scrollInf.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(scrollInf)
       scrollInf.fMask = &H10 Or &H1 Or &H2 'SIF_RANGE = &H1, SIF_PAGE= &H2, SIF_TRACKPOS = &H10
       GetScrollInfo(control.Handle, 1, scrollInf)
   End Sub

   Public Shared Function ReachedBottom(control As Control) As Boolean
       Get_ScrollInfo(control)
       Return scrollInf.max = scrollInf.nTrackPos + scrollInf.nPage
   End Function

   Public Shared Function ReachedTop(control As Control) As Boolean
       Get_ScrollInfo(control)
       Return scrollInf.nTrackPos < 0
   End Function

   Public Shared Function IsAtBottom(control As Control) As Boolean
       Get_ScrollInfo(control)
       Return scrollInf.max = (scrollInf.nTrackPos + scrollInf.nPage) - 1
   End Function

   Public Shared Function IsAtTop(control As Control) As Boolean
       Get_ScrollInfo(control)
       Return scrollInf.nTrackPos = 0
   End Function

End Class








MauriH

Cita de: EleKtro H@cker en 13 Octubre 2013, 03:55 AM
Este código reemplaza una palabra en un string, por una secuencia numérica:

Código (vbnet) [Seleccionar]
#Region " Replace Word (Increment method) "

   ' [ Replace Word (Increment method) ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   ' MsgBox(Replace_Word_By_Increment("Hello World!, Hello World!", "Hello", , 3)) ' Result: 001 World!, 002 World!

   Private Function Replace_Word_By_Increment(ByVal str As String, _
                                              ByVal replace As String, _
                                              Optional ByVal IgnoreCase As System.StringComparison = StringComparison.CurrentCulture, _
                                              Optional ByVal DigitLength As Long = 0) As String

       Dim str_split() As String = str.Split
       Dim replacement As String = Nothing
       Dim IndexCount As Long = 0

       DigitLength = If(DigitLength = 0, replace.Length, DigitLength)

       For Item As Long = 0 To str_split.LongCount - 1

           If str_split(Item).Equals(replace, IgnoreCase) Then

               replacement &= Threading.Interlocked.Increment(IndexCount).ToString

               While Not replacement.Length >= DigitLength
                   replacement = replacement.Insert(0, "0")
               End While

               str_split(Item) = replacement
               replacement = Nothing

           End If

       Next Item

       Return String.Join(Convert.ToChar(Keys.Space), str_split)

   End Function

#End Region



Este código reemplaza un patrón de búsqueda en un string, por una secuencia numérica:

Código (vbnet) [Seleccionar]
#Region " Replace String (Increment method) "

    ' [ Replace String (Increment method) ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' MsgBox(Replace_String_By_Increment("Hello World!, Hello World!", New System.Text.RegularExpressions.Regex("Hello\sWorld", RegexOptions.IgnoreCase), 3)) ' Result: 001!, 002!

    Private Function Replace_String_By_Increment(ByVal str As String, _
                                                 ByVal replace As System.Text.RegularExpressions.Regex, _
                                                 Optional ByVal DigitLength As Long = 0) As String

        DigitLength = If(DigitLength = 0, replace.ToString.Length, DigitLength)

        Dim IndexCount As Integer = 0
        Dim replacement As String = Nothing
        Dim matches As System.Text.RegularExpressions.MatchCollection = replace.Matches(str)

        For Each match As System.Text.RegularExpressions.Match In matches

            replacement &= Threading.Interlocked.Increment(IndexCount).ToString

            While Not replacement.Length >= DigitLength
                replacement = replacement.Insert(0, "0")
            End While

            str = replace.Replace(str, replacement, 1, match.Index - (match.Length * (IndexCount - 1)))
            replacement = Nothing

        Next

        matches = Nothing
        replacement = Nothing
        IndexCount = 0
        Return str

    End Function

#End Region


Disculpen la ignorancia, apenas conozco algo de batch, este codigo me interesa, pero la verdad es q no sé como utilizarlo, q se supone q debo hacer con el codigo? lo copie a un archivo de texto y le puse la extension .vbs, hice bien? crei q funcionaría como un batch, lo ejecuté y me salio error de compilación o algo así, por favor q alguien me ayude  :-\

Novlucker

Contribuye con la limpieza del foro, reporta los "casos perdidos" a un MOD XD

"Hay dos cosas infinitas: el Universo y la estupidez  humana. Y de la primera no estoy muy seguro."
Albert Einstein

Eleкtro









Eleкtro

#316
Añadir la funcionalidad 'Find Next' y 'Find Previous' en un RichTextBox,
Le añadi soporte para poder utilizar expresiones regulares y también para poder resaltar el text seleccionado en colores :).

[youtube=640,360]http://www.youtube.com/watch?v=mWRMdlC5DH8[/youtube]

Código (vbnet) [Seleccionar]
#Region " [RichTextBox] FindNext "

   ' [ FindNext ]
   '
   ' //By Elektro H@cker
   '
   ' Examples :
   '
   ' RichTextBox1.Text = "Hello World!, Hello World!, Hello World!"
   '
   ' FindNext(RichTextBox1, "hello", FindDirection.Down, RegexOptions.IgnoreCase, Color.LightBlue, Color.Black)
   ' FindNext(RichTextBox1, "hello", FindDirection.Up, RegexOptions.IgnoreCase, Color.Red, Color.Black)
   '
   ' Private Sub RichTextBox_Enter(sender As Object, e As EventArgs) ' Handles RichTextBox1.Enter
   '    ' Restore Selection Colors before search next match.
   '    sender.SelectionBackColor = DefaultBackColor
   '    sender.SelectionColor = DefaultForeColor
   ' End Sub

   Public Enum FindDirection
       Up = 0
       Down = 1
   End Enum

   ' FindNext
   Private Sub FindNext(ByVal [Control] As RichTextBox, _
                              ByVal SearchText As String, _
                              ByVal Direction As FindDirection, _
                              Optional ByVal IgnoreCase As System.Text.RegularExpressions.RegexOptions = RegexOptions.None, _
                              Optional ByVal Highlight_BackColor As Color = Nothing, _
                              Optional ByVal Highlight_ForeColor As Color = Nothing)

       If [Control].TextLength = 0 Then Exit Sub

       ' Start searching at 'SelectionStart'.
       Dim Search_StartIndex As Integer = [Control].SelectionStart

       ' Stores the MatchIndex count
       Dim matchIndex As Integer = 0

       ' Flag to check if it's first find call
       Static First_Find As Boolean = True

       ' Checks to don't ommit the selection of first match if match index is exactly at 0 start point.
       If First_Find _
           AndAlso Search_StartIndex = 0 _
           AndAlso Direction = FindDirection.Down Then
           Search_StartIndex = -1
           First_Find = False
       ElseIf Not First_Find _
           AndAlso Search_StartIndex = 0 _
           AndAlso Direction = FindDirection.Down Then
           First_Find = False
           Search_StartIndex = 0
       End If

       ' Store the matches
       Dim matches As System.Text.RegularExpressions.MatchCollection = _
           System.Text.RegularExpressions.Regex.Matches([Control].Text, _
                                                        SearchText, _
                                                        IgnoreCase Or If(Direction = FindDirection.Up, _
                                                                         RegexOptions.RightToLeft, _
                                                                         RegexOptions.None))

       If matches.Count = 0 Then First_Find = True : Exit Sub

       ' Restore Highlight colors of previous selection
       [Control].SelectionBackColor = [Control].BackColor
       [Control].SelectionColor = [Control].ForeColor

       ' Set next selection Highlight colors
       If Highlight_BackColor = Nothing Then Highlight_BackColor = [Control].BackColor
       If Highlight_ForeColor = Nothing Then Highlight_ForeColor = [Control].ForeColor

       ' Set the match selection
       For Each match As System.Text.RegularExpressions.Match In matches

           matchIndex += 1

           Select Case Direction

               Case FindDirection.Down
                   If match.Index > Search_StartIndex Then ' Select next match
                       [Control].Select(match.Index, match.Length)
                       Exit For
                   ElseIf match.Index <= Search_StartIndex _
                   AndAlso matchIndex = matches.Count Then ' Select first match
                       [Control].Select(matches.Item(0).Index, matches.Item(0).Length)
                       Exit For
                   End If

               Case FindDirection.Up
                   If match.Index < Search_StartIndex Then ' Select previous match
                       [Control].Select(match.Index, match.Length)
                       Exit For
                   ElseIf match.Index >= Search_StartIndex _
                   AndAlso matchIndex = matches.Count Then ' Select last match
                       [Control].Select(matches.Item(0).Index, matches.Item(0).Length)
                       Exit For
                   End If

           End Select

       Next match

       ' Set the current selection BackColor
       [Control].SelectionBackColor = Highlight_BackColor
       ' Set the current selection ForeColor
       [Control].SelectionColor = Highlight_ForeColor
       ' Scroll to Caret/Cursor selection position
       [Control].ScrollToCaret()

   End Sub

#End Region



EDITO:

Aquí dejo una versión alternativa, no soporta RegEx y no soporta búsqueda hacia arriba,
el código no es peor, símplemente si no se requiere el uso de búsqueda por RegEx ni buscar hacia arriba entonces es preferible usar este snippet.

Código (vbnet) [Seleccionar]
#Region " [RichTextBox] FindNext String "

    ' [ FindNext String ]
    '
    ' //By Elektro H@cker
    '
    ' Examples :
    '
    ' FindNext(RichTextBox1, "Hello", RichTextBoxFinds.MatchCase, Color.LightBlue, Color.Black)
    '
    ' Private Sub RichTextBox_Enter(sender As Object, e As EventArgs) ' Handles RichTextBox1.Enter
    '    ' Restore Selection Colors before search next match.
    '    sender.SelectionBackColor = DefaultBackColor
    '    sender.SelectionColor = DefaultForeColor
    ' End Sub

    ' FindNext
    Private Sub FindNext(ByVal [Control] As RichTextBox, _
                        ByVal SearchText As String, _
                        ByVal IgnoreCase As RichTextBoxFinds, _
                        Optional ByVal Highlight_BackColor As Color = Nothing, _
                        Optional ByVal Highlight_ForeColor As Color = Nothing)

        ' Start searching at 'SelectionStart'.
        Dim Search_StartIndex As Integer = [Control].SelectionStart
        Static Next_Count As Integer = 0

        ' Restore Highlight colors of previous selection
        [Control].SelectionBackColor = [Control].BackColor
        [Control].SelectionColor = [Control].ForeColor

        ' Set next selection Highlight colors
        If Highlight_BackColor = Nothing Then Highlight_BackColor = [Control].BackColor
        If Highlight_ForeColor = Nothing Then Highlight_ForeColor = [Control].ForeColor

        ' If is not first FindNext call then...
        If Next_Count <> 0 Then
            Search_StartIndex += SearchText.Length
        Else ' If is first FindNext call then...
            Next_Count += 1
        End If

        ' Set Search_StartIndex
        Search_StartIndex = _
        [Control].Find(SearchText, Search_StartIndex, IgnoreCase)
        ' ...And prevent search at End Of File
        If Search_StartIndex = -1 Then
            Search_StartIndex = _
            [Control].Find(SearchText, 0, IgnoreCase)
        End If

        If Search_StartIndex = -1 Then
            Exit Sub ' No matches found
        End If

        ' Set the match selection
        [Control].Select(Search_StartIndex, SearchText.Length)
        ' Set the BackColor
        [Control].SelectionBackColor = Highlight_BackColor
        ' Set the ForeColor
        [Control].SelectionColor = Highlight_ForeColor
        ' Scroll to Caret/Cursor position
        [Control].ScrollToCaret()

    End Sub

#End Region








Eleкtro

#317
Una class para manejar bases de clientes,
En principio el código original lo descargué de la página CodeProject, pero lo modifiqué casi por completo y además le añadi +20 funciones genéricas para que las operaciones más comunes no requieran escritura de código adicional.

(La lista de contactos es facil de añadir en un Listview/DataGridView)

Esto es un ejemplo de para que sirve:



EDITO: He añadido un par de funciones más.

Código (vbnet) [Seleccionar]
#Region " Contact "

#Region " Examples (Normal usage)"

' Create a new list of contacts
' Dim Contacts As List(Of Contact) = New List(Of Contact)
' Or load ContactList from previous serialized file
' Dim Contacts As List(Of Contact) = ContactSerializer.Deserialize("C:\Contacts.bin")

' Set a variable to store the current contact position
' Dim CurrentPosition As Integer = 0

' Create a new contact
' Dim CurrentContact As Contact = New Contact With { _
'     .Name = "Manolo", _
'     .Surname = "El del Bombo", _
'     .Country = "Spain", _
'     .City = "Valencia", _
'     .Street = "Av. Mestalla", _
'     .ZipCode = "42731", _
'     .Phone = "96.XXX.XX.XX", _
'     .CellPhone = "651.XXX.XXX", _
'     .Email = "ManoloToLoko@Gmail.com"}

' Add a contact to contacts list
' Contacts.Add(CurrentContact)

' Update the CurrentPosition index value
' CurrentPosition = Contacts.IndexOf(CurrentContact)

#End Region

#Region " Examples (Generic functions) "


' Examples:
'
' -----------------
' Add a new contact
' -----------------
' Contact.Add_Contact(ContactList, "Manolo", "El del Bombo", "Spain", "Valencia", "Av. Mestalla", "42731", "96.XXX.XX.XX", "651.XXX.XXX", "ManoloToLoko@Gmail.com")
'
'
' -----------------------------------------------------------------
' Load a contact from an existing contacts list into TextBox Fields
' -----------------------------------------------------------------
' Contact.Load_Contact(ContactList, 0, TextBox_Name, textbox_surName, TextBox_Country, textbox_City, TextBox_Street, TextBox_ZipCode, TextBox_Phone, TextBox_CellPhone, TextBox_email)
'
'
' ----------------------------------
' Load a contact into TextBox Fields
' ----------------------------------
' Contact.Load_Contact(Contact, TextBox_Name, textbox_surName, TextBox_Country, textbox_City, TextBox_Street, TextBox_ZipCode, TextBox_Phone, TextBox_CellPhone, TextBox_email)
'
'
' ---------------------------------
' Load a contact list into ListView
' ---------------------------------
' Contact.Load_ContactList_Into_ListView(ContactList, ListView1)
'
'
' -------------------------------------
' Load a contact list into DataGrivView
' -------------------------------------
' Contact.Load_ContactList_Into_DataGrivView(ContactList, DataGrivView1)
'
'
' -------------------------------------------
' Load a contacts list from a serialized file
' -------------------------------------------
' Dim ContactList As List(Of Contact) = Contact.Load_ContactList("C:\Contacts.bin")
'
'
' -----------------------------------------------------------------------
' Find the first occurrence of a contact name in a existing contacts list
' -----------------------------------------------------------------------
' Dim ContactFound As Contact = Contact.Match_Contact_Name_FirstOccurrence(ContactList, "Manolo")
'
'
' ----------------------------------------------------------------------
' Find all the occurrences of a contact name in a existing contacts list
' ----------------------------------------------------------------------
' Dim ContactsFound As List(Of Contact) = Contact.Match_Contact_Name(ContactList, "Manolo")
'
'
' -------------------------------------------------------------
' Remove a contact from a Contact List giving the contact index
' -------------------------------------------------------------
' Remove_Contact(ContactList, 0)
'
'
' -------------------------------------------------------
' Remove a contact from a Contact List giving the contact
' -------------------------------------------------------
' Remove_Contact(ContactList, MyContact)
'
'
' -------------------------
' Save the contacts to file
' -------------------------
' Contact.Save_ContactList(ContactList, "C:\Contacts.bin")
'
'
' -------------------------
' Sort the contacts by name
' -------------------------
' Dim SorteredContacts As List(Of Contact) = Contact.Sort_ContactList_By_Name(ContactList, Contact.ContectSortMode.Ascending)
'
'
' --------------------------------------------------------------------
' Get a formatted string containing the details of an existing contact
' --------------------------------------------------------------------
' MsgBox(Contact.Get_Contact_Details(ContactList, 0))
' MsgBox(Contact.Get_Contact_Details(CurrentContact))
'     
'
' ----------------------------------------------------------------------------------
' Copy to clipboard a formatted string containing the details of an existing contact
' ----------------------------------------------------------------------------------
' Contact.Copy_Contact_Details_To_Clipboard(ContactList, 0)
' Contact.Copy_Contact_Details_To_Clipboard(CurrentContact)


#End Region

<Serializable()> _
Public Class Contact

    Public Enum ContectSortMode As Short
        Ascending = 0
        Descending = 1
    End Enum

#Region "Member Variables"

    Private mId As System.Guid
    Private mName As String
    Private mSurname As String
    Private mCountry As String
    Private mCity As String
    Private mStreet As String
    Private mZip As String
    Private mPhone As String
    Private mCellPhone As String
    Private mEmail As String

#End Region

#Region "Constructor"

    Public Sub New()
        mId = Guid.NewGuid()
    End Sub


    Public Sub New(ByVal ID As System.Guid)
        mId = ID
    End Sub

#End Region

#Region "Properties"

    Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property

    Public Property Surname() As String
        Get
            Return mSurname
        End Get
        Set(ByVal value As String)
            mSurname = value
        End Set
    End Property

    Public Property Street() As String
        Get
            Return mStreet
        End Get
        Set(ByVal value As String)
            mStreet = value
        End Set
    End Property

    Public Property City() As String
        Get
            Return mCity
        End Get
        Set(ByVal value As String)
            mCity = value
        End Set
    End Property

    Public Property Country() As String
        Get
            Return mCountry
        End Get
        Set(ByVal value As String)
            mCountry = value
        End Set
    End Property

    Public Property ZipCode() As String
        Get
            Return mZip
        End Get
        Set(ByVal value As String)
            mZip = value
        End Set
    End Property

    Public Property Email() As String
        Get
            Return mEmail
        End Get
        Set(ByVal value As String)
            mEmail = value
        End Set
    End Property

    Public Property Phone() As String
        Get
            Return mPhone
        End Get
        Set(ByVal value As String)
            mPhone = value
        End Set
    End Property

    Public Property CellPhone() As String
        Get
            Return mCellPhone
        End Get
        Set(ByVal value As String)
            mCellPhone = value
        End Set
    End Property

#End Region

#Region " ContactSerializer "

    Public Class ContactSerializer

        ''' <summary>
        ''' Serialize a contact list into a contacts file.
        ''' </summary>
        ''' <param name="ContactList"></param>
        ''' <param name="FilePath"></param>
        ''' <remarks></remarks>
        Public Shared Sub Save(ByVal ContactList As List(Of Contact), _
                                    ByVal FilePath As String)

            Dim fs As IO.FileStream = Nothing
            Dim formatter As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            Try
                fs = New IO.FileStream(FilePath, IO.FileMode.OpenOrCreate)
                formatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
                formatter.Serialize(fs, ContactList)

            Catch ex As Exception

                MessageBox.Show(String.Format("{0}:{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), _
                                "Error", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Error)

            Finally
                If fs IsNot Nothing Then fs.Dispose()

            End Try

        End Sub

        ''' <summary>
        ''' Deserialize an existing file into a contact list.
        ''' </summary>
        ''' <param name="FilePath"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Load(ByVal FilePath As String) As List(Of Contact)

            Dim fs As IO.FileStream = Nothing
            Dim formatter As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            Try
                fs = New IO.FileStream(FilePath, IO.FileMode.Open)
                formatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
                Return formatter.Deserialize(fs)

            Catch ex As Exception

                MessageBox.Show(String.Format("{0}:{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), _
                                "Error", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Error)
                Return Nothing

            Finally
                If fs IsNot Nothing Then fs.Dispose()

            End Try

        End Function

    End Class

#End Region

#Region " Generic Functions "

    ' Formatted String of contact detailed information
    Shared ReadOnly DetailsFormat As String = _
    "Name.....: {1}{0}Surname..: {2}{0}Country..: {3}{0}City.....: {4}{0}Street...: {5}{0}Zipcode..: {6}{0}Phone....: {7}{0}CellPhone: {8}{0}Email....: {9}"

    ''' <summary>
    ''' Add a new contact into a existing contacts list.
    ''' </summary>
    Public Shared Sub Add_Contact(ByVal ContactList As List(Of Contact), _
                           ByVal Name As String, _
                           ByVal Surname As String, _
                           ByVal Country As String, _
                           ByVal City As String, _
                           ByVal Street As String, _
                           ByVal ZipCode As String, _
                           ByVal Phone As String, _
                           ByVal CellPhone As String, _
                           ByVal Email As String)

        ContactList.Add(New Contact With { _
                        .Name = Name, _
                        .Surname = Surname, _
                        .Country = Country, _
                        .City = City, _
                        .Street = Street, _
                        .ZipCode = ZipCode, _
                        .Phone = Phone, _
                        .CellPhone = CellPhone, _
                        .Email = Email _
                    })

    End Sub

    ''' <summary>
    ''' Remove a contact from an existing contacts list.
    ''' </summary>
    Public Shared Sub Remove_Contact(ByVal ContactList As List(Of Contact), ByVal ContactIndex As Integer)
        ContactList.RemoveAt(ContactIndex)
    End Sub

    ''' <summary>
    ''' Remove a contact from an existing contacts list.
    ''' </summary>
    Public Shared Sub Remove_Contact(ByVal ContactList As List(Of Contact), ByVal Contact As Contact)
        ContactList.Remove(Contact)
    End Sub

    ''' <summary>
    ''' Find the first occurrence of a contact name in an existing contacts list.
    ''' </summary>
    Public Shared Function Match_Contact_Name_FirstOccurrence(ByVal ContactList As List(Of Contact), ByVal Name As String) As Contact

        Return ContactList.Find(Function(contact) contact.Name.ToLower.StartsWith(Name.ToLower) _
                                OrElse contact.Name.ToLower.Contains(Name.ToLower))
    End Function

    ''' <summary>
    ''' Find all the occurrences of a contact name in a existing contacts list.
    ''' </summary>
    Public Shared Function Match_Contact_Name(ByVal ContactList As List(Of Contact), ByVal Name As String) As List(Of Contact)

        Return ContactList.FindAll(Function(contact) contact.Name.ToLower.StartsWith(Name.ToLower) _
                                   OrElse contact.Name.ToLower.Contains(Name.ToLower))

    End Function

    ''' <summary>
    ''' Load a contact from an existing contacts list into textbox fields.
    ''' </summary>
    Public Shared Sub Load_Contact(ByVal ContactList As List(Of Contact), _
                            ByVal ContactIndex As Integer, _
                            ByVal TextBox_Name As TextBox, _
                            ByVal TextBox_Surname As TextBox, _
                            ByVal TextBox_Country As TextBox, _
                            ByVal TextBox_City As TextBox, _
                            ByVal TextBox_Street As TextBox, _
                            ByVal TextBox_Zipcode As TextBox, _
                            ByVal TextBox_Phone As TextBox, _
                            ByVal TextBox_CellPhone As TextBox, _
                            ByVal TextBox_Email As TextBox)

        TextBox_Name.Text = ContactList.Item(ContactIndex).Name
        TextBox_Surname.Text = ContactList.Item(ContactIndex).Surname
        TextBox_Country.Text = ContactList.Item(ContactIndex).Country
        TextBox_City.Text = ContactList.Item(ContactIndex).City
        TextBox_Street.Text = ContactList.Item(ContactIndex).Street
        TextBox_Zipcode.Text = ContactList.Item(ContactIndex).ZipCode
        TextBox_Phone.Text = ContactList.Item(ContactIndex).Phone
        TextBox_CellPhone.Text = ContactList.Item(ContactIndex).CellPhone
        TextBox_Email.Text = ContactList.Item(ContactIndex).Email

    End Sub

    ''' <summary>
    ''' Load a contact into textbox fields.
    ''' </summary>
    Public Shared Sub Load_Contact(ByVal Contact As Contact, _
                            ByVal TextBox_Name As TextBox, _
                            ByVal TextBox_Surname As TextBox, _
                            ByVal TextBox_Country As TextBox, _
                            ByVal TextBox_City As TextBox, _
                            ByVal TextBox_Street As TextBox, _
                            ByVal TextBox_Zipcode As TextBox, _
                            ByVal TextBox_Phone As TextBox, _
                            ByVal TextBox_CellPhone As TextBox, _
                            ByVal TextBox_Email As TextBox)

        TextBox_Name.Text = Contact.Name
        TextBox_Surname.Text = Contact.Surname
        TextBox_Country.Text = Contact.Country
        TextBox_City.Text = Contact.City
        TextBox_Street.Text = Contact.Street
        TextBox_Zipcode.Text = Contact.ZipCode
        TextBox_Phone.Text = Contact.Phone
        TextBox_CellPhone.Text = Contact.CellPhone
        TextBox_Email.Text = Contact.Email

    End Sub

    ''' <summary>
    ''' Seriale a contacts list to a file.
    ''' </summary>
    Public Shared Sub Save_ContactList(ByVal ContactList As List(Of Contact), ByVal FilePath As String)

        Contact.ContactSerializer.Save(ContactList, FilePath)

    End Sub

    ''' <summary>
    ''' Load a contacts list from a serialized file.
    ''' </summary>
    Public Shared Function Load_ContactList(ByVal FilePath As String) As List(Of Contact)

        Return Contact.ContactSerializer.Load(FilePath)

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Name field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Name(ByVal ContactList As List(Of Contact), _
                                              ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.Name).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.Name).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Surname field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Surname(ByVal ContactList As List(Of Contact), _
                                                 ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.Surname).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.Surname).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Country field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Country(ByVal ContactList As List(Of Contact), _
                                                 ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.Country).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.Country).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the City field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_City(ByVal ContactList As List(Of Contact), _
                                              ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.City).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.City).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Street field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Street(ByVal ContactList As List(Of Contact), _
                                                ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.Street).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.Street).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Zipcode field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Zipcode(ByVal ContactList As List(Of Contact), _
                                                 ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.ZipCode).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.ZipCode).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Phone field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Phone(ByVal ContactList As List(Of Contact), _
                                               ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.Phone).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.Phone).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the CellPhone field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_CellPhone(ByVal ContactList As List(Of Contact), _
                                                   ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.CellPhone).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.CellPhone).ToList())

    End Function

    ''' <summary>
    ''' Reorder the contacts of a Contacts List by the Email field.
    ''' </summary>
    Public Shared Function Sort_ContactList_By_Email(ByVal ContactList As List(Of Contact), _
                                               ByVal ContectSortMode As Contact.ContectSortMode) As List(Of Contact)

        Return If(ContectSortMode = Contact.ContectSortMode.Ascending, _
                  ContactList.OrderBy(Function(contact) contact.Email).ToList(), _
                  ContactList.OrderByDescending(Function(contact) contact.Email).ToList())

    End Function

    ''' <summary>
    ''' Get a formatted string containing the details of an existing contact.
    ''' </summary>
    Public Shared Function Get_Contact_Details(ByVal ContactList As List(Of Contact), ByVal ContactIndex As Integer) As String

        Return String.Format(DetailsFormat, _
                             Environment.NewLine, _
                             ContactList.Item(ContactIndex).Name, _
                             ContactList.Item(ContactIndex).Surname, _
                             ContactList.Item(ContactIndex).Country, _
                             ContactList.Item(ContactIndex).City, _
                             ContactList.Item(ContactIndex).Street, _
                             ContactList.Item(ContactIndex).ZipCode, _
                             ContactList.Item(ContactIndex).Phone, _
                             ContactList.Item(ContactIndex).CellPhone, _
                             ContactList.Item(ContactIndex).Email)

    End Function

    ''' <summary>
    ''' Get a formatted string containing the details of an existing contact.
    ''' </summary>
    Public Shared Function Get_Contact_Details(ByVal Contact As Contact) As String

        Return String.Format(DetailsFormat, _
                             Environment.NewLine, _
                             Contact.Name, _
                             Contact.Surname, _
                             Contact.Country, _
                             Contact.City, _
                             Contact.Street, _
                             Contact.ZipCode, _
                             Contact.Phone, _
                             Contact.CellPhone, _
                             Contact.Email)

    End Function

    ''' <summary>
    ''' Copy to clipboard a formatted string containing the details of an existing contact.
    ''' </summary>
    Public Shared Sub Copy_Contact_Details_To_Clipboard(ByVal ContactList As List(Of Contact), ByVal ContactIndex As Integer)

        Clipboard.SetText(String.Format(DetailsFormat, _
                          Environment.NewLine, _
                          ContactList.Item(ContactIndex).Name, _
                          ContactList.Item(ContactIndex).Surname, _
                          ContactList.Item(ContactIndex).Country, _
                          ContactList.Item(ContactIndex).City, _
                          ContactList.Item(ContactIndex).Street, _
                          ContactList.Item(ContactIndex).ZipCode, _
                          ContactList.Item(ContactIndex).Phone, _
                          ContactList.Item(ContactIndex).CellPhone, _
                          ContactList.Item(ContactIndex).Email))

    End Sub

    ''' <summary>
    ''' Copy to clipboard a formatted string containing the details of an existing contact.
    ''' </summary>
    Public Shared Sub Copy_Contact_Details_To_Clipboard(ByVal Contact As Contact)

        Clipboard.SetText(String.Format(DetailsFormat, _
                          Environment.NewLine, _
                          Contact.Name, _
                          Contact.Surname, _
                          Contact.Country, _
                          Contact.City, _
                          Contact.Street, _
                          Contact.ZipCode, _
                          Contact.Phone, _
                          Contact.CellPhone, _
                          Contact.Email))

    End Sub

    ''' <summary>
    ''' Load an existing contacts list into a ListView.
    ''' </summary>
    Public Shared Sub Load_ContactList_Into_ListView(ByVal ContactList As List(Of Contact), _
                                                     ByVal Listview As ListView)

        Listview.Items.AddRange( _
                       ContactList _
                       .Select(Function(Contact) _
                               New ListViewItem(New String() { _
                                                                Contact.Name, _
                                                                Contact.Surname, _
                                                                Contact.Country, _
                                                                Contact.City, _
                                                                Contact.Street, _
                                                                Contact.ZipCode, _
                                                                Contact.Phone, _
                                                                Contact.CellPhone, _
                                                                Contact.Email _
                                                             })).ToArray())

    End Sub

    ''' <summary>
    ''' Load an existing contacts list into a DataGridView.
    ''' </summary>
    Public Shared Sub Load_ContactList_Into_DataGridView(ByVal ContactList As List(Of Contact), _
                                                         ByVal DataGridView As DataGridView)

        DataGridView.DataSource = ContactList
        ' Sortered:
        ' DataGridView.DataSource = (From Contact In ContactList Order By Contact.Name Ascending Select Contact).ToList

    End Sub


#End Region

End Class

#End Region








MauriH

#318
Cita de: EleKtro H@cker en 14 Octubre 2013, 04:37 AM
@MauriH

Vuelve a leer este post hasta el final: http://foro.elhacker.net/net/libreria_de_snippets_posteen_aqui_sus_snippets-t378770.0.html;msg1891125#msg1891125

Solo quiero decir una cosa:

Un millón de gracias!!  ;D
Estuve averiguando y al parecer tengo q usar Visual Studio para utilizar los codigos posteados o me equivoco?

Saludos.

Eleкtro

#319
Cita de: MauriH en 14 Octubre 2013, 20:23 PMEstuve averiguando y al parecer tengo q usar Visual Studio para utilizar los codigos posteados o me equivoco?

Si, estás en lo cierto, tienes que usar VisualStudio,
existen otras IDES como SharpDevelop, MonoDevelop, e incluso puedes programar/compilar C# online desde la página -> CodeRun,
pero en mi opinión como la IDE de Microsoft no hay ninguna que se pueda comparar, aunque si tienes un PC lento quizás prefieras usar sharpdevelop porque VisualStudio consume bastantes recursos del sistema (no se puede ser el mejor sin tener algún inconveniente).

EDITO:
En -> IDEOne y -> CompileOnline puedes compilar código VBNET.

Un saludo!