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

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 ... 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 [39] 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,328 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #380 en: 21 Febrero 2014, 03:59 am »

Ejemplo de como encontrar e invocar un método usando Reflection, si solo tenemos un String que contiene el nombre del método, y como pasarle un parámetro nulo al invocar.

Código
  1. Imports System.Reflection
  2. Imports System.Globalization
  3.  
  4. Public Class Form1
  5.  
  6.    Private Shadows Sub Load() Handles MyBase.Load
  7.  
  8.        Dim MethodName As String = "Test"
  9.  
  10.        Dim Method As MethodInfo =
  11.            Me.GetType().GetMethod(MethodName, BindingFlags.IgnoreCase Or BindingFlags.Instance Or
  12.                                               BindingFlags.Public Or BindingFlags.NonPublic)
  13.  
  14.        If Method IsNot Nothing Then
  15.            Method.Invoke(Me, BindingFlags.IgnoreCase Or BindingFlags.Instance Or
  16.                              BindingFlags.Public Or BindingFlags.NonPublic,
  17.                          Nothing,
  18.                          New Object() {"Hello World!", Type.Missing}, CultureInfo.InvariantCulture)
  19.  
  20.        Else
  21.            MsgBox("Method not found.")
  22.  
  23.        End If
  24.  
  25.    End Sub
  26.  
  27.    Private Sub Test(ByVal StringValue As String, Optional ByVal IntValue As Integer = 1)
  28.        MessageBox.Show(StringValue & IntValue)
  29.    End Sub
  30.  
  31. End Class



Un DateDifference personalizado:

Código
  1.    ' Date Difference
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples :
  5.    '
  6.    ' MsgBox(DateDifference(DateTime.Parse("01/03/2013 00:00:00"),
  7.    '                       DateTime.Parse("09/04/2014 01:01:01"),
  8.    '                       "{0} Year(s), {1} Month(s), {2} Week(s), {3} Day(s), {4} Hour(s), {5} Minute(s) and {6} Second(s)"))
  9.  
  10.    ''' <summary>
  11.    ''' Shows the difference between two dates with custom string format.
  12.    ''' </summary>
  13.    ''' <param name="Date1">Indicates the first date to compare.</param>
  14.    ''' <param name="Date2">Indicates the second date to compare.</param>
  15.    ''' <param name="StringFormat">
  16.    ''' Indicates the string format to display the difference, where:
  17.    ''' {0} = Years, {1} = Months, {2} = Weeks, {3} = Days, {4} = Hours, {5} = Minutes and {6} = Seconds</param>
  18.    ''' <returns>System.String.</returns>
  19.    Private Function DateDifference(ByVal Date1 As DateTime,
  20.                                    ByVal Date2 As DateTime,
  21.                                    ByVal StringFormat As String) As String
  22.  
  23.        Dim Time As TimeSpan
  24.        Dim YearDiff As Integer, MonthDiff As Integer, WeekDiff As Integer
  25.  
  26.        Do Until Date1 > Date2
  27.  
  28.            Date1 = Date1.AddMonths(1)
  29.            MonthDiff += 1
  30.  
  31.            If MonthDiff = 12 Then
  32.                YearDiff += 1
  33.                MonthDiff = 0
  34.            End If
  35.  
  36.        Loop
  37.  
  38.        MonthDiff -= 1
  39.        Date1 = Date1.AddMonths(-1)
  40.        Time = (Date2 - Date1)
  41.        WeekDiff = (Time.Days \ 7)
  42.        Time = (Time - TimeSpan.FromDays(WeekDiff * 7))
  43.  
  44.        Return String.Format(StringFormat, YearDiff, MonthDiff, WeekDiff, Time.Days, Time.Hours, Time.Minutes, Time.Seconds)
  45.  
  46.    End Function


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #381 en: 21 Febrero 2014, 12:18 pm »

Un helper class para el método SendInput de la WinAPI

Synthesizes keystrokes, mouse motions, and button clicks.

PD: El método 'sendkeys' no es 100% perfecto con caracteres especiales como la 'Ñ', pero tampoco lo voy a elaborar más por el momento,ya que es un coñazo por los distintos layouts del teclado.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-21-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SendInputs.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Private Sub Test() Handles Button1.Click
  13.  
  14. ' AppActivate(Process.GetProcessesByName("notepad").First.Id)
  15.  
  16. ' Dim c As Char = Convert.ToChar(Keys.Oemtilde) ' Ñ
  17. ' Dim Result As Integer = SendInputs.SendKey(Convert.ToChar(c.ToString.ToLower))
  18. ' MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result)))
  19.  
  20. ' SendInputs.SendKey(Keys.Enter)
  21. ' SendInputs.SendKey(Convert.ToChar(Keys.Back))
  22. ' SendInputs.SendKeys("Hello World", True)
  23. ' SendInputs.SendKey(Convert.ToChar(Keys.D0))
  24. ' SendInputs.SendKeys(Keys.Insert, BlockInput:=True)
  25.  
  26. ' SendInputs.MouseClick(SendInputs.MouseButton.RightPress, False)
  27. ' SendInputs.MouseMove(5, -5)
  28. ' SendInputs.MousePosition(New Point(100, 500))
  29.  
  30. 'End Sub
  31.  
  32. #End Region
  33.  
  34. #Region " Imports "
  35.  
  36. Imports System.Runtime.InteropServices
  37. Imports System.ComponentModel
  38.  
  39. #End Region
  40.  
  41. ''' <summary>
  42. ''' Synthesizes keystrokes, mouse motions, and button clicks.
  43. ''' </summary>
  44. Public Class SendInputs
  45.  
  46. #Region " P/Invoke "
  47.  
  48.    Friend Class NativeMethods
  49.  
  50. #Region " Methods "
  51.  
  52.        ''' <summary>
  53.        ''' Blocks keyboard and mouse input events from reaching applications.
  54.        ''' For more info see here:
  55.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx
  56.        ''' </summary>
  57.        ''' <param name="fBlockIt">
  58.        ''' The function's purpose.
  59.        ''' If this parameter is 'TRUE', keyboard and mouse input events are blocked.
  60.        ''' If this parameter is 'FALSE', keyboard and mouse events are unblocked.
  61.        ''' </param>
  62.        ''' <returns>
  63.        ''' If the function succeeds, the return value is nonzero.
  64.        ''' If input is already blocked, the return value is zero.
  65.        ''' </returns>
  66.        ''' <remarks>
  67.        ''' Note that only the thread that blocked input can successfully unblock input.
  68.        ''' </remarks>
  69.        <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall,
  70.        SetLastError:=True)>
  71.        Friend Shared Function BlockInput(
  72.               ByVal fBlockIt As Boolean
  73.        ) As Integer
  74.        End Function
  75.  
  76.        ''' <summary>
  77.        ''' Synthesizes keystrokes, mouse motions, and button clicks.
  78.        ''' For more info see here:
  79.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx
  80.        ''' </summary>
  81.        ''' <param name="nInputs">
  82.        ''' Indicates the number of structures in the pInputs array.
  83.        ''' </param>
  84.        ''' <param name="pInputs">
  85.        ''' Indicates an Array of 'INPUT' structures.
  86.        ''' Each structure represents an event to be inserted into the keyboard or mouse input stream.
  87.        ''' </param>
  88.        ''' <param name="cbSize">
  89.        ''' The size, in bytes, of an 'INPUT' structure.
  90.        ''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails.
  91.        ''' </param>
  92.        ''' <returns>
  93.        ''' The function returns the number of events that it successfully
  94.        ''' inserted into the keyboard or mouse input stream.
  95.        ''' If the function returns zero, the input was already blocked by another thread.
  96.        ''' </returns>
  97.        <DllImport("user32.dll", SetLastError:=True)>
  98.        Friend Shared Function SendInput(
  99.               ByVal nInputs As Integer,
  100.               <MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(),
  101.               ByVal cbSize As Integer
  102.        ) As Integer
  103.        End Function
  104.  
  105. #End Region
  106.  
  107. #Region " Enumerations "
  108.  
  109.        ''' <summary>
  110.        ''' VirtualKey codes.
  111.        ''' </summary>
  112.        Friend Enum VirtualKeys As Short
  113.  
  114.            ''' <summary>
  115.            ''' The Shift key.
  116.            ''' VK_SHIFT
  117.            ''' </summary>
  118.            SHIFT = &H10S
  119.  
  120.            ''' <summary>
  121.            ''' The DEL key.
  122.            ''' VK_DELETE
  123.            ''' </summary>
  124.            DELETE = 46S
  125.  
  126.            ''' <summary>
  127.            ''' The ENTER key.
  128.            ''' VK_RETURN
  129.            ''' </summary>
  130.            [RETURN] = 13S
  131.  
  132.        End Enum
  133.  
  134.        ''' <summary>
  135.        ''' The type of the input event.
  136.        ''' For more info see here:
  137.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
  138.        ''' </summary>
  139.        <Description("Enumeration used for 'type' parameter of 'INPUT' structure")>
  140.        Friend Enum InputType As Integer
  141.  
  142.            ''' <summary>
  143.            ''' The event is a mouse event.
  144.            ''' Use the mi structure of the union.
  145.            ''' </summary>
  146.            Mouse = 0
  147.  
  148.            ''' <summary>
  149.            ''' The event is a keyboard event.
  150.            ''' Use the ki structure of the union.
  151.            ''' </summary>
  152.            Keyboard = 1
  153.  
  154.            ''' <summary>
  155.            ''' The event is a hardware event.
  156.            ''' Use the hi structure of the union.
  157.            ''' </summary>
  158.            Hardware = 2
  159.  
  160.        End Enum
  161.  
  162.        ''' <summary>
  163.        ''' Specifies various aspects of a keystroke.
  164.        ''' This member can be certain combinations of the following values.
  165.        ''' For more info see here:
  166.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
  167.        ''' </summary>
  168.        <Description("Enumeration used for 'dwFlags' parameter of 'KeyboardInput' structure")>
  169.        <Flags>
  170.        Friend Enum KeyboardInput_Flags As Integer
  171.  
  172.            ''' <summary>
  173.            ''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224).
  174.            ''' </summary>
  175.            ExtendedKey = &H1
  176.  
  177.            ''' <summary>
  178.            ''' If specified, the key is being pressed.
  179.            ''' </summary>
  180.            KeyDown = &H0
  181.  
  182.            ''' <summary>
  183.            ''' If specified, the key is being released.
  184.            ''' If not specified, the key is being pressed.
  185.            ''' </summary>
  186.            KeyUp = &H2
  187.  
  188.            ''' <summary>
  189.            ''' If specified, 'wScan' identifies the key and 'wVk' is ignored.
  190.            ''' </summary>
  191.            ScanCode = &H8
  192.  
  193.            ''' <summary>
  194.            ''' If specified, the system synthesizes a 'VK_PACKET' keystroke.
  195.            ''' The 'wVk' parameter must be '0'.
  196.            ''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag.
  197.            ''' </summary>
  198.            Unicode = &H4
  199.  
  200.        End Enum
  201.  
  202.        ''' <summary>
  203.        ''' A set of bit flags that specify various aspects of mouse motion and button clicks.
  204.        ''' The bits in this member can be any reasonable combination of the following values.
  205.        ''' For more info see here:
  206.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
  207.        ''' </summary>
  208.        <Description("Enumeration used for 'dwFlags' parameter of 'MouseInput' structure")>
  209.        <Flags>
  210.        Friend Enum MouseInput_Flags As Integer
  211.  
  212.            ''' <summary>
  213.            ''' The 'dx' and 'dy' members contain normalized absolute coordinates.
  214.            ''' If the flag is not set, 'dx' and 'dy' contain relative data
  215.            ''' (the change in position since the last reported position).
  216.            ''' This flag can be set, or not set,
  217.            ''' regardless of what kind of mouse or other pointing device, if any, is connected to the system.
  218.            ''' </summary>
  219.            Absolute = &H8000I
  220.  
  221.            ''' <summary>
  222.            ''' Movement occurred.
  223.            ''' </summary>
  224.            Move = &H1I
  225.  
  226.            ''' <summary>
  227.            ''' The 'WM_MOUSEMOVE' messages will not be coalesced.
  228.            ''' The default behavior is to coalesce 'WM_MOUSEMOVE' messages.
  229.            ''' </summary>
  230.            Move_NoCoalesce = &H2000I
  231.  
  232.            ''' <summary>
  233.            ''' The left button was pressed.
  234.            ''' </summary>
  235.            LeftDown = &H2I
  236.  
  237.            ''' <summary>
  238.            ''' The left button was released.
  239.            ''' </summary>
  240.            LeftUp = &H4I
  241.  
  242.            ''' <summary>
  243.            ''' The right button was pressed.
  244.            ''' </summary>
  245.            RightDown = &H8I
  246.  
  247.            ''' <summary>
  248.            ''' The right button was released.
  249.            ''' </summary>
  250.            RightUp = &H10I
  251.  
  252.            ''' <summary>
  253.            ''' The middle button was pressed.
  254.            ''' </summary>
  255.            MiddleDown = &H20I
  256.  
  257.            ''' <summary>
  258.            ''' The middle button was released.
  259.            ''' </summary>
  260.            MiddleUp = &H40I
  261.  
  262.            ''' <summary>
  263.            ''' Maps coordinates to the entire desktop.
  264.            ''' Must be used in combination with 'Absolute'.
  265.            ''' </summary>
  266.            VirtualDesk = &H4000I
  267.  
  268.            ''' <summary>
  269.            ''' The wheel was moved, if the mouse has a wheel.
  270.            ''' The amount of movement is specified in 'mouseData'.
  271.            ''' </summary>
  272.            Wheel = &H800I
  273.  
  274.            ''' <summary>
  275.            ''' The wheel was moved horizontally, if the mouse has a wheel.
  276.            ''' The amount of movement is specified in 'mouseData'.
  277.            ''' </summary>
  278.            HWheel = &H1000I
  279.  
  280.            ''' <summary>
  281.            ''' An X button was pressed.
  282.            ''' </summary>
  283.            XDown = &H80I
  284.  
  285.            ''' <summary>
  286.            ''' An X button was released.
  287.            ''' </summary>
  288.            XUp = &H100I
  289.  
  290.        End Enum
  291.  
  292. #End Region
  293.  
  294. #Region " Structures "
  295.  
  296.        ''' <summary>
  297.        ''' Used by 'SendInput' function
  298.        ''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.
  299.        ''' For more info see here:
  300.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
  301.        ''' </summary>
  302.        <Description("Structure used for 'INPUT' parameter of 'SendInput' API method")>
  303.        <StructLayout(LayoutKind.Explicit)>
  304.        Friend Structure Input
  305.  
  306.            ' ******
  307.            '  NOTE
  308.            ' ******
  309.            ' Field offset for 32 bit machine: 4
  310.            ' Field offset for 64 bit machine: 8
  311.  
  312.            ''' <summary>
  313.            ''' The type of the input event.
  314.            ''' </summary>
  315.            <FieldOffset(0)>
  316.            Public type As InputType
  317.  
  318.            ''' <summary>
  319.            ''' The information about a simulated mouse event.
  320.            ''' </summary>
  321.            <FieldOffset(8)>
  322.            Public mi As MouseInput
  323.  
  324.            ''' <summary>
  325.            ''' The information about a simulated keyboard event.
  326.            ''' </summary>
  327.            <FieldOffset(8)>
  328.            Public ki As KeyboardInput
  329.  
  330.            ''' <summary>
  331.            ''' The information about a simulated hardware event.
  332.            ''' </summary>
  333.            <FieldOffset(8)>
  334.            Public hi As HardwareInput
  335.  
  336.        End Structure
  337.  
  338.        ''' <summary>
  339.        ''' Contains information about a simulated mouse event.
  340.        ''' For more info see here:
  341.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
  342.        ''' </summary>
  343.        <Description("Structure used for 'mi' parameter of 'INPUT' structure")>
  344.        Friend Structure MouseInput
  345.  
  346.            ''' <summary>
  347.            ''' The absolute position of the mouse,
  348.            ''' or the amount of motion since the last mouse event was generated,
  349.            ''' depending on the value of the dwFlags member.
  350.            ''' Absolute data is specified as the 'x' coordinate of the mouse;
  351.            ''' relative data is specified as the number of pixels moved.
  352.            ''' </summary>
  353.            Public dx As Integer
  354.  
  355.            ''' <summary>
  356.            ''' The absolute position of the mouse,
  357.            ''' or the amount of motion since the last mouse event was generated,
  358.            ''' depending on the value of the dwFlags member.
  359.            ''' Absolute data is specified as the 'y' coordinate of the mouse;
  360.            ''' relative data is specified as the number of pixels moved.
  361.            ''' </summary>
  362.            Public dy As Integer
  363.  
  364.            ''' <summary>
  365.            ''' If 'dwFlags' contains 'MOUSEEVENTF_WHEEL',
  366.            ''' then 'mouseData' specifies the amount of wheel movement.
  367.            ''' A positive value indicates that the wheel was rotated forward, away from the user;
  368.            ''' a negative value indicates that the wheel was rotated backward, toward the user.
  369.            ''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
  370.            '''
  371.            ''' If 'dwFlags' does not contain 'MOUSEEVENTF_WHEEL', 'MOUSEEVENTF_XDOWN', or 'MOUSEEVENTF_XUP',
  372.            ''' then mouseData should be '0'.
  373.            ''' </summary>
  374.            Public mouseData As Integer
  375.  
  376.            ''' <summary>
  377.            ''' A set of bit flags that specify various aspects of mouse motion and button clicks.
  378.            ''' The bits in this member can be any reasonable combination of the following values.
  379.            ''' The bit flags that specify mouse button status are set to indicate changes in status,
  380.            ''' not ongoing conditions.
  381.            ''' For example, if the left mouse button is pressed and held down,
  382.            ''' 'MOUSEEVENTF_LEFTDOWN' is set when the left button is first pressed,
  383.            ''' but not for subsequent motions.
  384.            ''' Similarly, 'MOUSEEVENTF_LEFTUP' is set only when the button is first released.
  385.            '''
  386.            ''' You cannot specify both the 'MOUSEEVENTF_WHEE'L flag
  387.            ''' and either 'MOUSEEVENTF_XDOWN' or 'MOUSEEVENTF_XUP' flags simultaneously in the 'dwFlags' parameter,
  388.            ''' because they both require use of the 'mouseData' field.
  389.            ''' </summary>
  390.            Public dwFlags As MouseInput_Flags
  391.  
  392.            ''' <summary>
  393.            ''' The time stamp for the event, in milliseconds.
  394.            ''' If this parameter is '0', the system will provide its own time stamp.
  395.            ''' </summary>
  396.            Public time As Integer
  397.  
  398.            ''' <summary>
  399.            ''' An additional value associated with the mouse event.
  400.            ''' An application calls 'GetMessageExtraInfo' to obtain this extra information.
  401.            ''' </summary>
  402.            Public dwExtraInfo As IntPtr
  403.  
  404.        End Structure
  405.  
  406.        ''' <summary>
  407.        ''' Contains information about a simulated keyboard event.
  408.        ''' For more info see here:
  409.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
  410.        ''' </summary>
  411.        <Description("Structure used for 'ki' parameter of 'INPUT' structure")>
  412.        Friend Structure KeyboardInput
  413.  
  414.            ''' <summary>
  415.            ''' A virtual-key code.
  416.            ''' The code must be a value in the range '1' to '254'.
  417.            ''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'.
  418.            ''' </summary>
  419.            Public wVk As Short
  420.  
  421.            ''' <summary>
  422.            ''' A hardware scan code for the key.
  423.            ''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE',
  424.            ''' 'wScan' specifies a Unicode character which is to be sent to the foreground application.
  425.            ''' </summary>
  426.            Public wScan As Short
  427.  
  428.            ''' <summary>
  429.            ''' Specifies various aspects of a keystroke.
  430.            ''' </summary>
  431.            Public dwFlags As KeyboardInput_Flags
  432.  
  433.            ''' <summary>
  434.            ''' The time stamp for the event, in milliseconds.
  435.            ''' If this parameter is '0', the system will provide its own time stamp.
  436.            ''' </summary>
  437.            Public time As Integer
  438.  
  439.            ''' <summary>
  440.            ''' An additional value associated with the keystroke.
  441.            ''' Use the 'GetMessageExtraInfo' function to obtain this information.
  442.            ''' </summary>
  443.            Public dwExtraInfo As IntPtr
  444.  
  445.        End Structure
  446.  
  447.        ''' <summary>
  448.        ''' Contains information about a simulated message generated by an input device other than a keyboard or mouse.
  449.        ''' For more info see here:
  450.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx
  451.        ''' </summary>
  452.        <Description("Structure used for 'hi' parameter of 'INPUT' structure")>
  453.        Friend Structure HardwareInput
  454.  
  455.            ''' <summary>
  456.            ''' The message generated by the input hardware.
  457.            ''' </summary>
  458.            Public uMsg As Integer
  459.  
  460.            ''' <summary>
  461.            ''' The low-order word of the lParam parameter for uMsg.
  462.            ''' </summary>
  463.            Public wParamL As Short
  464.  
  465.            ''' <summary>
  466.            ''' The high-order word of the lParam parameter for uMsg.
  467.            ''' </summary>
  468.            Public wParamH As Short
  469.  
  470.        End Structure
  471.  
  472. #End Region
  473.  
  474.    End Class
  475.  
  476. #End Region
  477.  
  478. #Region " Enumerations "
  479.  
  480.    ''' <summary>
  481.    ''' Indicates a mouse button.
  482.    ''' </summary>
  483.    <Description("Enumeration used for 'MouseAction' parameter of 'MouseClick' function.")>
  484.    Public Enum MouseButton As Integer
  485.  
  486.        ''' <summary>
  487.        ''' Hold the left button.
  488.        ''' </summary>
  489.        LeftDown = &H2I
  490.  
  491.        ''' <summary>
  492.        ''' Release the left button.
  493.        ''' </summary>
  494.        LeftUp = &H4I
  495.  
  496.        ''' <summary>
  497.        ''' Hold the right button.
  498.        ''' </summary>
  499.        RightDown = &H8I
  500.  
  501.        ''' <summary>
  502.        ''' Release the right button.
  503.        ''' </summary>
  504.        RightUp = &H10I
  505.  
  506.        ''' <summary>
  507.        ''' Hold the middle button.
  508.        ''' </summary>
  509.        MiddleDown = &H20I
  510.  
  511.        ''' <summary>
  512.        ''' Release the middle button.
  513.        ''' </summary>
  514.        MiddleUp = &H40I
  515.  
  516.        ''' <summary>
  517.        ''' Press the left button.
  518.        ''' ( Hold + Release )
  519.        ''' </summary>
  520.        LeftPress = LeftDown + LeftUp
  521.  
  522.        ''' <summary>
  523.        ''' Press the Right button.
  524.        ''' ( Hold + Release )
  525.        ''' </summary>
  526.        RightPress = RightDown + RightUp
  527.  
  528.        ''' <summary>
  529.        ''' Press the Middle button.
  530.        ''' ( Hold + Release )
  531.        ''' </summary>
  532.        MiddlePress = MiddleDown + MiddleUp
  533.  
  534.    End Enum
  535.  
  536. #End Region
  537.  
  538. #Region " Public Methods "
  539.  
  540.    ''' <summary>
  541.    ''' Sends a keystroke.
  542.    ''' </summary>
  543.    ''' <param name="key">
  544.    ''' Indicates the keystroke to simulate.
  545.    ''' </param>
  546.    ''' <param name="BlockInput">
  547.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  548.    ''' </param>
  549.    ''' <returns>
  550.    ''' The function returns the number of events that it successfully inserted into the keyboard input stream.
  551.    ''' If the function returns zero, the input was already blocked by another thread.
  552.    ''' </returns>
  553.    Public Shared Function SendKey(ByVal key As Char,
  554.                                   Optional BlockInput As Boolean = False) As Integer
  555.  
  556.        ' Block Keyboard and mouse.
  557.        If BlockInput Then NativeMethods.BlockInput(True)
  558.  
  559.        ' The inputs structures to send.
  560.        Dim Inputs As New List(Of NativeMethods.INPUT)
  561.  
  562.        ' The current input to add into the Inputs list.
  563.        Dim CurrentInput As New NativeMethods.INPUT
  564.  
  565.        ' Determines whether a character is an alphabetic letter.
  566.        Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower)
  567.  
  568.        ' Determines whether a character is an uppercase alphabetic letter.
  569.        Dim IsUpperCase As Boolean =
  570.            (key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower)
  571.  
  572.        ' Determines whether the CapsLock key is pressed down.
  573.        Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock
  574.  
  575.        ' Set the passed key to upper-case.
  576.        If IsAlphabetic AndAlso Not IsUpperCase Then
  577.            key = Convert.ToChar(key.ToString.ToUpper)
  578.        End If
  579.  
  580.        ' If character is alphabetic and is UpperCase and CapsLock is pressed down,
  581.        ' OrElse character is alphabetic and is not UpperCase and CapsLock is not pressed down,
  582.        ' OrElse character is not alphabetic.
  583.        If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _
  584.        OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _
  585.        OrElse (Not IsAlphabetic) Then
  586.  
  587.            ' Hold the character key.
  588.            With CurrentInput
  589.                .type = NativeMethods.InputType.Keyboard
  590.                .ki.wVk = Convert.ToInt16(CChar(key))
  591.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  592.            End With : Inputs.Add(CurrentInput)
  593.  
  594.            ' Release the character key.
  595.            With CurrentInput
  596.                .type = NativeMethods.InputType.Keyboard
  597.                .ki.wVk = Convert.ToInt16(CChar(key))
  598.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  599.            End With : Inputs.Add(CurrentInput)
  600.  
  601.            ' If character is alphabetic and is UpperCase and CapsLock is not pressed down,
  602.            ' OrElse character is alphabetic and is not UpperCase and CapsLock is pressed down.
  603.        ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _
  604.        OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then
  605.  
  606.            ' Hold the Shift key.
  607.            With CurrentInput
  608.                .type = NativeMethods.InputType.Keyboard
  609.                .ki.wVk = NativeMethods.VirtualKeys.SHIFT
  610.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  611.            End With : Inputs.Add(CurrentInput)
  612.  
  613.            ' Hold the character key.
  614.            With CurrentInput
  615.                .type = NativeMethods.InputType.Keyboard
  616.                .ki.wVk = Convert.ToInt16(CChar(key))
  617.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  618.            End With : Inputs.Add(CurrentInput)
  619.  
  620.            ' Release the character key.
  621.            With CurrentInput
  622.                .type = NativeMethods.InputType.Keyboard
  623.                .ki.wVk = Convert.ToInt16(CChar(key))
  624.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  625.            End With : Inputs.Add(CurrentInput)
  626.  
  627.            ' Release the Shift key.
  628.            With CurrentInput
  629.                .type = NativeMethods.InputType.Keyboard
  630.                .ki.wVk = NativeMethods.VirtualKeys.SHIFT
  631.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  632.            End With : Inputs.Add(CurrentInput)
  633.  
  634.        End If ' UpperCase And My.Computer.Keyboard.CapsLock is...
  635.  
  636.        ' Send the input key.
  637.        Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
  638.                                       Marshal.SizeOf(GetType(NativeMethods.Input)))
  639.  
  640.        ' Unblock Keyboard and mouse.
  641.        If BlockInput Then NativeMethods.BlockInput(False)
  642.  
  643.    End Function
  644.  
  645.    ''' <summary>
  646.    ''' Sends a keystroke.
  647.    ''' </summary>
  648.    ''' <param name="key">
  649.    ''' Indicates the keystroke to simulate.
  650.    ''' </param>
  651.    ''' <param name="BlockInput">
  652.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  653.    ''' </param>
  654.    ''' <returns>
  655.    ''' The function returns the number of events that it successfully inserted into the keyboard input stream.
  656.    ''' If the function returns zero, the input was already blocked by another thread.
  657.    ''' </returns>
  658.    Public Shared Function SendKey(ByVal key As Keys,
  659.                                   Optional BlockInput As Boolean = False) As Integer
  660.  
  661.        Return SendKey(Convert.ToChar(key), BlockInput)
  662.  
  663.    End Function
  664.  
  665.    ''' <summary>
  666.    ''' Sends a string.
  667.    ''' </summary>
  668.    ''' <param name="String">
  669.    ''' Indicates the string to send.
  670.    ''' </param>
  671.    ''' <param name="BlockInput">
  672.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  673.    ''' </param>
  674.    ''' <returns>
  675.    ''' The function returns the number of events that it successfully inserted into the keyboard input stream.
  676.    ''' If the function returns zero, the input was already blocked by another thread.
  677.    ''' </returns>
  678.    Public Shared Function SendKeys(ByVal [String] As String,
  679.                                    Optional BlockInput As Boolean = False) As Integer
  680.  
  681.        Dim SuccessCount As Integer = 0
  682.  
  683.        ' Block Keyboard and mouse.
  684.        If BlockInput Then NativeMethods.BlockInput(True)
  685.  
  686.        For Each c As Char In [String]
  687.            SuccessCount += SendKey(c, BlockInput:=False)
  688.        Next c
  689.  
  690.        ' Unblock Keyboard and mouse.
  691.        If BlockInput Then NativeMethods.BlockInput(False)
  692.  
  693.        Return SuccessCount
  694.  
  695.    End Function
  696.  
  697.    ''' <summary>
  698.    ''' Slices the mouse position.
  699.    ''' </summary>
  700.    ''' <param name="Offset">
  701.    ''' Indicates the offset, in coordinates.
  702.    ''' </param>
  703.    ''' <param name="BlockInput">
  704.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the mouse movement is sent.
  705.    ''' </param>
  706.    ''' <returns>
  707.    ''' The function returns the number of events that it successfully inserted into the mouse input stream.
  708.    ''' If the function returns zero, the input was already blocked by another thread.
  709.    ''' </returns>
  710.    Public Shared Function MouseMove(ByVal Offset As Point,
  711.                                     Optional BlockInput As Boolean = False) As Integer
  712.  
  713.        ' Block Keyboard and mouse.
  714.        If BlockInput Then NativeMethods.BlockInput(True)
  715.  
  716.        ' The inputs structures to send.
  717.        Dim Inputs As New List(Of NativeMethods.Input)
  718.  
  719.        ' The current input to add into the Inputs list.
  720.        Dim CurrentInput As New NativeMethods.Input
  721.  
  722.        ' Add a mouse movement.
  723.        With CurrentInput
  724.            .type = NativeMethods.InputType.Mouse
  725.            .mi.dx = Offset.X
  726.            .mi.dy = Offset.Y
  727.            .mi.dwFlags = NativeMethods.MouseInput_Flags.Move
  728.        End With : Inputs.Add(CurrentInput)
  729.  
  730.        ' Send the mouse movement.
  731.        Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
  732.                                       Marshal.SizeOf(GetType(NativeMethods.Input)))
  733.  
  734.        ' Unblock Keyboard and mouse.
  735.        If BlockInput Then NativeMethods.BlockInput(False)
  736.  
  737.    End Function
  738.  
  739.    ''' <summary>
  740.    ''' Slices the mouse position.
  741.    ''' </summary>
  742.    ''' <param name="X">
  743.    ''' Indicates the 'X' offset.
  744.    ''' </param>
  745.    ''' <param name="Y">
  746.    ''' Indicates the 'Y' offset.
  747.    ''' </param>
  748.    ''' <param name="BlockInput">
  749.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the mouse movement is sent.
  750.    ''' </param>
  751.    ''' <returns>
  752.    ''' The function returns the number of events that it successfully inserted into the mouse input stream.
  753.    ''' If the function returns zero, the input was already blocked by another thread.
  754.    ''' </returns>
  755.    Public Shared Function MouseMove(ByVal X As Integer, ByVal Y As Integer,
  756.                                     Optional BlockInput As Boolean = False) As Integer
  757.  
  758.        Return MouseMove(New Point(X, Y), BlockInput)
  759.  
  760.    End Function
  761.  
  762.    ''' <summary>
  763.    ''' Moves the mouse hotspot to an absolute position, in coordinates.
  764.    ''' </summary>
  765.    ''' <param name="Position">
  766.    ''' Indicates the absolute position.
  767.    ''' </param>
  768.    ''' <param name="BlockInput">
  769.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the mouse movement is sent.
  770.    ''' </param>
  771.    ''' <returns>
  772.    ''' The function returns the number of events that it successfully inserted into the mouse input stream.
  773.    ''' If the function returns zero, the input was already blocked by another thread.
  774.    ''' </returns>
  775.    Public Shared Function MousePosition(ByVal Position As Point,
  776.                                         Optional BlockInput As Boolean = False) As Integer
  777.  
  778.        ' Block Keyboard and mouse.
  779.        If BlockInput Then NativeMethods.BlockInput(True)
  780.  
  781.        ' The inputs structures to send.
  782.        Dim Inputs As New List(Of NativeMethods.Input)
  783.  
  784.        ' The current input to add into the Inputs list.
  785.        Dim CurrentInput As New NativeMethods.Input
  786.  
  787.        ' Transform the coordinates.
  788.        Position.X = CInt(Position.X * 65535 / (Screen.PrimaryScreen.Bounds.Width - 1))
  789.        Position.Y = CInt(Position.Y * 65535 / (Screen.PrimaryScreen.Bounds.Height - 1))
  790.  
  791.        ' Add an absolute mouse movement.
  792.        With CurrentInput
  793.            .type = NativeMethods.InputType.Mouse
  794.            .mi.dx = Position.X
  795.            .mi.dy = Position.Y
  796.            .mi.dwFlags = NativeMethods.MouseInput_Flags.Absolute Or NativeMethods.MouseInput_Flags.Move
  797.            .mi.time = 0
  798.        End With : Inputs.Add(CurrentInput)
  799.  
  800.        ' Send the absolute mouse movement.
  801.        Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
  802.                                       Marshal.SizeOf(GetType(NativeMethods.Input)))
  803.  
  804.        ' Unblock Keyboard and mouse.
  805.        If BlockInput Then NativeMethods.BlockInput(False)
  806.  
  807.    End Function
  808.  
  809.    ''' <summary>
  810.    ''' Moves the mouse hotspot to an absolute position, in coordinates.
  811.    ''' </summary>
  812.    ''' <param name="X">
  813.    ''' Indicates the absolute 'X' coordinate.
  814.    ''' </param>
  815.    ''' <param name="Y">
  816.    ''' Indicates the absolute 'Y' coordinate.
  817.    ''' </param>
  818.    ''' <param name="BlockInput">
  819.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the mouse movement is sent.
  820.    ''' </param>
  821.    ''' <returns>
  822.    ''' The function returns the number of events that it successfully inserted into the mouse input stream.
  823.    ''' If the function returns zero, the input was already blocked by another thread.
  824.    ''' </returns>
  825.    Public Shared Function MousePosition(ByVal X As Integer, ByVal Y As Integer,
  826.                                         Optional BlockInput As Boolean = False) As Integer
  827.  
  828.        Return MousePosition(New Point(X, Y), BlockInput)
  829.  
  830.    End Function
  831.  
  832.    ''' <summary>
  833.    ''' Simulates a mouse click.
  834.    ''' </summary>
  835.    ''' <param name="MouseAction">
  836.    ''' Indicates the mouse action to perform.
  837.    ''' </param>
  838.    ''' <param name="BlockInput">
  839.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the mouse movement is sent.
  840.    ''' </param>
  841.    ''' <returns>
  842.    ''' The function returns the number of events that it successfully inserted into the mouse input stream.
  843.    ''' If the function returns zero, the input was already blocked by another thread.
  844.    ''' </returns>
  845.    Public Shared Function MouseClick(ByVal MouseAction As MouseButton,
  846.                                      Optional BlockInput As Boolean = False) As Integer
  847.  
  848.        ' Block Keyboard and mouse.
  849.        If BlockInput Then NativeMethods.BlockInput(True)
  850.  
  851.        ' The inputs structures to send.
  852.        Dim Inputs As New List(Of NativeMethods.Input)
  853.  
  854.        ' The current input to add into the Inputs list.
  855.        Dim CurrentInput As New NativeMethods.Input
  856.  
  857.        ' The mouse actions to perform.
  858.        Dim MouseActions As New List(Of MouseButton)
  859.  
  860.        Select Case MouseAction
  861.  
  862.            Case MouseButton.LeftPress ' Left button, hold and release.
  863.                MouseActions.Add(MouseButton.LeftDown)
  864.                MouseActions.Add(MouseButton.LeftUp)
  865.  
  866.            Case MouseButton.RightPress ' Right button, hold and release.
  867.                MouseActions.Add(MouseButton.RightDown)
  868.                MouseActions.Add(MouseButton.RightUp)
  869.  
  870.            Case MouseButton.MiddlePress ' Middle button, hold and release.
  871.                MouseActions.Add(MouseButton.MiddleDown)
  872.                MouseActions.Add(MouseButton.MiddleUp)
  873.  
  874.            Case Else ' Other
  875.                MouseActions.Add(MouseAction)
  876.  
  877.        End Select ' MouseAction
  878.  
  879.        For Each Action As MouseButton In MouseActions
  880.  
  881.            ' Add the mouse click.
  882.            With CurrentInput
  883.                .type = NativeMethods.InputType.Mouse
  884.                '.mi.dx = Offset.X
  885.                '.mi.dy = Offset.Y
  886.                .mi.dwFlags = Action
  887.            End With : Inputs.Add(CurrentInput)
  888.  
  889.        Next Action
  890.  
  891.        ' Send the mouse click.
  892.        Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
  893.                                       Marshal.SizeOf(GetType(NativeMethods.Input)))
  894.  
  895.        ' Unblock Keyboard and mouse.
  896.        If BlockInput Then NativeMethods.BlockInput(False)
  897.  
  898.    End Function
  899.  
  900. #End Region
  901.  
  902. End Class


« Última modificación: 21 Febrero 2014, 12:24 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #382 en: 24 Febrero 2014, 10:41 am »

String Is Numeric Of DataType?

La típica función para comprobar si un String es numérico, reinventada para cumplir dos tareas en una, comprueba si un string es un valor numérico de un tipo específico.

Código
  1.    ' String Is Numeric Of Type?
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(StringIsNumeric(Of Long)("50.1")) ' Result: False (it's a Double).
  6.    ' MsgBox(StringIsNumeric(Of Integer)("9999999999")) ' Result: False (it's a Long).
  7.    ' MsgBox(StringIsNumeric(Of Integer)(CStr(Integer.MaxValue))) ' Result: True.
  8.    '
  9.    ''' <summary>
  10.    ''' Determines whether an String is a valid numeric value of the specified type.
  11.    ''' </summary>
  12.    ''' <typeparam name="T">Indicates the numeric DataType</typeparam>
  13.    ''' <param name="Value">Indicates the string value.</param>
  14.    ''' <returns>
  15.    ''' <c>true</c> if string is a valid numeric value of the specified type, <c>false</c> otherwise.
  16.    ''' </returns>
  17.    ''' <exception cref="Exception"></exception>
  18.    Private Function StringIsNumeric(Of T)(ByVal Value As String) As Boolean
  19.  
  20.        Const MethodName As String = "TryParse"
  21.        Dim DataType As Type = GetType(T)
  22.        Dim Result As Object = Nothing
  23.  
  24.        Dim Method As System.Reflection.MethodInfo =
  25.        DataType.GetMethod(MethodName,
  26.                           System.Reflection.BindingFlags.Public Or System.Reflection.BindingFlags.Static,
  27.                           Type.DefaultBinder,
  28.                           New Type() {GetType(String), DataType.MakeByRefType()},
  29.                           New System.Reflection.ParameterModifier() {Nothing})
  30.  
  31.        If Method IsNot Nothing Then
  32.            Return Method.Invoke(Nothing,
  33.                                 System.Reflection.BindingFlags.Public Or System.Reflection.BindingFlags.Static,
  34.                                 Type.DefaultBinder,
  35.                                 New Object() {Value, Result},
  36.                                 System.Globalization.CultureInfo.InvariantCulture)
  37.  
  38.        Else
  39.            Throw New Exception(String.Format("Static method '{0}' not found in '{1}' Type.",
  40.                                              MethodName, DataType.Name))
  41.            Return False
  42.  
  43.        End If
  44.  
  45.    End Function
« Última modificación: 24 Febrero 2014, 11:00 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #383 en: 25 Febrero 2014, 16:32 pm »

Código
  1.    ' String Is Alphabetic?
  2.    ' ( By Elektro )
  3.    '
  4.    ''' <summary>
  5.    ''' Determines whether a String is alphabetic.
  6.    ''' </summary>
  7.    ''' <param name="str">Indicates the string.</param>
  8.    ''' <returns><c>true</c> if string only contains alphabetic characters, <c>false</c> otherwise.</returns>
  9.    Private Function StringIsAlphabetic(ByVal str As String) As Boolean
  10.  
  11.        Return Not Convert.ToBoolean((From c As Char In str Where Not "abcdefghijklmnopqrstuvwxyz".Contains(c)).Count)
  12.  
  13.    End Function



Código
  1.   ' Get Biggest Letter Of String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples
  5.    ' MsgBox(GetBiggestLetter("qwerty012345"))
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the biggest letter in a String.
  9.    ''' </summary>
  10.    ''' <param name="str">Indicates the string.</param>
  11.    ''' <returns>System.Char.</returns>
  12.    Private Function GetBiggestLetter(ByVal str As String) As Char
  13.  
  14.        Return (From c As Char In str.ToLower
  15.                Where "abcdefghijklmnopqrstuvwxyz".Contains(c)
  16.                Order By c Descending).FirstOrDefault
  17.  
  18.    End Function

Código
  1.    ' Get Lowest Letter Of String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples
  5.    ' MsgBox(GetLowestLetter("qwerty012345"))
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the lowest letter in a String.
  9.    ''' </summary>
  10.    ''' <param name="str">Indicates the string.</param>
  11.    ''' <returns>System.Char.</returns>
  12.    Private Function GetLowestLetter(ByVal str As String) As Char
  13.  
  14.        Return (From c As Char In str.ToLower
  15.                Where "abcdefghijklmnopqrstuvwxyz".Contains(c)
  16.                Order By c Ascending).FirstOrDefault
  17.  
  18.    End Function

Código
  1.    ' Get Biggest Number Of String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples
  5.    ' MsgBox(GetBiggestNumber("qwerty012345"))
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the biggest number in a String.
  9.    ''' </summary>
  10.    ''' <param name="str">Indicates the string.</param>
  11.    ''' <returns>System.Int32.</returns>
  12.    Private Function GetBiggestNumber(ByVal str As String) As Integer
  13.  
  14.        Return Convert.ToInt32((From c As Char In str
  15.                                Where Integer.TryParse(c, New Integer)
  16.                                Order By c Descending).FirstOrDefault, 10)
  17.  
  18.    End Function

Código
  1.    ' Get Lowest Number Of String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples
  5.    ' MsgBox(GetLowestNumber("qwerty012345"))
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the lowest number in a String.
  9.    ''' </summary>
  10.    ''' <param name="str">Indicates the string.</param>
  11.    ''' <returns>System.Int32.</returns>
  12.    Private Function GetLowestNumber(ByVal str As String) As Integer
  13.  
  14.        Return Convert.ToInt32((From c As Char In str
  15.                                Where Integer.TryParse(c, New Integer)
  16.                                Order By c Ascending).FirstOrDefault, 10)
  17.  
  18.    End Function
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #384 en: 25 Febrero 2014, 17:02 pm »

Una mini-Class para Blinkear un control (efecto de parpadeo), o el texto de un control:



Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-25-2014
  4. ' ***********************************************************************
  5. ' <copyright file="Blinker.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Friend WithEvents LabelBlinker As Blinker
  13.  
  14. 'Private Shadows Sub Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
  15.  
  16. '    LabelBlinker = New Blinker(Textbox1)
  17.  
  18. '    LabelBlinker.Blink(Interval:=500)
  19. '    LabelBlinker.BlinkText(Interval:=500, CustomText:="Custom Text!")
  20.  
  21. '    LabelBlinker.Unblink(Visible:=True)
  22. '    LabelBlinker.UnblinkText(RestoreText:=False)
  23.  
  24. 'End Sub
  25.  
  26. #End Region
  27.  
  28. ''' <summary>
  29. ''' Blinks a Control.
  30. ''' </summary>
  31. Friend NotInheritable Class Blinker
  32.  
  33. #Region " Objects "
  34.  
  35.    ''' <summary>
  36.    ''' The control to blink.
  37.    ''' </summary>
  38.    Private ctrl As Control = Nothing
  39.  
  40.    ''' <summary>
  41.    ''' A Timer to blink a control.
  42.    ''' </summary>
  43.    Private WithEvents BlinkTimer As New Timer
  44.  
  45.    ''' <summary>
  46.    ''' A Timer to blink the text of a control.
  47.    ''' </summary>
  48.    Private WithEvents BlinkTextTimer As New Timer
  49.  
  50.    ''' <summary>
  51.    ''' A custom text to restore after blinking the control.
  52.    ''' </summary>
  53.    Private TextToRestore As String = String.Empty
  54.  
  55. #End Region
  56.  
  57. #Region " Constructors "
  58.  
  59.    ''' <summary>
  60.    ''' Initializes a new instance of the <see cref="Blinker" /> class.
  61.    ''' </summary>
  62.    ''' <param name="ctrl">Indicates the control to blink.</param>
  63.    Public Sub New(ByVal ctrl As Control)
  64.  
  65.        ' Assign the control to blink.
  66.        Me.ctrl = ctrl
  67.  
  68.    End Sub
  69.  
  70. #End Region
  71.  
  72. #Region " Public Methods "
  73.  
  74.    ''' <summary>
  75.    ''' Blinks the Control.
  76.    ''' </summary>
  77.    ''' <param name="Interval">Indicates the blink interval, in ms.</param>
  78.    Public Sub Blink(Optional ByVal Interval As Integer = 500)
  79.  
  80.        With BlinkTimer
  81.            .Interval = Interval
  82.            .Enabled = True
  83.        End With
  84.  
  85.    End Sub
  86.  
  87.    ''' <summary>
  88.    ''' Stop blinking the Control.
  89.    ''' </summary>
  90.    ''' <param name="Visible">Indicates the visibility of the control.</param>
  91.    Public Sub Unblink(Optional ByVal Visible As Boolean = True)
  92.  
  93.        With BlinkTimer
  94.            .Enabled = False
  95.        End With
  96.  
  97.        ctrl.Visible = Visible
  98.  
  99.    End Sub
  100.  
  101.    ''' <summary>
  102.    ''' Blinks the text content of the Control.
  103.    ''' </summary>
  104.    ''' <param name="Interval">Indicates the blink interval.</param>
  105.    ''' <param name="CustomText">Indicates a custom text to blink.</param>
  106.    Public Sub BlinkText(Optional ByVal Interval As Integer = 500,
  107.                         Optional ByVal CustomText As String = Nothing)
  108.  
  109.        With BlinkTextTimer
  110.            .Tag = If(String.IsNullOrEmpty(CustomText), Me.ctrl.Text, CustomText)
  111.            .Interval = Interval
  112.            .Enabled = True
  113.        End With
  114.  
  115.    End Sub
  116.  
  117.    ''' <summary>
  118.    ''' Stop blinking the text content of the Control.
  119.    ''' </summary>
  120.    ''' <param name="RestoreText">If set to <c>true</c>, the control text is resetted to the initial state before started blinking.</param>
  121.    Public Sub UnblinkText(Optional ByVal RestoreText As Boolean = False)
  122.  
  123.        With BlinkTextTimer
  124.            .Enabled = False
  125.        End With
  126.  
  127.        If RestoreText Then
  128.            Me.ctrl.Text = TextToRestore
  129.        End If
  130.  
  131.    End Sub
  132.  
  133. #End Region
  134.  
  135. #Region " Event Handlers"
  136.  
  137.    ''' <summary>
  138.    ''' Handles the Tick event of the BlinkTimer control.
  139.    ''' </summary>
  140.    ''' <param name="sender">The source of the event.</param>
  141.    ''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  142.    Private Sub BlinkTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles BlinkTimer.Tick
  143.  
  144.        Me.ctrl.Visible = Not Me.ctrl.Visible
  145.  
  146.    End Sub
  147.  
  148.    ''' <summary>
  149.    ''' Handles the Tick event of the BlinkTextTimer control.
  150.    ''' </summary>
  151.    ''' <param name="sender">The source of the event.</param>
  152.    ''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  153.    Private Sub BlinkTextTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles BlinkTextTimer.Tick
  154.  
  155.        If String.IsNullOrEmpty(Me.ctrl.Text) Then
  156.            Me.ctrl.Text = CStr(sender.tag)
  157.  
  158.        Else
  159.            Me.ctrl.Text = String.Empty
  160.  
  161.        End If
  162.  
  163.    End Sub
  164.  
  165. #End Region
  166.  
  167. End Class
« Última modificación: 25 Febrero 2014, 17:06 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #385 en: 4 Marzo 2014, 18:19 pm »

Este snippet sirve para rotar la posición de las palabras que contiene un String.

Código
  1.    ' Rotate String
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(RotateString("a b c d e f", RotationDirectorion.Left, 2)) ' Result "c d e f a b"
  6.    ' MsgBox(RotateString("Hello_World_!", RotationDirectorion.Right, 1, "_"c)) ' Result: "!_Hello_World"
  7.  
  8.    ''' <summary>
  9.    ''' Indicates the rotation direction of an String.
  10.    ''' </summary>
  11.    Public Enum RotationDirectorion
  12.  
  13.        ''' <summary>
  14.        ''' Rotates to the left.
  15.        ''' </summary>
  16.        Left
  17.  
  18.        ''' <summary>
  19.        ''' Rotates to the right.
  20.        ''' </summary>
  21.        Right
  22.  
  23.    End Enum
  24.  
  25.    ''' <summary>
  26.    ''' Rotates the words in a String.
  27.    ''' </summary>
  28.    ''' <param name="String">Indicates the string to rotate.</param>
  29.    ''' <param name="Direction">Indicates the rotation direction.</param>
  30.    ''' <param name="Rotation">Indicates the rotation count.</param>
  31.    ''' <param name="Delimiter">
  32.    ''' Indicates the delimiter that is used to split the words of the string.
  33.    ''' Default is 'Space' character.
  34.    ''' </param>
  35.    ''' <returns>System.String.</returns>
  36.    ''' <exception cref="Exception">Rotation count is out of range.</exception>
  37.    Private Function RotateString(ByVal [String] As String,
  38.                                  ByVal Direction As RotationDirectorion,
  39.                                  ByVal Rotation As Integer,
  40.                                  Optional ByVal Delimiter As Char = " "c
  41.                                  ) As String
  42.  
  43.        Dim Parts As String() = [String].Split(Delimiter)
  44.  
  45.        If String.IsNullOrEmpty([String]) OrElse Not [String].Contains(CStr(Delimiter)) Then
  46.            Throw New Exception(String.Format("Delimiter '{0}' not found in the String.", CStr(Delimiter)))
  47.        End If
  48.  
  49.        If Rotation = 0 OrElse Rotation >= Parts.Length Then
  50.            Throw New Exception("Rotation count is out of range.")
  51.        End If
  52.  
  53.        Select Case Direction
  54.  
  55.            Case RotationDirectorion.Left
  56.                Return String.Format("{0}{1}",
  57.                                     String.Join(Delimiter,
  58.                                                 From s As String In Parts Skip Rotation) & CStr(Delimiter),
  59.                                     String.Join(Delimiter,
  60.                                                 From s As String In Parts Take Rotation))
  61.  
  62.            Case RotationDirectorion.Right
  63.                Return String.Format("{0}{1}",
  64.                                     String.Join(Delimiter,
  65.                                                 From s As String In Parts Skip (Parts.Length - Rotation)) & CStr(Delimiter),
  66.                                     String.Join(Delimiter,
  67.                                                 From s As String In Parts Take (Parts.Length - Rotation)))
  68.  
  69.            Case Else
  70.                Return String.Empty
  71.  
  72.        End Select ' Direction
  73.  
  74.    End Function
  75.  

En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #386 en: 5 Marzo 2014, 18:43 pm »

Una Class para utilizar el cifrado cromático de texto, es decir, esto:




Aquí pueden descargar la Class (no soy el autor de este laborioso código, solo lo adapté un poco añadiéndole algún método más, y elaboré un poco mejor la documentación):
http://pastebin.com/92JEWwxV

El source original: https://github.com/varocarbas/snippets_chromaticEncryption_VB

Ejemplo de uso:
Código
  1. Public Class Form1
  2.  
  3.    ''' <summary>
  4.    ''' Instance of a Class containing most of the methods involving image-related actions,
  5.    ''' common to both encryption and decryption.
  6.    ''' </summary>
  7.    Dim curentIO As New IO
  8.  
  9.    Private Sub Test() Handles MyBase.Load
  10.  
  11.  
  12.        ' Encrypt text into image:
  13.        Dim Encrypt As New Encrypting(Color.Red, "Hello World!", curentIO, 0)
  14.        Dim EncryptedImage As Bitmap = Nothing
  15.  
  16.        Select Case Encrypt.errors
  17.  
  18.            Case False
  19.                ' Encrypts the text and returns the encrypted Bitmap.
  20.                EncryptedImage = curentIO.Encrypt(500, 500, Encrypt)
  21.  
  22.                ' Or encrypts the text and save it directlly in a image file.
  23.                Encrypt = curentIO.SaveImageFile("C:\File.png", 500, 500, Encrypt)
  24.  
  25.            Case True
  26.                MessageBox.Show(Encrypt.errorMessage, "There was an error while encrypting the text.")
  27.  
  28.        End Select
  29.  
  30.  
  31.        ' Decrypt image into text:
  32.        Dim Decrypt As New Decrypting(Color.Red, EncryptedImage, curentIO, 0)
  33.        ' Dim Decrypt As New Decrypting(Color.Red, Bitmap.FromFile("C:\File.png"), curentIO, 0)
  34.  
  35.        If Not Decrypt.errors Then
  36.            MsgBox(Decrypt.decryptedString)
  37.        Else
  38.            MessageBox.Show(Decrypt.errorMessage, "Either the input parameters or the image are wrong.")
  39.        End If
  40.  
  41.  
  42.    End Sub
  43.  
  44. End Class
« Última modificación: 5 Marzo 2014, 18:47 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #387 en: 5 Marzo 2014, 18:46 pm »

Convierte los caracteres diacríticos de un String.

Código
  1.    ' Convert Diacritics
  2.    '
  3.    ' Usage Examples:
  4.    ' MsgBox(RemoveDiacritics("áéíóú àèìòù äëïöü ñÑ çÇ", UnicodeNormalization:=System.Text.NormalizationForm.FormKD))
  5.    ' Result: 'aeiou aeiou aeiou nN cC'
  6.    '
  7.    ''' <summary>
  8.    ''' Converts the diacritic characters in a String to an equivalent normalized English characters.
  9.    ''' </summary>
  10.    ''' <param name="String">
  11.    ''' Indicates the string that contains diacritic characters.
  12.    ''' </param>
  13.    ''' <param name="UnicodeNormalization">
  14.    ''' Defines the type of Unicode character normalization to perform.
  15.    ''' (Default is 'NormalizationForm.FormKD')
  16.    ''' </param>
  17.    ''' <returns>System.String.</returns>
  18.    Public Function ConvertDiacritics(ByVal [String] As String,
  19.                                      Optional ByVal UnicodeNormalization As System.Text.NormalizationForm =
  20.                                                                             System.Text.NormalizationForm.FormKD) As String
  21.  
  22.        Dim Characters As String = String.Empty
  23.  
  24.        For Each c As Char In [String].Normalize(UnicodeNormalization)
  25.  
  26.            Select Case Globalization.CharUnicodeInfo.GetUnicodeCategory(c)
  27.  
  28.                Case Globalization.UnicodeCategory.NonSpacingMark,
  29.                     Globalization.UnicodeCategory.SpacingCombiningMark,
  30.                     Globalization.UnicodeCategory.EnclosingMark
  31.  
  32.                    ' Do nothing.
  33.                    Exit Select
  34.  
  35.                Case Else
  36.                    Characters &= CStr(c)
  37.  
  38.            End Select
  39.  
  40.        Next c
  41.  
  42.        Return Characters
  43.  
  44.    End Function
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #388 en: 6 Marzo 2014, 16:56 pm »

FileType Detective

Comprueba el tipo de un archivo específico examinando su cabecera.

(Tipo 'MediaInfo')

Código
  1. ' ***********************************************************************
  2. ' Author   : Original: http://filetypedetective.codeplex.com/
  3. '            Source translated, revised and extended by Elektro.
  4. '
  5. ' Modified : 03-06-2014
  6. ' ***********************************************************************
  7. ' <copyright file="FileTypeDetective.vb" company="Elektro Studios">
  8. '     Copyright (c) Elektro Studios. All rights reserved.
  9. ' </copyright>
  10. ' ***********************************************************************
  11.  
  12. #Region " Info "
  13.  
  14. ' file headers are taken from here:
  15. 'http://www.garykessler.net/library/file_sigs.html
  16.  
  17. ' mime types are taken from here:
  18. ' http://www.webmaster-toolkit.com/mime-types.shtml
  19.  
  20. #End Region
  21.  
  22. #Region " Usage Examples "
  23.  
  24. 'Imports FileTypeDetective
  25.  
  26. 'Public Class Form1
  27.  
  28. '    Private Sub Test() Handles MyBase.Load
  29.  
  30. '        MessageBox.Show(Detective.isType("C:\File.reg", FileType.REG)) ' NOTE: The regfile should be Unicode, not ANSI.
  31. '        MessageBox.Show(Detective.GetFileType("C:\File.reg").mime)
  32.  
  33. '    End Sub
  34.  
  35. 'End Class
  36.  
  37. #End Region
  38.  
  39. #Region " Imports "
  40.  
  41. Imports System.IO
  42. Imports FileTypeDetective.FileType
  43.  
  44. #End Region
  45.  
  46. #Region " FileType Detective "
  47.  
  48. ''' <summary>
  49. ''' Little data structure to hold information about file types.
  50. ''' Holds information about binary header at the start of the file
  51. ''' </summary>
  52. Public Class FileType
  53.  
  54.    ' MS Office files
  55.    Public Shared ReadOnly WORD As New FileType(
  56.        New Nullable(Of Byte)() {&HEC, &HA5, &HC1, &H0}, 512I, "doc", "application/msword")
  57.  
  58.    Public Shared ReadOnly EXCEL As New FileType(
  59.        New Nullable(Of Byte)() {&H9, &H8, &H10, &H0, &H0, &H6, &H5, &H0}, 512I, "xls", "application/excel")
  60.  
  61.    Public Shared ReadOnly PPT As New FileType(
  62.        New Nullable(Of Byte)() {&HFD, &HFF, &HFF, &HFF, Nothing, &H0, &H0, &H0}, 512I, "ppt", "application/mspowerpoint")
  63.  
  64.    ' common documents
  65.    Public Shared ReadOnly RTF As New FileType(
  66.        New Nullable(Of Byte)() {&H7B, &H5C, &H72, &H74, &H66, &H31}, "rtf", "application/rtf")
  67.  
  68.    Public Shared ReadOnly PDF As New FileType(
  69.        New Nullable(Of Byte)() {&H25, &H50, &H44, &H46}, "pdf", "application/pdf")
  70.  
  71.    Public Shared ReadOnly REG As New FileType(
  72.        New Nullable(Of Byte)() {&HFF, &HFE}, "reg", "text/plain")
  73.  
  74.    ' grafics
  75.    Public Shared ReadOnly JPEG As New FileType(
  76.        New Nullable(Of Byte)() {&HFF, &HD8, &HFF}, "jpg", "image/jpeg")
  77.  
  78.    Public Shared ReadOnly PNG As New FileType(
  79.        New Nullable(Of Byte)() {&H89, &H50, &H4E, &H47, &HD, &HA, &H1A, &HA}, "png", "image/png")
  80.  
  81.    Public Shared ReadOnly GIF As New FileType(
  82.        New Nullable(Of Byte)() {&H47, &H49, &H46, &H38, Nothing, &H61}, "gif", "image/gif")
  83.  
  84.    ' Compressed
  85.    Public Shared ReadOnly ZIP As New FileType(
  86.        New Nullable(Of Byte)() {&H50, &H4B, &H3, &H4}, "zip", "application/x-compressed")
  87.  
  88.    Public Shared ReadOnly RAR As New FileType(
  89.        New Nullable(Of Byte)() {&H52, &H61, &H72, &H21}, "rar", "application/x-compressed")
  90.  
  91.    ' all the file types to be put into one list
  92.    Friend Shared ReadOnly types As New List(Of FileType)() From { _
  93.        PDF,
  94.        WORD,
  95.        EXCEL,
  96.        JPEG,
  97.        ZIP,
  98.        RAR,
  99.        RTF,
  100.        PNG,
  101.        PPT,
  102.        GIF,
  103.        REG
  104.    }
  105.  
  106.    ' number of bytes we read from a file
  107.    Friend Const MaxHeaderSize As Integer = 560
  108.    ' some file formats have headers offset to 512 bytes
  109.  
  110.    ' most of the times we only need first 8 bytes, but sometimes extend for 16
  111.    Private m_header As Nullable(Of Byte)()
  112.    Public Property header() As Nullable(Of Byte)()
  113.        Get
  114.            Return m_header
  115.        End Get
  116.        Private Set(value As Nullable(Of Byte)())
  117.            m_header = value
  118.        End Set
  119.    End Property
  120.  
  121.    Private m_headerOffset As Integer
  122.    Public Property headerOffset() As Integer
  123.        Get
  124.            Return m_headerOffset
  125.        End Get
  126.        Private Set(value As Integer)
  127.            m_headerOffset = value
  128.        End Set
  129.    End Property
  130.  
  131.    Private m_extension As String
  132.    Public Property extension() As String
  133.        Get
  134.            Return m_extension
  135.        End Get
  136.        Private Set(value As String)
  137.            m_extension = value
  138.        End Set
  139.    End Property
  140.  
  141.    Private m_mime As String
  142.    Public Property mime() As String
  143.        Get
  144.            Return m_mime
  145.        End Get
  146.        Private Set(value As String)
  147.            m_mime = value
  148.        End Set
  149.    End Property
  150.  
  151. #Region " Constructors "
  152.  
  153.    ''' <summary>
  154.    ''' Initializes a new instance of the <see cref="FileType"/> class.
  155.    ''' Default construction with the header offset being set to zero by default
  156.    ''' </summary>
  157.    ''' <param name="header">Byte array with header.</param>
  158.    ''' <param name="extension">String with extension.</param>
  159.    ''' <param name="mime">The description of MIME.</param>
  160.    Public Sub New(header As Nullable(Of Byte)(), extension As String, mime As String)
  161.        Me.header = header
  162.        Me.extension = extension
  163.        Me.mime = mime
  164.        Me.headerOffset = 0
  165.    End Sub
  166.  
  167.    ''' <summary>
  168.    ''' Initializes a new instance of the <see cref="FileType"/> struct.
  169.    ''' Takes the details of offset for the header
  170.    ''' </summary>
  171.    ''' <param name="header">Byte array with header.</param>
  172.    ''' <param name="offset">The header offset - how far into the file we need to read the header</param>
  173.    ''' <param name="extension">String with extension.</param>
  174.    ''' <param name="mime">The description of MIME.</param>
  175.    Public Sub New(header As Nullable(Of Byte)(), offset As Integer, extension As String, mime As String)
  176.        Me.header = Nothing
  177.        Me.header = header
  178.        Me.headerOffset = offset
  179.        Me.extension = extension
  180.        Me.mime = mime
  181.    End Sub
  182.  
  183. #End Region
  184.  
  185.    Public Overrides Function Equals(other As Object) As Boolean
  186.  
  187.        If Not MyBase.Equals(other) Then
  188.            Return False
  189.        End If
  190.  
  191.        If Not (TypeOf other Is FileType) Then
  192.            Return False
  193.        End If
  194.  
  195.        Dim otherType As FileType = DirectCast(other, FileType)
  196.  
  197.        If Not Me.header Is otherType.header Then
  198.            Return False
  199.        End If
  200.  
  201.        If Me.headerOffset <> otherType.headerOffset Then
  202.            Return False
  203.        End If
  204.  
  205.        If Me.extension <> otherType.extension Then
  206.            Return False
  207.        End If
  208.  
  209.        If Me.mime <> otherType.mime Then
  210.            Return False
  211.        End If
  212.  
  213.        Return True
  214.  
  215.    End Function
  216.  
  217.    Public Overrides Function ToString() As String
  218.        Return extension
  219.    End Function
  220.  
  221. End Class
  222.  
  223. ''' <summary>
  224. ''' Helper class to identify file type by the file header, not file extension.
  225. ''' </summary>
  226. Public NotInheritable Class FileTypeDetective
  227.  
  228.    ''' <summary>
  229.    ''' Prevents a default instance of the <see cref="FileTypeDetective"/> class from being created.
  230.    ''' </summary>
  231.    Private Sub New()
  232.    End Sub
  233.  
  234. #Region "Main Methods"
  235.  
  236.    ''' <summary>
  237.    ''' Gets the list of FileTypes based on list of extensions in Comma-Separated-Values string
  238.    ''' </summary>
  239.    ''' <param name="CSV">The CSV String with extensions</param>
  240.    ''' <returns>List of FileTypes</returns>
  241.    Private Shared Function GetFileTypesByExtensions(CSV As String) As List(Of FileType)
  242.        Dim extensions As [String]() = CSV.ToUpper().Replace(" ", "").Split(","c)
  243.  
  244.        Dim result As New List(Of FileType)()
  245.  
  246.        For Each type As FileType In types
  247.            If extensions.Contains(type.extension.ToUpper()) Then
  248.                result.Add(type)
  249.            End If
  250.        Next
  251.        Return result
  252.    End Function
  253.  
  254.    ''' <summary>
  255.    ''' Reads the file header - first (16) bytes from the file
  256.    ''' </summary>
  257.    ''' <param name="file">The file to work with</param>
  258.    ''' <returns>Array of bytes</returns>
  259.    Private Shared Function ReadFileHeader(file As FileInfo, MaxHeaderSize As Integer) As [Byte]()
  260.        Dim header As [Byte]() = New Byte(MaxHeaderSize - 1) {}
  261.        Try
  262.            ' read file
  263.            Using fsSource As New FileStream(file.FullName, FileMode.Open, FileAccess.Read)
  264.                ' read first symbols from file into array of bytes.
  265.                fsSource.Read(header, 0, MaxHeaderSize)
  266.                ' close the file stream
  267.            End Using
  268.        Catch e As Exception
  269.            ' file could not be found/read
  270.            Throw New ApplicationException("Could not read file : " & e.Message)
  271.        End Try
  272.  
  273.        Return header
  274.    End Function
  275.  
  276.    ''' <summary>
  277.    ''' Read header of a file and depending on the information in the header
  278.    ''' return object FileType.
  279.    ''' Return null in case when the file type is not identified.
  280.    ''' Throws Application exception if the file can not be read or does not exist
  281.    ''' </summary>
  282.    ''' <param name="file">The FileInfo object.</param>
  283.    ''' <returns>FileType or null not identified</returns>
  284.    Public Shared Function GetFileType(file As FileInfo) As FileType
  285.        ' read first n-bytes from the file
  286.        Dim fileHeader As [Byte]() = ReadFileHeader(file, MaxHeaderSize)
  287.  
  288.        ' compare the file header to the stored file headers
  289.        For Each type As FileType In types
  290.            Dim matchingCount As Integer = 0
  291.            For i As Integer = 0 To type.header.Length - 1
  292.                ' if file offset is not set to zero, we need to take this into account when comparing.
  293.                ' if byte in type.header is set to null, means this byte is variable, ignore it
  294.                If type.header(i) IsNot Nothing AndAlso type.header(i) <> fileHeader(i + type.headerOffset) Then
  295.                    ' if one of the bytes does not match, move on to the next type
  296.                    matchingCount = 0
  297.                    Exit For
  298.                Else
  299.                    matchingCount += 1
  300.                End If
  301.            Next
  302.            If matchingCount = type.header.Length Then
  303.                ' if all the bytes match, return the type
  304.                Return type
  305.            End If
  306.        Next
  307.        ' if none of the types match, return null
  308.        Return Nothing
  309.    End Function
  310.  
  311.    ''' <summary>
  312.    ''' Read header of a file and depending on the information in the header
  313.    ''' return object FileType.
  314.    ''' Return null in case when the file type is not identified.
  315.    ''' Throws Application exception if the file can not be read or does not exist
  316.    ''' </summary>
  317.    ''' <param name="file">The FileInfo object.</param>
  318.    ''' <returns>FileType or null not identified</returns>
  319.    Public Shared Function GetFileType(file As String) As FileType
  320.        Return GetFileType(New FileInfo(file))
  321.    End Function
  322.  
  323.    ''' <summary>
  324.    ''' Determines whether provided file belongs to one of the provided list of files
  325.    ''' </summary>
  326.    ''' <param name="file">The file.</param>
  327.    ''' <param name="requiredTypes">The required types.</param>
  328.    ''' <returns>
  329.    '''   <c>true</c> if file of the one of the provided types; otherwise, <c>false</c>.
  330.    ''' </returns>
  331.    Public Shared Function isFileOfTypes(file As FileInfo, requiredTypes As List(Of FileType)) As Boolean
  332.  
  333.        Dim currentType As FileType = GetFileType(file)
  334.  
  335.        If currentType Is Nothing Then
  336.            Return False
  337.        End If
  338.  
  339.        Return requiredTypes.Contains(currentType)
  340.  
  341.    End Function
  342.  
  343.    ''' <summary>
  344.    ''' Determines whether provided file belongs to one of the provided list of files,
  345.    ''' where list of files provided by string with Comma-Separated-Values of extensions
  346.    ''' </summary>
  347.    ''' <param name="file">The file.</param>
  348.    ''' <returns>
  349.    '''   <c>true</c> if file of the one of the provided types; otherwise, <c>false</c>.
  350.    ''' </returns>
  351.    Public Shared Function isFileOfTypes(file As FileInfo, CSV As String) As Boolean
  352.  
  353.        Dim providedTypes As List(Of FileType) = GetFileTypesByExtensions(CSV)
  354.  
  355.        Return isFileOfTypes(file, providedTypes)
  356.  
  357.    End Function
  358.  
  359. #End Region
  360.  
  361. #Region "isType functions"
  362.  
  363.    ''' <summary>
  364.    ''' Determines whether the specified file is of provided type
  365.    ''' </summary>
  366.    ''' <param name="file">The file.</param>
  367.    ''' <param name="type">The FileType</param>
  368.    ''' <returns>
  369.    '''   <c>true</c> if the specified file is type; otherwise, <c>false</c>.
  370.    ''' </returns>
  371.    Public Shared Function isType(file As FileInfo, type As FileType) As Boolean
  372.  
  373.        Dim actualType As FileType = GetFileType(file)
  374.  
  375.        If actualType Is Nothing Then
  376.            Return False
  377.        End If
  378.  
  379.        Return (actualType.Equals(type))
  380.  
  381.    End Function
  382.  
  383.    ''' <summary>
  384.    ''' Determines whether the specified file is of provided type
  385.    ''' </summary>
  386.    ''' <param name="file">The file.</param>
  387.    ''' <param name="type">The FileType</param>
  388.    ''' <returns>
  389.    '''   <c>true</c> if the specified file is type; otherwise, <c>false</c>.
  390.    ''' </returns>
  391.    Public Shared Function isType(file As String, type As FileType) As Boolean
  392.  
  393.        Return isType(New FileInfo(file), type)
  394.  
  395.    End Function
  396.  
  397. #End Region
  398.  
  399. End Class
  400.  
  401. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #389 en: 7 Marzo 2014, 19:52 pm »

Algunos métodos de uso genérico sobre las cuentas de usuario.




Código
  1.    ' Get UserNames
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' Dim UserNames As String() = GetUserNames()
  10.    '
  11.    ''' <summary>
  12.    ''' Get the username accounts of the current machine.
  13.    ''' </summary>
  14.    ''' <returns>System.String[][].</returns>
  15.    Public Function GetUserNames() As String()
  16.  
  17.        Dim pContext As New PrincipalContext(ContextType.Machine)
  18.        Dim pUser As New UserPrincipal(pContext)
  19.        Dim pSearcher As New PrincipalSearcher(pUser)
  20.        Dim UserNames As String() = (From u As Principal In pSearcher.FindAll Select u.Name).ToArray
  21.  
  22.        pContext.Dispose()
  23.        pSearcher.Dispose()
  24.        pUser.Dispose()
  25.  
  26.        Return UserNames
  27.  
  28.    End Function



Código
  1.    ' Get Users
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' Dim Users As Principal() = GetUsers()
  10.    ' For Each User As Principal In Users()
  11.    '     MsgBox(User.Name)
  12.    ' Next
  13.    '
  14.    ''' <summary>
  15.    ''' Get the users of the current machine.
  16.    ''' </summary>
  17.    ''' <returns>Principal[][].</returns>
  18.    Public Function GetUsers() As Principal()
  19.  
  20.        Dim pContext As New PrincipalContext(ContextType.Machine)
  21.        Dim pUser As New UserPrincipal(pContext)
  22.        Dim pSearcher As New PrincipalSearcher(pUser)
  23.        Dim Users As Principal() = (From User As Principal In pSearcher.FindAll).ToArray
  24.  
  25.        Return Users
  26.  
  27.    End Function



Código
  1.   ' Delete User Account
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' DeleteUserAccount("Username")
  10.    ' DeleteUserAccount(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"))
  11.    '
  12.    ''' <summary>
  13.    ''' Deletes an existing user account in the current machine.
  14.    ''' </summary>
  15.    ''' <param name="UserName">Indicates the account Username.</param>
  16.    ''' <returns><c>true</c> if deletion success, <c>false</c> otherwise.</returns>
  17.    Public Function DeleteUserAccount(ByVal UserName As String) As Boolean
  18.  
  19.        Dim pContext As New PrincipalContext(ContextType.Machine)
  20.        Dim pUser As New UserPrincipal(pContext)
  21.        Dim pSearcher As New PrincipalSearcher(pUser)
  22.  
  23.        Dim User As Principal =
  24.            (From u As Principal In pSearcher.FindAll
  25.            Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  26.  
  27.        If User Is Nothing Then
  28.            Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
  29.        End If
  30.  
  31.        Try
  32.            User.Delete()
  33.            Return True
  34.  
  35.        Catch ex As InvalidOperationException
  36.            Throw New Exception(ex.Message)
  37.  
  38.        Finally
  39.            pContext.Dispose()
  40.            pSearcher.Dispose()
  41.            pUser.Dispose()
  42.  
  43.        End Try
  44.  
  45.        Return False ' Failed.
  46.  
  47.    End Function

Código
  1.    ''' <summary>
  2.    ''' Deletes an existing user account in the current machine.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the account security identifier (SID).</param>
  5.    ''' <returns><c>true</c> if deletion success, <c>false</c> otherwise.</returns>
  6.    Public Function DeleteUserAccount(ByVal UserSID As Security.Principal.SecurityIdentifier) As Boolean
  7.  
  8.        Dim pContext As New PrincipalContext(ContextType.Machine)
  9.        Dim pUser As New UserPrincipal(pContext)
  10.        Dim pSearcher As New PrincipalSearcher(pUser)
  11.  
  12.        Dim User As Principal =
  13.            (From u As Principal In pSearcher.FindAll
  14.            Where u.Sid = UserSID).FirstOrDefault
  15.  
  16.        If User Is Nothing Then
  17.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  18.        End If
  19.  
  20.        Try
  21.            User.Delete()
  22.            Return True
  23.  
  24.        Catch ex As InvalidOperationException
  25.            Throw New Exception(ex.Message)
  26.  
  27.        Finally
  28.            pContext.Dispose()
  29.            pSearcher.Dispose()
  30.            pUser.Dispose()
  31.  
  32.        End Try
  33.  
  34.        Return False ' Failed.
  35.  
  36.    End Function



Código
  1.    ' User Is Admin?
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' MsgBox(UserIsAdmin("Administrador"))
  10.    ' MsgBox(UserIsAdmin(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500")))
  11.    '
  12.    ''' <summary>
  13.    ''' Determines whether an User is an Administrator.
  14.    ''' </summary>
  15.    ''' <param name="UserName">Indicates the account Username.</param>
  16.    ''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
  17.    Public Function UserIsAdmin(ByVal UserName As String) As Boolean
  18.  
  19.        Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")
  20.  
  21.        Dim pContext As New PrincipalContext(ContextType.Machine)
  22.        Dim pUser As New UserPrincipal(pContext)
  23.        Dim pSearcher As New PrincipalSearcher(pUser)
  24.  
  25.        Dim User As Principal =
  26.            (From u As Principal In pSearcher.FindAll
  27.            Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  28.  
  29.        If User Is Nothing Then
  30.            Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
  31.        End If
  32.  
  33.        Dim IsAdmin As Boolean =
  34.            (From Group As GroupPrincipal In User.GetGroups
  35.             Where Group.Sid = AdminGroupSID).Any
  36.  
  37.        pContext.Dispose()
  38.        pSearcher.Dispose()
  39.        pUser.Dispose()
  40.  
  41.        Return IsAdmin
  42.  
  43.    End Function

Código
  1.    ''' <summary>
  2.    ''' Determines whether an User is an Administrator.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the SID of the user account.</param>
  5.    ''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
  6.    Public Function UserIsAdmin(ByVal UserSID As Security.Principal.SecurityIdentifier) As Boolean
  7.  
  8.        Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")
  9.  
  10.        Dim pContext As New PrincipalContext(ContextType.Machine)
  11.        Dim pUser As New UserPrincipal(pContext)
  12.        Dim pSearcher As New PrincipalSearcher(pUser)
  13.  
  14.        Dim User As Principal =
  15.            (From u As Principal In pSearcher.FindAll
  16.            Where u.Sid = UserSID).FirstOrDefault
  17.  
  18.        If User Is Nothing Then
  19.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  20.        End If
  21.  
  22.        Dim IsAdmin As Boolean =
  23.            (From Group As GroupPrincipal In User.GetGroups
  24.             Where Group.Sid = AdminGroupSID).Any
  25.  
  26.        pContext.Dispose()
  27.        pSearcher.Dispose()
  28.        pUser.Dispose()
  29.  
  30.        Return IsAdmin
  31.  
  32.    End Function



Código
  1.   ' Set UserName
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' SetUserName("Username", "New Name")
  10.    ' SetUserName(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"), "New Name")
  11.    '
  12.    ''' <summary>
  13.    ''' Sets the UserName of an existing User account.
  14.    ''' </summary>
  15.    ''' <param name="OldUserName">Indicates an existing username account.</param>
  16.    ''' <param name="NewUserName">Indicates the new name for the user account.</param>
  17.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  18.    Public Function SetUserName(ByVal OldUserName As String,
  19.                                ByVal NewUserName As String) As Boolean
  20.  
  21.        Dim pContext As New PrincipalContext(ContextType.Machine)
  22.        Dim pUser As New UserPrincipal(pContext)
  23.        Dim pSearcher As New PrincipalSearcher(pUser)
  24.  
  25.        Dim User As Principal =
  26.            (From u As Principal In pSearcher.FindAll
  27.            Where u.Name.Equals(OldUserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  28.  
  29.        If User Is Nothing Then
  30.            Throw New Exception(String.Format("User with name '{0}' not found.", OldUserName))
  31.        End If
  32.  
  33.        Try
  34.            User.Name = NewUserName
  35.            User.Save()
  36.            Return True
  37.  
  38.        Catch ex As InvalidOperationException
  39.            Throw New Exception(ex.Message)
  40.  
  41.        Finally
  42.            pContext.Dispose()
  43.            pSearcher.Dispose()
  44.            pUser.Dispose()
  45.  
  46.        End Try
  47.  
  48.        Return False ' Failed.
  49.  
  50.    End Function

Código
  1.    ''' <summary>
  2.    ''' Sets the UserName of an existing User account.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the SID of the user account.</param>
  5.    ''' <param name="NewUserName">Indicates the new name for the user account.</param>
  6.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  7.    Public Function SetUserName(ByVal UserSID As Security.Principal.SecurityIdentifier,
  8.                                ByVal NewUserName As String) As Boolean
  9.  
  10.        Dim pContext As New PrincipalContext(ContextType.Machine)
  11.        Dim pUser As New UserPrincipal(pContext)
  12.        Dim pSearcher As New PrincipalSearcher(pUser)
  13.  
  14.        Dim User As Principal =
  15.            (From u As Principal In pSearcher.FindAll
  16.            Where u.Sid = UserSID).FirstOrDefault
  17.  
  18.        If User Is Nothing Then
  19.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  20.        End If
  21.  
  22.        Try
  23.            User.Name = NewUserName
  24.            User.Save()
  25.            Return True
  26.  
  27.        Catch ex As InvalidOperationException
  28.            Throw New Exception(ex.Message)
  29.  
  30.        Finally
  31.            pContext.Dispose()
  32.            pSearcher.Dispose()
  33.            pUser.Dispose()
  34.  
  35.        End Try
  36.  
  37.        Return False ' Failed.
  38.  
  39.    End Function
  40.  


Código
  1.   ' Set Account DisplayName
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' SetAccountDisplayName("Username", "New Name")
  10.    ' SetAccountDisplayName(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"), "New Name")
  11.    '
  12.    ''' <summary>
  13.    ''' Sets the display name of an existing User account.
  14.    ''' </summary>
  15.    ''' <param name="OldDisplayName">Indicates an existing display name user account.</param>
  16.    ''' <param name="NewDisplayName">Indicates the new display name for the user account.</param>
  17.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  18.    Public Function SetAccountDisplayName(ByVal OldDisplayName As String,
  19.                                          ByVal NewDisplayName As String) As Boolean
  20.  
  21.        Dim pContext As New PrincipalContext(ContextType.Machine)
  22.        Dim pUser As New UserPrincipal(pContext)
  23.        Dim pSearcher As New PrincipalSearcher(pUser)
  24.  
  25.        Dim User As Principal =
  26.            (From u As Principal In pSearcher.FindAll
  27.            Where u.Name.Equals(OldDisplayName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  28.  
  29.        If User Is Nothing Then
  30.            Throw New Exception(String.Format("User with display name '{0}' not found.", OldDisplayName))
  31.        End If
  32.  
  33.        Try
  34.            User.DisplayName = NewDisplayName
  35.            User.Save()
  36.            Return True
  37.  
  38.        Catch ex As InvalidOperationException
  39.            Throw New Exception(ex.Message)
  40.  
  41.        Finally
  42.            pContext.Dispose()
  43.            pSearcher.Dispose()
  44.            pUser.Dispose()
  45.  
  46.        End Try
  47.  
  48.        Return False ' Failed.
  49.  
  50.    End Function

Código
  1.    ''' <summary>
  2.    ''' Sets the display name of an existing User account.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the SID of the user account.</param>
  5.    ''' <param name="NewDisplayName">Indicates the new display name for the user account.</param>
  6.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  7.    Public Function SetAccountDisplayName(ByVal UserSID As Security.Principal.SecurityIdentifier,
  8.                                          ByVal NewDisplayName As String) As Boolean
  9.  
  10.        Dim pContext As New PrincipalContext(ContextType.Machine)
  11.        Dim pUser As New UserPrincipal(pContext)
  12.        Dim pSearcher As New PrincipalSearcher(pUser)
  13.  
  14.        Dim User As Principal =
  15.            (From u As Principal In pSearcher.FindAll
  16.            Where u.Sid = UserSID).FirstOrDefault
  17.  
  18.        If User Is Nothing Then
  19.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  20.        End If
  21.  
  22.        Try
  23.            User.DisplayName = NewDisplayName
  24.            User.Save()
  25.            Return True
  26.  
  27.        Catch ex As InvalidOperationException
  28.            Throw New Exception(ex.Message)
  29.  
  30.        Finally
  31.            pContext.Dispose()
  32.            pSearcher.Dispose()
  33.            pUser.Dispose()
  34.  
  35.        End Try
  36.  
  37.        Return False ' Failed.
  38.  
  39.    End Function
En línea

Páginas: 1 ... 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 [39] 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 ... 58 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines