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

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


+  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 ... 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 [49] 50 51 52 53 54 55 56 57 58 59 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 532,617 veces)
josnan

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #480 en: 3 Septiembre 2015, 21:57 pm »

Me gustaria probar esos snippets pero el enlace no funciona.


En línea

josnan

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #481 en: 6 Septiembre 2015, 22:50 pm »

Ya lo consegui de otro enlace.


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #482 en: 6 Septiembre 2015, 23:00 pm »

@josnan

Se me olvidó responder a la petición que hiciste, la leí el otro día pero se me pasó contestarte, lo siento.

actualmente los snippets los estoy "reconstruyendo", refactorizando, reordenando, actualizándolos, etc, prefiero no publicarlos todavía, pero te los pasaré en breve por privado.

Gracias por tu interés, y perdona el pequeño olvido.

Saludos
En línea



josnan

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #483 en: 9 Septiembre 2015, 21:03 pm »

Gracias, se aprende mucho con estos ejemplos.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #484 en: 19 Septiembre 2015, 09:01 am »

Despues de un tiempo sin actualizar, volvemos a la carga con un par de snippets.



Ejemplo de uso de la librería CodeScales:
http://www.codescales.com/

Es un simple, muy simple cliente http que encapsula el código/miembros necesarios de la librería de classes de .Net para realizar peticiones Post con MultiPart, y otras, de forma muy sencilla:

Código
  1.  
  2.        ' *********************
  3.        ' Get Method
  4.        ' http://www.google.com
  5.        ' *********************
  6.        '
  7.        ' Dim client As New HttpClient
  8.        ' Dim getMethod As New HttpGet(New Uri("http://www.google.com/search"))
  9.        '
  10.        ' With getMethod
  11.        '     .Parameters.Add("q", "Hello")
  12.        '     .Parameters.Add("lr", "lang_en")
  13.        ' End With
  14.        '
  15.        ' Dim response As HttpResponse = client.Execute(getMethod)
  16.        ' Dim text As String = EntityUtils.ToString(response.Entity)
  17.  
  18.  
  19.  
  20.        ' **************************
  21.        ' Post Method with MultiPart
  22.        ' http://9kw.eu/
  23.        ' **************************
  24.        '
  25.        ' Dim apiKey As String = "XXXXXXXXXXXX"
  26.        ' Dim filepath As String = "C:\File.png"
  27.        '
  28.        ' Dim client As New HttpClient
  29.        ' Dim postMethod As New HttpPost(New Uri("http://www.9kw.eu/index.cgi"))
  30.        '
  31.        ' Dim multipartEntity As New MultipartEntity
  32.        ' postMethod.Entity = multipartEntity
  33.        '
  34.        ' With multipartEntity
  35.        '     .AddBody(New StringBody(Encoding.UTF8, "apikey", apiKey))
  36.        '     .AddBody(New StringBody(Encoding.UTF8, "action", "usercaptchaupload"))
  37.        '     .AddBody(New StringBody(Encoding.UTF8, "source", "vbapi"))
  38.        ' End With
  39.        '
  40.        ' Dim fileBody As New FileBody("file-upload-01", filepath, New IO.FileInfo(filepath))
  41.        ' multipartEntity.AddBody(fileBody)
  42.        '
  43.        ' Dim response As HttpResponse = client.Execute(postMethod)
  44.        ' Dim text As String = EntityUtils.ToString(response.Entity)
  45.  



9KW Captcha Helper
http://9kw.eu/
(veanse otros ejemplos de uso en el apartado de la API en la página oficial)

Es una class para utilizar el servicio de solución de captchas de 9KW. Este servicio es de pago, se necesita una API key para podr utilizarlo.

Por el momento cumple las dos labores más esenciales, la función GetCredits devuelve los créditos actuales del usuario, y el método SolveCaptcha soluciona el captcha especificado.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 18-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="KWCaptchaHelper.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " Properties "
  13.  
  14. ' KWCaptchaHelper.ApiKey As String
  15.  
  16. #End Region
  17.  
  18. #Region " Functions "
  19.  
  20. ' KWCaptchaHelper.GetCredits As String
  21.  
  22. #End Region
  23.  
  24. #Region " Methods "
  25.  
  26. ' KWCaptchaHelper.SolveCaptcha(String)
  27.  
  28. #End Region
  29.  
  30. #End Region
  31.  
  32. #Region " Usage Examples "
  33.  
  34. ' Dim captchaSolver As New KWCaptchaHelper(apiKey:="XXXXXXXXXXXXXXXXXXX")
  35. ' Dim imagePath As String = "C:\captcha.png"
  36. ' Dim result As String = String.Empty
  37.  
  38. ' Console.WriteLine(String.Format("User Credits: {0}", captchaSolver.GetCredits()))
  39. ' Console.WriteLine(String.Format("Captcha Img.: {0}", imagePath))
  40.  
  41. ' Console.WriteLine("Solving Captcha, please wait...")
  42. ' result = captchaSolver.SolveCaptcha(imagePath)
  43. ' Console.WriteLine(String.Format("Result: {0}", result))
  44.  
  45. 'Console.ReadKey()
  46.  
  47. #End Region
  48.  
  49. #Region " Imports "
  50.  
  51. Imports CodeScales.Http
  52. Imports CodeScales.Http.Entity
  53. Imports CodeScales.Http.Methods
  54. Imports CodeScales.Http.Entity.Mime
  55.  
  56. Imports System
  57. Imports System.IO
  58. Imports System.Linq
  59. Imports System.Text
  60. Imports System.Threading
  61.  
  62. #End Region
  63.  
  64. #Region " KWCaptchaHelper "
  65.  
  66. ''' ----------------------------------------------------------------------------------------------------
  67. ''' <summary>
  68. ''' 9KW Captcha service. Helper Class.
  69. ''' </summary>
  70. ''' ----------------------------------------------------------------------------------------------------
  71. ''' <remarks>
  72. ''' Visit <see href="http://9kw.eu/"/> for further info.
  73. ''' </remarks>
  74. ''' ----------------------------------------------------------------------------------------------------
  75. Public NotInheritable Class KWCaptchaHelper
  76.  
  77. #Region " Properties "
  78.  
  79.    ''' ----------------------------------------------------------------------------------------------------
  80.    ''' <summary>
  81.    ''' Gets the 9KW's API user key.
  82.    ''' </summary>
  83.    ''' ----------------------------------------------------------------------------------------------------
  84.    ''' <value>
  85.    ''' The 9KW's API user key.
  86.    ''' </value>
  87.    ''' ----------------------------------------------------------------------------------------------------
  88.    Public ReadOnly Property ApiKey As String
  89.        Get
  90.            Return Me.apiKeyB
  91.        End Get
  92.    End Property
  93.    ''' ----------------------------------------------------------------------------------------------------
  94.    ''' <summary>
  95.    ''' ( Backing field )
  96.    ''' The 9KW's API user key.
  97.    ''' </summary>
  98.    ''' ----------------------------------------------------------------------------------------------------
  99.    Private ReadOnly apiKeyB As String
  100.  
  101. #End Region
  102.  
  103. #Region " Constructors "
  104.  
  105.    ''' ----------------------------------------------------------------------------------------------------
  106.    ''' <summary>
  107.    ''' Initializes a new instance of the <see cref="KWCaptchaHelper"/> class.
  108.    ''' </summary>
  109.    ''' ----------------------------------------------------------------------------------------------------
  110.    ''' <param name="apiKey">
  111.    ''' The 9KW's API user key.
  112.    ''' </param>
  113.    ''' ----------------------------------------------------------------------------------------------------
  114.    Public Sub New(ByVal apiKey As String)
  115.  
  116.        Me.apiKeyB = apiKey
  117.  
  118.    End Sub
  119.  
  120.    ''' ----------------------------------------------------------------------------------------------------
  121.    ''' <summary>
  122.    ''' Prevents a default instance of the <see cref="KWCaptchaHelper"/> class from being created.
  123.    ''' </summary>
  124.    ''' ----------------------------------------------------------------------------------------------------
  125.    Private Sub New()
  126.    End Sub
  127.  
  128. #End Region
  129.  
  130. #Region " Private Methods "
  131.  
  132.    ''' ----------------------------------------------------------------------------------------------------
  133.    ''' <summary>
  134.    ''' </summary>
  135.    ''' ----------------------------------------------------------------------------------------------------
  136.    ''' <param name="data">
  137.    ''' The data.
  138.    ''' </param>
  139.    ''' ----------------------------------------------------------------------------------------------------
  140.    ''' <returns>
  141.    ''' System.String.
  142.    ''' </returns>
  143.    ''' ----------------------------------------------------------------------------------------------------
  144.    Private Function Get9kwApi(ByVal data As String) As String
  145.  
  146.        Return Me.Get9kwHttp(String.Format("http://www.9kw.eu/index.cgi?source=vbapi&debug=0&apikey={0}&action=" & data, Me.apiKeyB))
  147.  
  148.    End Function
  149.  
  150.    ''' ----------------------------------------------------------------------------------------------------
  151.    ''' <summary>
  152.    ''' </summary>
  153.    ''' ----------------------------------------------------------------------------------------------------
  154.    ''' <param name="url">
  155.    ''' The URL.
  156.    ''' </param>
  157.    ''' ----------------------------------------------------------------------------------------------------
  158.    ''' <returns>
  159.    ''' System.String.
  160.    ''' </returns>
  161.    ''' ----------------------------------------------------------------------------------------------------
  162.    Private Function Get9kwHttp(ByVal url As String) As String
  163.  
  164.        Dim httpClient As New HttpClient
  165.        Dim httpGet As New HttpGet(New Uri(url))
  166.        Dim httpResponse As HttpResponse = httpClient.Execute(httpGet)
  167.  
  168.        Return EntityUtils.ToString(httpResponse.Entity)
  169.  
  170.    End Function
  171.  
  172.    ''' ----------------------------------------------------------------------------------------------------
  173.    ''' <summary>
  174.    ''' </summary>
  175.    ''' ----------------------------------------------------------------------------------------------------
  176.    ''' <param name="data">
  177.    ''' The data.
  178.    ''' </param>
  179.    ''' ----------------------------------------------------------------------------------------------------
  180.    ''' <returns>
  181.    ''' System.String.
  182.    ''' </returns>
  183.    ''' ----------------------------------------------------------------------------------------------------
  184.    Private Function Get9kwApiUpload(ByVal data As String) As String
  185.  
  186.        Dim client As New HttpClient
  187.        Dim postMethod As New HttpPost(New Uri("http://www.9kw.eu/index.cgi"))
  188.  
  189.        Dim multipartEntity As New MultipartEntity
  190.        postMethod.Entity = multipartEntity
  191.  
  192.        Dim stringBody As New StringBody(Encoding.UTF8, "apikey", Me.apiKeyB)
  193.        multipartEntity.AddBody(stringBody)
  194.  
  195.        Dim stringBody3 As New StringBody(Encoding.UTF8, "source", "vbapi")
  196.        multipartEntity.AddBody(stringBody3)
  197.  
  198.        Dim stringBody2 As New StringBody(Encoding.UTF8, "action", "usercaptchaupload")
  199.        multipartEntity.AddBody(stringBody2)
  200.  
  201.        Dim fileInfo As New FileInfo(data)
  202.        Dim fileBody As New FileBody("file-upload-01", data, fileInfo)
  203.        multipartEntity.AddBody(fileBody)
  204.  
  205.        Dim response As HttpResponse = client.Execute(postMethod)
  206.        Return EntityUtils.ToString(response.Entity)
  207.  
  208.    End Function
  209.  
  210. #End Region
  211.  
  212. #Region " Public Methods "
  213.  
  214.    ''' ----------------------------------------------------------------------------------------------------
  215.    ''' <summary>
  216.    ''' Gets the current remaining credits.
  217.    ''' </summary>
  218.    ''' ----------------------------------------------------------------------------------------------------
  219.    ''' <returns>
  220.    ''' The current remaining credits.
  221.    ''' </returns>
  222.    ''' ----------------------------------------------------------------------------------------------------
  223.    Public Function GetCredits() As String
  224.  
  225.        Return Me.Get9kwApi("usercaptchaguthaben")
  226.  
  227.    End Function
  228.  
  229.    ''' ----------------------------------------------------------------------------------------------------
  230.    ''' <summary>
  231.    ''' Solves the specified captcha image.
  232.    ''' </summary>
  233.    ''' ----------------------------------------------------------------------------------------------------
  234.    ''' <param name="imagePath">
  235.    ''' The image path.
  236.    ''' </param>
  237.    '''
  238.    ''' <param name="checkInterval">
  239.    ''' The interval to check whether the captcha is solved.
  240.    ''' </param>
  241.    '''
  242.    ''' <param name="totalTries">
  243.    ''' The total intents. ( <paramref name="totalTries"/> * <paramref name="checkInterval"/> ).
  244.    ''' </param>
  245.    ''' ----------------------------------------------------------------------------------------------------
  246.    ''' <returns>
  247.    ''' The solved text.
  248.    ''' </returns>
  249.    ''' ----------------------------------------------------------------------------------------------------
  250.    Public Function SolveCaptcha(ByVal imagePath As String,
  251.                                 Optional ByVal checkInterval As Integer = 2000,
  252.                                 Optional ByVal totalTries As Integer = 100) As String
  253.  
  254.        Dim newCaptchaID As String = Me.Get9kwApiUpload(imagePath)
  255.        Dim checkdata As String = String.Empty
  256.        Dim counter As Integer = 0
  257.  
  258.        Do Until Not String.IsNullOrEmpty(checkdata)
  259.  
  260.            If Interlocked.Increment(counter) = totalTries Then
  261.                Exit Do
  262.            Else
  263.                Thread.Sleep(checkInterval)
  264.            End If
  265.  
  266.            checkdata = Me.Get9kwApi("usercaptchacorrectdata&id=" & newCaptchaID)
  267.  
  268.        Loop
  269.  
  270.        Return checkdata
  271.  
  272.    End Function
  273.  
  274. #End Region
  275.  
  276. End Class
  277.  
  278. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #485 en: 19 Septiembre 2015, 09:11 am »

AppConfigUtil, es una class que expone un simple parser de uso genérico para comprovar el valor de una propiedad declarada en la configuración de aplicación (appconfig), el cual no he optimizado para los tipos de estructura del árbol de nodos del appconfig ...podría ser ineficiente en ciertos escenarios, pero es un comienzo.

Por ejemplo, para saber si los contadores de rendimientos están activados en el appconfig de una aplicación .Net, lo podriamos utilizar de la siguiente manera:

Código
  1. Dim isPerfCountersEnabled As boolean = GetAppConfigSetting(Of Boolean)("system.net", "settings", "performanceCounters", "enabled")

O utilizar el método IsPerformanceCountersEnabled definido expresamente para esa labor.

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 18-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="AppConfigUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " Functions "
  13.  
  14. ' GetAppConfigSetting(Of T)(String, String, String, String, Optional:String) As T
  15. ' GetAppConfigSetting(Of T)(String, String, String, String) As T
  16. ' IsPerformanceCountersEnabled(Optional:String) As Boolean
  17.  
  18. #End Region
  19.  
  20. #End Region
  21.  
  22. #Region " Option Statements "
  23.  
  24. Option Strict On
  25. Option Explicit On
  26. Option Infer Off
  27.  
  28. #End Region
  29.  
  30. #Region " Imports "
  31.  
  32. Imports System
  33. Imports System.Configuration
  34. Imports System.Linq
  35. Imports System.Net.Configuration
  36.  
  37. #End Region
  38.  
  39. #Region " AppConfig Util "
  40.  
  41. ''' ----------------------------------------------------------------------------------------------------
  42. ''' <summary>
  43. ''' Contains related AppConfig utilities.
  44. ''' </summary>
  45. ''' ----------------------------------------------------------------------------------------------------
  46. Public NotInheritable Class AppConfigUtil
  47.  
  48. #Region " Public Methods "
  49.  
  50.    ''' ----------------------------------------------------------------------------------------------------
  51.    ''' <summary>
  52.    ''' Gets the value of a setting declared in the application configuration file (app.config)
  53.    ''' of the specified application.
  54.    ''' </summary>
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    ''' <example> This is a code example.
  57.    ''' <code>
  58.    ''' Dim isPerfCountersEnabled As boolean = GetAppConfigSetting(Of Boolean)("system.net", "settings", "performanceCounters", "enabled")
  59.    ''' </code>
  60.    ''' </example>
  61.    ''' ----------------------------------------------------------------------------------------------------
  62.    ''' <typeparam name="T">
  63.    ''' </typeparam>
  64.    '''
  65.    ''' <param name="sectionGroupName">
  66.    ''' The name of the section group.
  67.    ''' </param>
  68.    '''
  69.    ''' <param name="sectionName">
  70.    ''' The name of the section.
  71.    ''' </param>
  72.    '''
  73.    ''' <param name="elementName">
  74.    ''' The name of the element.
  75.    ''' </param>
  76.    '''
  77.    ''' <param name="propertyName">
  78.    ''' The name of the property.
  79.    ''' </param>
  80.    '''
  81.    ''' <param name="exePath">
  82.    ''' The executable path of the current or an external .Net application.
  83.    ''' If any path is specified, it assumes the current application.
  84.    ''' </param>
  85.    ''' ----------------------------------------------------------------------------------------------------
  86.    ''' <returns>
  87.    ''' If the SectionGroup, the Section, the Element, or the Property doesn't exist, the return value is <see langword="Nothing"/>,
  88.    ''' otherwise, the value.
  89.    ''' </returns>
  90.    ''' ----------------------------------------------------------------------------------------------------
  91.    <DebuggerStepThrough>
  92.    <DebuggerHidden>
  93.    Public Shared Function GetAppConfigSetting(Of T)(ByVal sectionGroupName As String,
  94.                                                     ByVal sectionName As String,
  95.                                                     ByVal elementName As String,
  96.                                                     ByVal propertyName As String,
  97.                                                     Optional ByVal exePath As String = "") As T
  98.  
  99.        Dim appConfig As Configuration
  100.        Dim group As ConfigurationSectionGroup
  101.        Dim section As ConfigurationSection
  102.        Dim sectionPropInfo As PropertyInformation
  103.        Dim element As ConfigurationElement
  104.        Dim elementPropInfo As PropertyInformation
  105.  
  106.        If Not String.IsNullOrEmpty(exePath) Then
  107.            appConfig = ConfigurationManager.OpenExeConfiguration(exePath)
  108.        Else
  109.            appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  110.        End If
  111.  
  112.        group = appConfig.GetSectionGroup(sectionGroupName)
  113.        If group Is Nothing Then
  114.            Return Nothing
  115.        End If
  116.  
  117.        section = group.Sections(sectionName)
  118.        If section Is Nothing Then
  119.            Return Nothing
  120.        End If
  121.  
  122.        sectionPropInfo = section.ElementInformation.Properties(elementName)
  123.        If sectionPropInfo Is Nothing Then
  124.            Return Nothing
  125.        End If
  126.  
  127.        element = DirectCast(sectionPropInfo.Value, ConfigurationElement)
  128.        If element Is Nothing Then
  129.            Return Nothing
  130.        End If
  131.  
  132.        elementPropInfo = element.ElementInformation.Properties(propertyName)
  133.        If elementPropInfo Is Nothing Then
  134.            Return Nothing
  135.        End If
  136.  
  137.        Return DirectCast(elementPropInfo.Value, T)
  138.  
  139.    End Function
  140.  
  141.    ''' ----------------------------------------------------------------------------------------------------
  142.    ''' <summary>
  143.    ''' Gets the value of a setting declared in the application configuration file (app.config)
  144.    ''' of the specified application.
  145.    ''' </summary>
  146.    ''' ----------------------------------------------------------------------------------------------------
  147.    ''' <typeparam name="T">
  148.    ''' </typeparam>
  149.    '''
  150.    ''' <param name="sectionName">
  151.    ''' The name of the section.
  152.    ''' </param>
  153.    '''
  154.    ''' <param name="elementName">
  155.    ''' The name of the element.
  156.    ''' </param>
  157.    '''
  158.    ''' <param name="propertyName">
  159.    ''' The name of the property.
  160.    ''' </param>
  161.    '''
  162.    ''' <param name="exePath">
  163.    ''' The executable path of the current or an external .Net application.
  164.    ''' If any path is specified, it assumes the current application.
  165.    ''' </param>
  166.    ''' ----------------------------------------------------------------------------------------------------
  167.    ''' <returns>
  168.    ''' If the Section, the Element, or the Property doesn't exist, the return value is <see langword="Nothing"/>,
  169.    ''' otherwise, the value.
  170.    ''' </returns>
  171.    ''' ----------------------------------------------------------------------------------------------------
  172.    <DebuggerStepThrough>
  173.    <DebuggerHidden>
  174.    Public Shared Function GetAppConfigSetting(Of T)(ByVal sectionName As String,
  175.                                                     ByVal elementName As String,
  176.                                                     ByVal propertyName As String,
  177.                                                     Optional ByVal exePath As String = "") As T
  178.  
  179.        Dim appConfig As Configuration
  180.        Dim section As ConfigurationSection
  181.        Dim sectionPropInfo As PropertyInformation
  182.        Dim element As ConfigurationElement
  183.        Dim elementPropInfo As PropertyInformation
  184.  
  185.        If Not String.IsNullOrEmpty(exePath) Then
  186.            appConfig = ConfigurationManager.OpenExeConfiguration(exePath)
  187.        Else
  188.            appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  189.        End If
  190.  
  191.        section = appConfig.GetSection(sectionName)
  192.        If section Is Nothing Then
  193.            Return Nothing
  194.        End If
  195.  
  196.        sectionPropInfo = section.ElementInformation.Properties(elementName)
  197.        If sectionPropInfo Is Nothing Then
  198.            Return Nothing
  199.        End If
  200.  
  201.        element = DirectCast(sectionPropInfo.Value, ConfigurationElement)
  202.        If element Is Nothing Then
  203.            Return Nothing
  204.        End If
  205.  
  206.        elementPropInfo = element.ElementInformation.Properties(propertyName)
  207.        If elementPropInfo Is Nothing Then
  208.            Return Nothing
  209.        End If
  210.  
  211.        Return DirectCast(elementPropInfo.Value, T)
  212.  
  213.    End Function
  214.  
  215.    ''' ----------------------------------------------------------------------------------------------------
  216.    ''' <summary>
  217.    ''' Determines whether the performance counters feature is enabled in the application configuration file (app.config)
  218.    ''' of the specified application.
  219.    ''' </summary>
  220.    ''' ----------------------------------------------------------------------------------------------------
  221.    ''' <param name="exePath">
  222.    ''' The executable path of the current or an external .Net application.
  223.    ''' If any path is specified, it assumes the current application.
  224.    ''' </param>
  225.    ''' ----------------------------------------------------------------------------------------------------
  226.    ''' <returns>
  227.    ''' Returns <see langword="False"/> if the performance counters feature is disabled or if the "system.net" section is not defined;
  228.    ''' otherwise, <see langword="True"/>.
  229.    ''' </returns>
  230.    ''' ----------------------------------------------------------------------------------------------------
  231.    <DebuggerStepThrough>
  232.    <DebuggerHidden>
  233.    Public Shared Function IsPerformanceCountersEnabled(Optional ByVal exePath As String = "") As Boolean
  234.  
  235.        Dim appConfig As Configuration
  236.        Dim group As NetSectionGroup
  237.  
  238.        If Not String.IsNullOrEmpty(exePath) Then
  239.            appConfig = ConfigurationManager.OpenExeConfiguration(exePath)
  240.        Else
  241.            appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  242.        End If
  243.  
  244.        group = DirectCast(appConfig.GetSectionGroup("system.net"), NetSectionGroup)
  245.  
  246.        Return (group IsNot Nothing AndAlso group.Settings.PerformanceCounters.Enabled)
  247.  
  248.    End Function
  249.  
  250. #End Region
  251.  
  252. End Class
  253.  
  254. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #486 en: 19 Septiembre 2015, 09:20 am »

NetworkUtil.vb, esta class expone varias funcionalidades relacionadas con los adaptadores de red, desde un evento compartido, NetworkUtil.NetworkStatusChanged, el cual se puede utilizar para monitorizar el estado de la conexión, hasta las classes NetworkUtil.NetworkTrafficMonitor, y NetworkUtil.ProcessTrafficMonitor
que, con sus respectivos eventos a los que uno se puede suscribir, sirven para monitorizar el consumo de tráfico de una red, o el de un proces en particular. Realmente tiene poco más que lo que acabo de mencionar xD.

Source:
http://pastebin.com/byCZSqGc

Ejemplo para monitorizar el estado de la red:
Código
  1. Public Class Form1
  2.  
  3.    Private Sub Form1_Shown() Handles MyBase.Load
  4.  
  5.        AddHandler NetworkUtil.NetworkStatusChanged, AddressOf DoNetworkStatusChanged
  6.  
  7.    End Sub
  8.  
  9.    Private Sub DoNetworkStatusChanged(ByVal sender As Object, e As NetworkUtil.NetworkStatusChangedArgs)
  10.  
  11.        If e.IsAvailable Then
  12.            Console.WriteLine("Network is available.")
  13.  
  14.        Else
  15.            Console.WriteLine("Network is not available.")
  16.  
  17.        End If
  18.  
  19.    End Sub
  20.  
  21. End Class

Ejemplo para monitorizar el tráfico de red:
Código
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.     Dim WithEvents netMon As NetworkUtil.NetworkTrafficMonitor
  4.  
  5.     Private Sub Form1_Load() Handles MyBase.Load
  6.  
  7.         Me.netMon = New NetworkUtil.NetworkTrafficMonitor(NetworkUtil.NetworkTrafficMonitor.GetAvaliableInterfaceNames.First)
  8.         Me.netMon.UpdateBehavior = NetworkUtil.NetworkTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick
  9.         Me.netMon.UpdateInterval = 1000 ' 1 sec
  10.         Me.netMon.Start()
  11.  
  12.     End Sub
  13.  
  14.     '''  ----------------------------------------------------------------------------------------------------
  15.     '''  <summary>
  16.     '''  Handles the <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChanged"/> event of the netMon instance.
  17.     '''  </summary>
  18.     '''  ----------------------------------------------------------------------------------------------------
  19.     '''  <param name="sender">T
  20.     '''  The source of the event.
  21.     '''  </param>
  22.     '''  
  23.     '''  <param name="e">
  24.     '''  The <see cref="NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data.
  25.     '''  </param>
  26.     '''  ----------------------------------------------------------------------------------------------------
  27.     Private Sub NetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.NetworkTrafficMonitor.TrafficChangedEventArgs) _
  28.     Handles netMon.TrafficChanged
  29.  
  30.         Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2"))
  31.         Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2"))
  32.  
  33.         Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2"))
  34.         Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2"))
  35.  
  36.     End Sub
  37.  
  38.     Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click
  39.  
  40.         Dim url As String = "http://download.thinkbroadband.com/10MB.zip"
  41.         Dim client As New WebClient()
  42.         client.DownloadFileAsync(New Uri(url), Path.GetTempFileName())
  43.  
  44.     End Sub
  45.  
  46.     Private Sub BtPauseMon_Click() Handles BtPauseMon.Click
  47.  
  48.         If Me.netMon.IsActive Then
  49.             Me.netMon.Stop()
  50.         Else
  51.             Me.netMon.Start()
  52.         End If
  53.  
  54.     End Sub
  55.  
  56. End Class

Ejemplo para monitorizar el tráfico de una aplicación .Net (que tenga los contadores de rendimiento habilitados):
Código
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.    Dim WithEvents procNetMon As NetworkUtil.ProcessTrafficMonitor
  4.  
  5.    Private Sub Form1_Load() Handles MyBase.Load
  6.  
  7.        Me.procNetMon = New NetworkUtil.ProcessTrafficMonitor(Process.GetCurrentProcess.Id)
  8.        Me.procNetMon.UpdateBehavior = NetworkUtil.ProcessTrafficMonitor.UpdateBehaviorEnum.FireAlwaysAfterTick
  9.        Me.procNetMon.UpdateInterval = 1000 ' 1 sec
  10.        Me.procNetMon.Start()
  11.  
  12.    End Sub
  13.  
  14.   ''' ----------------------------------------------------------------------------------------------------
  15.   ''' <summary>
  16.   ''' Handles the <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChanged"/> event of the procNetMon instance.
  17.   ''' </summary>
  18.   ''' ----------------------------------------------------------------------------------------------------
  19.   ''' <param name="sender">T
  20.   ''' The source of the event.
  21.   ''' </param>
  22.   '''
  23.   ''' <param name="e">
  24.   ''' The <see cref="NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs"/> instance containing the event data.
  25.   ''' </param>
  26.   ''' -----------------------------------------------------------------------------------------------------
  27.    Private Sub ProcNetMon_TrafficChanged(ByVal sender As Object, ByVal e As NetworkUtil.ProcessTrafficMonitor.TrafficChangedEventArgs) _
  28.    Handles procNetMon.TrafficChanged
  29.  
  30.        Me.LabelBytesReceived.Text = String.Format("Bytes received: {0} kb", (e.BytesReceived / 1024).ToString("n2"))
  31.        Me.LabelDlSpeed.Text = String.Format("DL Speed: {0} kb/sec", (e.DiffBytesReceived / 1024).ToString("n2"))
  32.  
  33.        Me.LabelBytesSent.Text = String.Format("Bytes sent: {0} kb", (e.BytesSent / 1024).ToString("n2"))
  34.        Me.LabelUlSpeed.Text = String.Format("UL Speed: {0} kb/sec", (e.DiffBytesSent / 1024).ToString("n2"))
  35.  
  36.    End Sub
  37.  
  38.    Private Sub BtDownloadUrl_Click() Handles BtDownloadUrl.Click
  39.  
  40.        Dim url As String = "http://download.thinkbroadband.com/10MB.zip"
  41.        Dim client As New WebClient()
  42.        client.DownloadFileAsync(New Uri(url), Path.GetTempFileName())
  43.  
  44.    End Sub
  45.  
  46.    Private Sub BtPauseMon_Click() Handles BtPauseMon.Click
  47.  
  48.        If Me.procNetMon.IsActive Then
  49.            Me.procNetMon.Stop()
  50.        Else
  51.            Me.procNetMon.Start()
  52.        End If
  53.  
  54.    End Sub
  55.  
  56. End Class
« Última modificación: 19 Septiembre 2015, 09:24 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #487 en: 19 Septiembre 2015, 09:35 am »

IEnumerable(Of T) Extensions, cómo su propio nombre indica, expone varias extensiones de método para utilizarlas con una colección genérica.

Las extensiones son las siguiente, si alguna no es lo suficientemente aclaratoria entonces pueden usar IntelliSense o el ObjectInspector para conocer el propósito de cada una:
Código
  1. IEnumerable(Of T)().ConcatMultiple(IEnumerable(Of T)()) As IEnumerable(Of T)
  2. IEnumerable(Of T)().StringJoin As IEnumerable(Of T)
  3. IEnumerable(Of T).CountEmptyItems As Integer
  4. IEnumerable(Of T).CountNonEmptyItems As Integer
  5. IEnumerable(Of T).Duplicates As IEnumerable(Of T)
  6. IEnumerable(Of T).Randomize As IEnumerable(Of T)
  7. IEnumerable(Of T).RemoveDuplicates As IEnumerable(Of T)
  8. IEnumerable(Of T).SplitIntoNumberOfElements(Integer) As IEnumerable(Of T)
  9. IEnumerable(Of T).SplitIntoNumberOfElements(Integer, Boolean, T) As IEnumerable(Of T)
  10. IEnumerable(Of T).SplitIntoParts(Integer) As IEnumerable(Of T)
  11. IEnumerable(Of T).UniqueDuplicates As IEnumerable(Of T)
  12. IEnumerable(Of T).Uniques As IEnumerable(Of T)

Puse ejemplos de uso para cada extensión en la documentación XML del código fuente.

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 10-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="IEnumerableExtensions.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " Functions "
  13.  
  14. ' IEnumerable(Of T)().ConcatMultiple(IEnumerable(Of T)()) As IEnumerable(Of T)
  15. ' IEnumerable(Of T)().StringJoin As IEnumerable(Of T)
  16. ' IEnumerable(Of T).CountEmptyItems As Integer
  17. ' IEnumerable(Of T).CountNonEmptyItems As Integer
  18. ' IEnumerable(Of T).Duplicates As IEnumerable(Of T)
  19. ' IEnumerable(Of T).Randomize As IEnumerable(Of T)
  20. ' IEnumerable(Of T).RemoveDuplicates As IEnumerable(Of T)
  21. ' IEnumerable(Of T).SplitIntoNumberOfElements(Integer) As IEnumerable(Of T)
  22. ' IEnumerable(Of T).SplitIntoNumberOfElements(Integer, Boolean, T) As IEnumerable(Of T)
  23. ' IEnumerable(Of T).SplitIntoParts(Integer) As IEnumerable(Of T)
  24. ' IEnumerable(Of T).UniqueDuplicates As IEnumerable(Of T)
  25. ' IEnumerable(Of T).Uniques As IEnumerable(Of T)
  26.  
  27. #End Region
  28.  
  29. #End Region
  30.  
  31. #Region " Option Statements "
  32.  
  33. Option Strict On
  34. Option Explicit On
  35. Option Infer Off
  36.  
  37. #End Region
  38.  
  39. #Region " Imports "
  40.  
  41. Imports System
  42. Imports System.Collections.Generic
  43. Imports System.Diagnostics
  44. Imports System.Linq
  45. Imports System.Runtime.CompilerServices
  46.  
  47. #End Region
  48.  
  49. #Region " IEnumerableUtil "
  50.  
  51. ''' ----------------------------------------------------------------------------------------------------
  52. ''' <summary>
  53. ''' Contains custom extension methods to use with an <see cref="IEnumerable(Of T)"/>.
  54. ''' </summary>
  55. ''' ----------------------------------------------------------------------------------------------------
  56. Public Module IEnumerableExtensions
  57.  
  58.    ''' ----------------------------------------------------------------------------------------------------
  59.    ''' <remarks>
  60.    ''' Title : Get All Duplicates.
  61.    ''' Author: Elektro
  62.    ''' Date  : 08-March-2015
  63.    ''' </remarks>
  64.    ''' ----------------------------------------------------------------------------------------------------
  65.    ''' <example> This is a code example.
  66.    ''' <code>
  67.    ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
  68.    ''' Debug.WriteLine(String.Join(", ", col.Duplicates))
  69.    ''' </code>
  70.    ''' </example>
  71.    ''' ----------------------------------------------------------------------------------------------------
  72.    ''' <summary>
  73.    ''' Gets all the duplicated values of the source <see cref="IEnumerable(Of T)"/>.
  74.    ''' </summary>
  75.    ''' ----------------------------------------------------------------------------------------------------
  76.    ''' <typeparam name="T">
  77.    ''' </typeparam>
  78.    '''
  79.    ''' <param name="sender">
  80.    ''' The source collection.
  81.    ''' </param>
  82.    ''' ----------------------------------------------------------------------------------------------------
  83.    ''' <returns>
  84.    ''' <see cref="IEnumerable(Of T)"/>.
  85.    ''' </returns>
  86.    ''' ----------------------------------------------------------------------------------------------------
  87.    <DebuggerStepThrough>
  88.    <DebuggerHidden>
  89.    <Extension>
  90.    Public Function Duplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)
  91.  
  92.        Return sender.GroupBy(Function(value As T) value).
  93.                      Where(Function(group As IGrouping(Of T, T)) group.Count > 1).
  94.                      SelectMany(Function(group As IGrouping(Of T, T)) group)
  95.  
  96.    End Function
  97.  
  98.    ''' ----------------------------------------------------------------------------------------------------
  99.    ''' <remarks>
  100.    ''' Title : Get Unique Duplicates.
  101.    ''' Author: Elektro
  102.    ''' Date  : 08-March-2015
  103.    ''' </remarks>
  104.    ''' ----------------------------------------------------------------------------------------------------
  105.    ''' <example> This is a code example.
  106.    ''' <code>
  107.    ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
  108.    ''' Debug.WriteLine(String.Join(", ", col.UniqueDuplicates))
  109.    ''' </code>
  110.    ''' </example>
  111.    ''' ----------------------------------------------------------------------------------------------------
  112.    ''' <summary>
  113.    ''' Gets the unique duplicated values of the source <see cref="IEnumerable(Of T)"/>.
  114.    ''' </summary>
  115.    ''' ----------------------------------------------------------------------------------------------------
  116.    ''' <typeparam name="T">
  117.    ''' </typeparam>
  118.    '''
  119.    ''' <param name="sender">
  120.    ''' The source collection.
  121.    ''' </param>
  122.    ''' ----------------------------------------------------------------------------------------------------
  123.    ''' <returns>
  124.    ''' <see cref="IEnumerable(Of T)"/>.
  125.    ''' </returns>
  126.    ''' ----------------------------------------------------------------------------------------------------
  127.    <DebuggerStepThrough>
  128.    <DebuggerHidden>
  129.    <Extension>
  130.    Public Function UniqueDuplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)
  131.  
  132.        Return sender.GroupBy(Function(value As T) value).
  133.                      Where(Function(group As IGrouping(Of T, T)) group.Count > 1).
  134.                      Select(Function(group As IGrouping(Of T, T)) group.Key)
  135.  
  136.    End Function
  137.  
  138.    ''' ----------------------------------------------------------------------------------------------------
  139.    ''' <remarks>
  140.    ''' Title : Get Unique Values.
  141.    ''' Author: Elektro
  142.    ''' Date  : 08-March-2015
  143.    ''' </remarks>
  144.    ''' ----------------------------------------------------------------------------------------------------
  145.    ''' <example> This is a code example.
  146.    ''' <code>
  147.    ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
  148.    ''' Debug.WriteLine(String.Join(", ", col.Uniques))
  149.    ''' </code>
  150.    ''' </example>
  151.    ''' ----------------------------------------------------------------------------------------------------
  152.    ''' <summary>
  153.    ''' Gets the unique values of the source <see cref="IEnumerable(Of T)"/>.
  154.    ''' </summary>
  155.    ''' ----------------------------------------------------------------------------------------------------
  156.    ''' <typeparam name="T">
  157.    ''' </typeparam>
  158.    '''
  159.    ''' <param name="sender">
  160.    ''' The source collection.
  161.    ''' </param>
  162.    ''' ----------------------------------------------------------------------------------------------------
  163.    ''' <returns>
  164.    ''' <see cref="IEnumerable(Of T)"/>.
  165.    ''' </returns>
  166.    ''' ----------------------------------------------------------------------------------------------------
  167.    <DebuggerStepThrough>
  168.    <DebuggerHidden>
  169.    <Extension>
  170.    Public Function Uniques(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)
  171.  
  172.        Return sender.Except(IEnumerableExtensions.UniqueDuplicates(sender))
  173.  
  174.    End Function
  175.  
  176.    ''' ----------------------------------------------------------------------------------------------------
  177.    ''' <remarks>
  178.    ''' Title : Remove Duplicates.
  179.    ''' Author: Elektro
  180.    ''' Date  : 08-March-2015
  181.    ''' </remarks>
  182.    ''' ----------------------------------------------------------------------------------------------------
  183.    ''' <example> This is a code example.
  184.    ''' <code>
  185.    ''' Dim col As IEnumerable(Of Integer) = {1, 1, 2, 2, 3, 3, 0}
  186.    ''' Debug.WriteLine(String.Join(", ", col.RemoveDuplicates))
  187.    ''' </code>
  188.    ''' </example>
  189.    ''' ----------------------------------------------------------------------------------------------------
  190.    ''' <summary>
  191.    ''' Removes duplicated values in the source <see cref="IEnumerable(Of T)"/>.
  192.    ''' </summary>
  193.    ''' ----------------------------------------------------------------------------------------------------
  194.    ''' <typeparam name="T">
  195.    ''' </typeparam>
  196.    '''
  197.    ''' <param name="sender">
  198.    ''' The source collection.
  199.    ''' </param>
  200.    ''' ----------------------------------------------------------------------------------------------------
  201.    ''' <returns>
  202.    ''' <see cref="IEnumerable(Of T)"/>.
  203.    ''' </returns>
  204.    ''' ----------------------------------------------------------------------------------------------------
  205.    <DebuggerStepThrough>
  206.    <DebuggerHidden>
  207.    <Extension>
  208.    Public Function RemoveDuplicates(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)
  209.  
  210.        Return sender.Distinct
  211.  
  212.    End Function
  213.  
  214.    ''' ----------------------------------------------------------------------------------------------------
  215.    ''' <remarks>
  216.    ''' Title : Split Collection Into Number Of Parts.
  217.    ''' Author: Elektro
  218.    ''' Date  : 08-March-2015
  219.    ''' </remarks>
  220.    ''' ----------------------------------------------------------------------------------------------------
  221.    ''' <example> This is a code example.
  222.    ''' <code>
  223.    '''  Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
  224.    '''  Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoParts(amount:=2)
  225.    '''  splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
  226.    '''                                  Debug.WriteLine(String.Join(", ", col))
  227.    '''                              End Sub)
  228.    ''' </code>
  229.    ''' </example>
  230.    ''' ----------------------------------------------------------------------------------------------------
  231.    ''' <summary>
  232.    ''' Splits the source <see cref="IEnumerable(Of T)"/> into the specified amount of secuences.
  233.    ''' </summary>
  234.    ''' ----------------------------------------------------------------------------------------------------
  235.    ''' <typeparam name="T">
  236.    ''' </typeparam>
  237.    '''
  238.    ''' <param name="sender">
  239.    ''' The source collection.
  240.    ''' </param>
  241.    '''
  242.    ''' <param name="amount">
  243.    ''' The target amount of secuences.
  244.    ''' </param>
  245.    ''' ----------------------------------------------------------------------------------------------------
  246.    ''' <returns>
  247.    ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>.
  248.    ''' </returns>
  249.    ''' ----------------------------------------------------------------------------------------------------
  250.    <DebuggerStepThrough>
  251.    <DebuggerHidden>
  252.    <Extension>
  253.    Public Function SplitIntoParts(Of T)(ByVal sender As IEnumerable(Of T),
  254.                                         ByVal amount As Integer) As IEnumerable(Of IEnumerable(Of T))
  255.  
  256.        If (amount = 0) OrElse (amount > sender.Count) OrElse (sender.Count Mod amount <> 0) Then
  257.            Throw New ArgumentOutOfRangeException(paramName:="amount",
  258.                                                  message:="value should be greater than '0', smallest than 'col.Count', and multiplier of 'col.Count'.")
  259.        End If
  260.  
  261.        Dim chunkSize As Integer = CInt(Math.Ceiling(sender.Count() / amount))
  262.  
  263.        Return From index As Integer In Enumerable.Range(0, amount)
  264.               Select sender.Skip(chunkSize * index).Take(chunkSize)
  265.  
  266.    End Function
  267.  
  268.    ''' ----------------------------------------------------------------------------------------------------
  269.    ''' <remarks>
  270.    ''' Title : Split Collection Into Number Of Elements.
  271.    ''' Author: Elektro
  272.    ''' Date  : 08-March-2015
  273.    ''' </remarks>
  274.    ''' ----------------------------------------------------------------------------------------------------
  275.    ''' <example> This is a code example.
  276.    ''' <code>
  277.    '''  Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  278.    '''  Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoNumberOfElements(amount:=4)
  279.    '''  splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
  280.    '''                                  Debug.WriteLine(String.Join(", ", col))
  281.    '''                              End Sub)
  282.    ''' </code>
  283.    ''' </example>
  284.    ''' ----------------------------------------------------------------------------------------------------
  285.    ''' <summary>
  286.    ''' Splits the source <see cref="IEnumerable(Of T)"/> into secuences with the specified amount of elements.
  287.    ''' </summary>
  288.    ''' ----------------------------------------------------------------------------------------------------
  289.    ''' <typeparam name="T">
  290.    ''' </typeparam>
  291.    '''
  292.    ''' <param name="sender">
  293.    ''' The source collection.
  294.    ''' </param>
  295.    '''
  296.    ''' <param name="amount">
  297.    ''' The target amount of elements.
  298.    ''' </param>
  299.    ''' ----------------------------------------------------------------------------------------------------
  300.    ''' <returns>
  301.    ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>.
  302.    ''' </returns>
  303.    ''' ----------------------------------------------------------------------------------------------------
  304.    <DebuggerStepThrough>
  305.    <DebuggerHidden>
  306.    <Extension>
  307.    Public Function SplitIntoNumberOfElements(Of T)(ByVal sender As IEnumerable(Of T),
  308.                                                    ByVal amount As Integer) As IEnumerable(Of IEnumerable(Of T))
  309.  
  310.        Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(sender.Count() / amount)))
  311.               Select sender.Skip(index * amount).Take(amount)
  312.  
  313.    End Function
  314.  
  315.    ''' ----------------------------------------------------------------------------------------------------
  316.    ''' <remarks>
  317.    ''' Title : Split Collection Into Number Of Elements.
  318.    ''' Author: Elektro
  319.    ''' Date  : 08-March-2015
  320.    ''' </remarks>
  321.    ''' ----------------------------------------------------------------------------------------------------
  322.    ''' <example> This is a code example.
  323.    ''' <code>
  324.    '''  Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  325.    '''  Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = mainCol.SplitIntoNumberOfElements(amount:=4, fillEmpty:=True, valueToFill:=0)
  326.    '''  splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
  327.    '''                                  Debug.WriteLine(String.Join(", ", col))
  328.    '''                              End Sub)
  329.    ''' </code>
  330.    ''' </example>
  331.    ''' ----------------------------------------------------------------------------------------------------
  332.    ''' <summary>
  333.    ''' Splits the source <see cref="IEnumerable(Of T)"/> into secuences with the specified amount of elements.
  334.    ''' </summary>
  335.    ''' ----------------------------------------------------------------------------------------------------
  336.    ''' <typeparam name="T">
  337.    ''' </typeparam>
  338.    '''
  339.    ''' <param name="sender">
  340.    ''' The source collection.
  341.    ''' </param>
  342.    '''
  343.    ''' <param name="amount">
  344.    ''' The target amount of elements.
  345.    ''' </param>
  346.    '''
  347.    ''' <param name="fillEmpty">
  348.    ''' If set to <c>true</c>, generates empty elements to fill the last secuence's part amount.
  349.    ''' </param>
  350.    '''
  351.    ''' <param name="valueToFill">
  352.    ''' An optional value used to fill the last secuence's part amount.
  353.    ''' </param>
  354.    ''' ----------------------------------------------------------------------------------------------------
  355.    ''' <returns>
  356.    ''' <see cref="IEnumerable(Of IEnumerable(Of T))"/>.
  357.    ''' </returns>
  358.    ''' ----------------------------------------------------------------------------------------------------
  359.    <DebuggerStepThrough>
  360.    <DebuggerHidden>
  361.    <Extension>
  362.    Public Function SplitIntoNumberOfElements(Of T)(ByVal sender As IEnumerable(Of T),
  363.                                                    ByVal amount As Integer,
  364.                                                    ByVal fillEmpty As Boolean,
  365.                                                    Optional valueToFill As T = Nothing) As IEnumerable(Of IEnumerable(Of T))
  366.  
  367.        Return (From count As Integer In Enumerable.Range(0, CInt(Math.Ceiling(sender.Count() / amount)))).
  368.                Select(Function(count)
  369.  
  370.                           Select Case fillEmpty
  371.  
  372.                               Case True
  373.                                   If (sender.Count - (count * amount)) >= amount Then
  374.                                       Return sender.Skip(count * amount).Take(amount)
  375.  
  376.                                   Else
  377.                                       Return sender.Skip(count * amount).Take(amount).
  378.                                                  Concat(Enumerable.Repeat(Of T)(
  379.                                                         valueToFill,
  380.                                                         amount - (sender.Count() - (count * amount))))
  381.                                   End If
  382.  
  383.                               Case Else
  384.                                   Return sender.Skip(count * amount).Take(amount)
  385.  
  386.                           End Select
  387.  
  388.                       End Function)
  389.  
  390.    End Function
  391.  
  392.    ''' ----------------------------------------------------------------------------------------------------
  393.    ''' <remarks>
  394.    ''' Title : Randomize Collection.
  395.    ''' Author: Elektro
  396.    ''' Date  : 08-March-2015
  397.    ''' </remarks>
  398.    ''' ----------------------------------------------------------------------------------------------------
  399.    ''' <example> This is a code example.
  400.    ''' <code>
  401.    ''' Dim col As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  402.    ''' Debug.WriteLine(String.Join(", ", col.Randomize))
  403.    ''' </code>
  404.    ''' </example>
  405.    ''' ----------------------------------------------------------------------------------------------------
  406.    ''' <summary>
  407.    ''' Randomizes the elements of the source <see cref="IEnumerable(Of T)"/>.
  408.    ''' </summary>
  409.    ''' ----------------------------------------------------------------------------------------------------
  410.    ''' <typeparam name="T">
  411.    ''' </typeparam>
  412.    '''
  413.    ''' <param name="sender">
  414.    ''' The source collection.
  415.    ''' </param>
  416.    ''' ----------------------------------------------------------------------------------------------------
  417.    ''' <returns>
  418.    ''' <see cref="IEnumerable(Of T)"/>.
  419.    ''' </returns>
  420.    ''' ----------------------------------------------------------------------------------------------------
  421.    <DebuggerStepThrough>
  422.    <DebuggerHidden>
  423.    <Extension>
  424.    Public Function Randomize(Of T)(ByVal sender As IEnumerable(Of T)) As IEnumerable(Of T)
  425.  
  426.        Dim rand As New Random
  427.  
  428.        Return From item As T In sender
  429.               Order By rand.Next
  430.  
  431.    End Function
  432.  
  433.    ''' ----------------------------------------------------------------------------------------------------
  434.    ''' <remarks>
  435.    ''' Title : Concatenate Multiple Collections.
  436.    ''' Author: Elektro
  437.    ''' Date  : 08-March-2015
  438.    ''' </remarks>
  439.    ''' ----------------------------------------------------------------------------------------------------
  440.    ''' <example> This is a code example.
  441.    ''' <code>
  442.    ''' Dim col1 As IEnumerable(Of Integer) = {1, 2, 3}
  443.    ''' Dim col2 As IEnumerable(Of Integer) = {4, 5, 6}
  444.    ''' Dim col3 As IEnumerable(Of Integer) = {7, 8, 9}
  445.    ''' Debug.WriteLine(String.Join(", ", {col1, col2, col3}.ConcatMultiple))
  446.    ''' </code>
  447.    ''' </example>
  448.    ''' ----------------------------------------------------------------------------------------------------
  449.    ''' <summary>
  450.    ''' Concatenates multiple <see cref="IEnumerable(Of T)"/> at once into a single <see cref="IEnumerable(Of T)"/>.
  451.    ''' </summary>
  452.    ''' ----------------------------------------------------------------------------------------------------
  453.    ''' <typeparam name="T">
  454.    ''' </typeparam>
  455.    '''
  456.    ''' <param name="sender">
  457.    ''' The source collections.
  458.    ''' </param>
  459.    ''' ----------------------------------------------------------------------------------------------------
  460.    ''' <returns>
  461.    ''' <see cref="IEnumerable(Of T)"/>.
  462.    ''' </returns>
  463.    ''' ----------------------------------------------------------------------------------------------------
  464.    <DebuggerStepThrough>
  465.    <DebuggerHidden>
  466.    <Extension>
  467.    Public Function ConcatMultiple(Of T)(ByVal sender As IEnumerable(Of T)()) As IEnumerable(Of T)
  468.  
  469.        Return sender.SelectMany(Function(col As IEnumerable(Of T)) col)
  470.  
  471.    End Function
  472.  
  473.    ''' ----------------------------------------------------------------------------------------------------
  474.    ''' <remarks>
  475.    ''' Title : Join Multiple Collections Into Single String.
  476.    ''' Author: Elektro
  477.    ''' Date  : 08-March-2015
  478.    ''' </remarks>
  479.    ''' ----------------------------------------------------------------------------------------------------
  480.    ''' <example> This is a code example.
  481.    ''' <code>
  482.    ''' Dim col1 As IEnumerable(Of Integer) = {1, 2, 3}
  483.    ''' Dim col2 As IEnumerable(Of Integer) = {4, 5, 6}
  484.    ''' Dim col3 As IEnumerable(Of Integer) = {7, 8, 9}
  485.    ''' Debug.WriteLine({col1, col2, col3}.StringJoin(", ")))
  486.    ''' </code>
  487.    ''' </example>
  488.    ''' ----------------------------------------------------------------------------------------------------
  489.    ''' <summary>
  490.    ''' Joins multiple <see cref="IEnumerable(Of T)"/> at once into a single string.
  491.    ''' </summary>
  492.    ''' ----------------------------------------------------------------------------------------------------
  493.    ''' <typeparam name="T">
  494.    ''' </typeparam>
  495.    '''    
  496.    ''' <param name="separator">
  497.    ''' The string to use as a separator.
  498.    ''' </param>
  499.    '''
  500.    ''' <param name="sender">
  501.    ''' The source collections.
  502.    ''' </param>
  503.    ''' ----------------------------------------------------------------------------------------------------
  504.    ''' <returns>
  505.    ''' <see cref="String"/>.
  506.    ''' </returns>
  507.    ''' ----------------------------------------------------------------------------------------------------
  508.    <DebuggerStepThrough>
  509.    <DebuggerHidden>
  510.    <Extension>
  511.    Public Function StringJoin(Of T)(ByVal sender As IEnumerable(Of T)(),
  512.                                     ByVal separator As String) As String
  513.  
  514.        Dim sb As New System.Text.StringBuilder
  515.  
  516.        For Each col As IEnumerable(Of T) In sender
  517.            sb.Append(String.Join(separator, col) & separator)
  518.        Next col
  519.  
  520.        Return sb.Remove(sb.Length - separator.Length, separator.Length).ToString
  521.  
  522.    End Function
  523.  
  524.    ''' ----------------------------------------------------------------------------------------------------
  525.    ''' <remarks>
  526.    ''' Title : Count empty items of collection.
  527.    ''' Author: Elektro
  528.    ''' Date  : 16-June-2015
  529.    ''' </remarks>
  530.    ''' ----------------------------------------------------------------------------------------------------
  531.    ''' <example>
  532.    ''' Dim emptyItemCount As Integer = {"Hello", "   ", "World!"}.CountEmptyItems
  533.    ''' </example>
  534.    ''' ----------------------------------------------------------------------------------------------------
  535.    ''' <summary>
  536.    ''' Counts the empty items of the source <see cref="IEnumerable(Of T)"/>.
  537.    ''' </summary>
  538.    ''' ----------------------------------------------------------------------------------------------------
  539.    ''' <param name="sender">
  540.    ''' The source <see cref="IEnumerable(Of T)"/>.
  541.    ''' </param>
  542.    ''' ----------------------------------------------------------------------------------------------------
  543.    ''' <returns>
  544.    ''' The total amount of empty items.
  545.    ''' </returns>
  546.    ''' ----------------------------------------------------------------------------------------------------
  547.    <DebuggerStepThrough>
  548.    <DebuggerHidden>
  549.    <Extension>
  550.    Public Function CountEmptyItems(Of T)(ByVal sender As IEnumerable(Of T)) As Integer
  551.  
  552.        Return (From item As T In sender
  553.                Where (item.Equals(Nothing))).Count
  554.  
  555.    End Function
  556.  
  557.    ''' ----------------------------------------------------------------------------------------------------
  558.    ''' <remarks>
  559.    ''' Title : Count non-empty items of collection.
  560.    ''' Author: Elektro
  561.    ''' Date  : 16-June-2015
  562.    ''' </remarks>
  563.    ''' ----------------------------------------------------------------------------------------------------
  564.    ''' <example>
  565.    ''' Dim nonEmptyItemCount As Integer = {"Hello", "   ", "World!"}.CountNonEmptyItems
  566.    ''' </example>
  567.    ''' ----------------------------------------------------------------------------------------------------
  568.    ''' <summary>
  569.    ''' Counts the non-empty items of the source <see cref="IEnumerable(Of T)"/>.
  570.    ''' </summary>
  571.    ''' ----------------------------------------------------------------------------------------------------
  572.    ''' <param name="sender">
  573.    ''' The source <see cref="IEnumerable(Of T)"/>.
  574.    ''' </param>
  575.    ''' ----------------------------------------------------------------------------------------------------
  576.    ''' <returns>
  577.    ''' The total amount of non-empty items.
  578.    ''' </returns>
  579.    ''' ----------------------------------------------------------------------------------------------------
  580.    <DebuggerStepThrough>
  581.    <DebuggerHidden>
  582.    <Extension>
  583.    Public Function CountNonEmptyItems(Of T)(ByVal sender As IEnumerable(Of T)) As Integer
  584.  
  585.        Return (sender.Count - IEnumerableExtensions.CountEmptyItems(sender))
  586.  
  587.    End Function
  588.  
  589. End Module
  590.  
  591. #End Region











IEnumerable(Of String) Extensions, cómo su propio nombre indica, expone varias extensiones de método para utilizarlas con una colección de strings.

Las extensiones son las siguiente, si alguna no es lo suficientemente aclaratoria entonces pueden usar IntelliSense o el ObjectInspector para conocer el propósito de cada una:
Código
  1. IEnumerable(Of String).BubbleSort As IEnumerable(Of String)
  2. IEnumerable(Of String).CountEmptyItems As Integer
  3. IEnumerable(Of String).CountNonEmptyItems As Integer
  4. IEnumerable(Of String).FindByContains(String, Boolean) As IEnumerable(Of String)
  5. IEnumerable(Of String).FindByLike(String, Boolean) As IEnumerable(Of String)
  6. IEnumerable(Of String).FindExact(String, StringComparison) As IEnumerable(Of String)
  7. IEnumerable(Of String).RemoveByContains(String, Boolean) As IEnumerable(Of String)
  8. IEnumerable(Of String).RemoveByLike(String, Boolean) As IEnumerable(Of String)
  9. IEnumerable(Of String).RemoveExact(String, StringComparison) As IEnumerable(Of String)


Puse ejemplos de uso para cada extensión en la documentación XML del código fuente.

Source:
http://pastebin.com/6XfLcMj8










Array Extensions, cómo su propio nombre indica, expone extensiones de método para utilizarlas con Arays.

Aunque realmente, por el momento solo puse una extensión, pero de igual modo comparto el código para que puedan extender su funcionalidad o tomar la idea como base.

La extensión es la siguiente, sirve para redimensionar el tamaño del array de forma automatizada y más veloz que la habitual.
Código
  1. T().Resize As T()

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 10-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="Array Extensions.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " Functions "
  13.  
  14. ' T().Resize As T()
  15.  
  16. #End Region
  17.  
  18. #End Region
  19.  
  20. #Region " Option Statements "
  21.  
  22. Option Strict On
  23. Option Explicit On
  24. Option Infer Off
  25.  
  26. #End Region
  27.  
  28. #Region " Imports "
  29.  
  30. Imports System
  31. Imports System.Diagnostics
  32. Imports System.Runtime.CompilerServices
  33.  
  34. #End Region
  35.  
  36. ''' ----------------------------------------------------------------------------------------------------
  37. ''' <summary>
  38. ''' Contains custom extension methods to use with an <see cref="Array"/>.
  39. ''' </summary>
  40. ''' ----------------------------------------------------------------------------------------------------
  41. Public Module ArrayExtensions
  42.  
  43. #Region " Public Extension Methods "
  44.  
  45.    ''' ----------------------------------------------------------------------------------------------------
  46.    ''' <remarks>
  47.    ''' Title : Resize Array.
  48.    ''' Author: Elektro
  49.    ''' Date  : 10-September-2015
  50.    ''' </remarks>
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    ''' <example> This is a code example.
  53.    ''' <code>
  54.    ''' Dim myArray(50) As Integer
  55.    ''' Console.WriteLine(String.Format("{0,-12}: {1}", "Initial Size", myArray.Length))
  56.    '''
  57.    ''' myArray = myArray.Resize(myArray.Length - 51)
  58.    ''' Console.WriteLine(String.Format("{0,-12}: {1}", "New Size", myArray.Length))
  59.    ''' </code>
  60.    ''' </example>
  61.    ''' ----------------------------------------------------------------------------------------------------
  62.    ''' <summary>
  63.    ''' Resizes the number of elements of the source <see cref="Array"/>.
  64.    ''' </summary>
  65.    ''' ----------------------------------------------------------------------------------------------------
  66.    ''' <typeparam name="T">
  67.    ''' </typeparam>
  68.    '''
  69.    ''' <param name="sender">
  70.    ''' The source <see cref="Array"/>.
  71.    ''' </param>
  72.    '''
  73.    ''' <param name="newSize">
  74.    ''' The new size.
  75.    ''' </param>
  76.    ''' ----------------------------------------------------------------------------------------------------
  77.    ''' <returns>
  78.    ''' The resized <see cref="Array"/>.
  79.    ''' </returns>
  80.    ''' ----------------------------------------------------------------------------------------------------
  81.    ''' <exception cref="System.ArgumentOutOfRangeException">
  82.    ''' newSize;Non-negative number required
  83.    ''' </exception>
  84.    ''' ----------------------------------------------------------------------------------------------------
  85.    <DebuggerStepThrough>
  86.    <DebuggerHidden>
  87.    <Extension>
  88.    Public Function Resize(Of T)(ByVal sender As T(),
  89.                                 ByVal newSize As Integer) As T()
  90.  
  91.        If (newSize <= 0) Then
  92.            Throw New System.ArgumentOutOfRangeException(paramName:="newSize", message:="Value greater than 0 is required.")
  93.        End If
  94.  
  95.        Dim preserveLength As Integer = Math.Min(sender.Length, newSize)
  96.  
  97.        If (preserveLength > 0) Then
  98.            Dim newArray As Array = Array.CreateInstance(sender.GetType.GetElementType, newSize)
  99.            Array.Copy(sender, newArray, preserveLength)
  100.            Return DirectCast(newArray, T())
  101.  
  102.        Else
  103.            Return sender
  104.  
  105.        End If
  106.  
  107.    End Function
  108.  
  109. #End Region
  110.  
  111. End Module
« Última modificación: 19 Septiembre 2015, 09:44 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #488 en: 19 Septiembre 2015, 09:51 am »

CursorUtil.vb, es una class que por el momento sirve cómo un simple wrapper de la función LoadCursorFromFile de la WinAPI, la cual nos permite evadir las limitaciones de un WindowsForms para poder cargar y utilizar un cursor que no sea blanco y negro.

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 08-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="CursorUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System
  13. Imports System.ComponentModel
  14. Imports System.Diagnostics
  15. Imports System.IO
  16. Imports System.Linq
  17. Imports System.Runtime.InteropServices
  18. Imports System.Windows.Forms
  19.  
  20. #End Region
  21.  
  22. ''' ----------------------------------------------------------------------------------------------------
  23. ''' <summary>
  24. ''' Contains related cursor utilities.
  25. ''' </summary>
  26. ''' ----------------------------------------------------------------------------------------------------
  27. Public NotInheritable Class CursorUtil
  28.  
  29. #Region " P/Invoking "
  30.  
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    ''' <summary>
  33.    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  34.    ''' This class does not suppress stack walks for unmanaged code permission.
  35.    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
  36.    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    ''' <remarks>
  40.    ''' MSDN Documentation: <see href="http://msdn.microsoft.com/en-us/library/ms182161.aspx"/>
  41.    ''' </remarks>
  42.    ''' ----------------------------------------------------------------------------------------------------
  43.    Private NotInheritable Class NativeMethods
  44.  
  45. #Region " Functions "
  46.  
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        ''' <summary>
  49.        ''' Creates a cursor based on data contained in a file.
  50.        ''' </summary>
  51.        ''' ----------------------------------------------------------------------------------------------------
  52.        ''' <param name="filepath">
  53.        ''' The source of the file data to be used to create the cursor.
  54.        ''' The data in the file must be in either .CUR or .ANI format.
  55.        ''' </param>
  56.        ''' ----------------------------------------------------------------------------------------------------
  57.        ''' <returns>
  58.        ''' If the function is successful, the return value is an <see cref="IntPtr"/> to the new cursor.
  59.        ''' If the function fails, the return value is <see cref="IntPtr.Zero"/>.
  60.        ''' To get extended error information, call <see cref="Marshal.GetLastWin32Error"/>.
  61.        ''' </returns>
  62.        ''' ----------------------------------------------------------------------------------------------------    
  63.        ''' <remarks>
  64.        ''' MSDN Documentation: <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms648392%28v=vs.85%29.aspx"/>
  65.        ''' </remarks>
  66.        ''' ----------------------------------------------------------------------------------------------------
  67.        <DllImport("User32.dll", CharSet:=CharSet.Ansi, BestFitMapping:=False, ThrowOnUnmappableChar:=True, SetLastError:=True)>
  68.        Friend Shared Function LoadCursorFromFile(
  69.               ByVal filepath As String
  70.        ) As IntPtr
  71.        End Function
  72.  
  73. #End Region
  74.  
  75.    End Class
  76.  
  77. #End Region
  78.  
  79. #Region " Constructors "
  80.  
  81.    ''' <summary>
  82.    ''' Prevents a default instance of the <see cref="CursorUtil"/> class from being created.
  83.    ''' </summary>
  84.    Private Sub New()
  85.    End Sub
  86.  
  87. #End Region
  88.  
  89. #Region " Public Methods "
  90.  
  91.    ''' ----------------------------------------------------------------------------------------------------
  92.    ''' <summary>
  93.    ''' Creates a cursor based on data contained in a managed .Net resource.
  94.    ''' </summary>
  95.    ''' ----------------------------------------------------------------------------------------------------
  96.    ''' <param name="resource">
  97.    ''' The raw resource data.
  98.    ''' </param>
  99.    ''' ----------------------------------------------------------------------------------------------------
  100.    ''' <returns>
  101.    ''' <see cref="System.Windows.Forms.Cursor"/>.
  102.    ''' </returns>
  103.    ''' ----------------------------------------------------------------------------------------------------
  104.    ''' <exception cref="Exception">
  105.    ''' </exception>
  106.    '''
  107.    ''' <exception cref="Win32Exception">
  108.    ''' </exception>
  109.    ''' ----------------------------------------------------------------------------------------------------
  110.    <DebuggerStepThrough>
  111.    <DebuggerHidden>
  112.    Public Shared Function LoadCursorFromResource(ByVal resource As Byte(),
  113.                                                  Optional cleanTempFile As Boolean = False) As Cursor
  114.  
  115.        Dim tmpFilepath As String = Path.GetTempFileName
  116.  
  117.        Try
  118.            Using fs As New FileStream(tmpFilepath, FileMode.Create, FileAccess.Write, FileShare.Read)
  119.                fs.Write(resource, 0, resource.Length)
  120.            End Using
  121.  
  122.            Dim result As IntPtr = NativeMethods.LoadCursorFromFile(tmpFilepath)
  123.            Dim win32Err As Integer = Marshal.GetLastWin32Error
  124.  
  125.            If (result = IntPtr.Zero) Then
  126.                Throw New Win32Exception([error]:=win32Err)
  127.            Else
  128.                Return New Cursor(result)
  129.            End If
  130.  
  131.        Catch ex As Exception
  132.            Throw
  133.  
  134.        Finally
  135.            If (cleanTempFile) AndAlso (File.Exists(tmpFilepath)) Then
  136.                File.Delete(tmpFilepath)
  137.            End If
  138.  
  139.        End Try
  140.  
  141.    End Function
  142.  
  143. #End Region
  144.  
  145. End Class









SerializationUtil.vb, es una class para serializar y deserializar datos en binario o Xml de forma (más)sencilla y haciendo uso de Generics.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 05-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="SerializationUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System
  13. Imports System.Data
  14. Imports System.IO
  15. Imports System.Linq
  16. Imports System.Runtime.Serialization.Formatters.Binary
  17. Imports System.Xml.Serialization
  18.  
  19. #End Region
  20.  
  21. ''' <summary>
  22. ''' Contains related serialization utilities.
  23. ''' </summary>
  24. Public NotInheritable Class SerializationUtil
  25.  
  26. #Region " Constructors "
  27.  
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    ''' <summary>
  30.    ''' Prevents a default instance of the <see cref="SerializationUtil"/> class from being created.
  31.    ''' </summary>
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    Private Sub New()
  34.    End Sub
  35.  
  36. #End Region
  37.  
  38. #Region " Private Methods "
  39.  
  40.    ''' ----------------------------------------------------------------------------------------------------
  41.    ''' <summary>
  42.    ''' Gets the proper data serializer.
  43.    ''' </summary>
  44.    ''' ----------------------------------------------------------------------------------------------------
  45.    ''' <typeparam name="T">
  46.    ''' </typeparam>
  47.    '''
  48.    ''' <param name="format">
  49.    ''' The serialization format.
  50.    ''' </param>
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    ''' <exception cref="System.ArgumentException">
  53.    ''' Wrong Serialization Format.
  54.    ''' </exception>
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    <DebuggerStepThrough>
  57.    <DebuggerHidden>
  58.    Private Shared Function GetSerializer(Of T)(ByVal format As SerializationFormat) As Object
  59.  
  60.        Select Case format
  61.  
  62.            Case SerializationFormat.Binary
  63.                Return New BinaryFormatter
  64.  
  65.            Case SerializationFormat.Xml
  66.                Return New XmlSerializer(type:=GetType(T))
  67.  
  68.            Case Else
  69.                Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat")
  70.  
  71.        End Select
  72.  
  73.    End Function
  74.  
  75.    ''' ----------------------------------------------------------------------------------------------------
  76.    ''' <summary>
  77.    ''' Gets the proper data serializer.
  78.    ''' </summary>
  79.    ''' ----------------------------------------------------------------------------------------------------
  80.    ''' <typeparam name="T">
  81.    ''' </typeparam>
  82.    '''
  83.    ''' <param name="obj">
  84.    ''' The object to check.
  85.    ''' </param>
  86.    '''
  87.    ''' <param name="format">
  88.    ''' The serialization format.
  89.    ''' </param>
  90.    ''' ----------------------------------------------------------------------------------------------------
  91.    <DebuggerStepThrough>
  92.    <DebuggerHidden>
  93.    Private Shared Function GetSerializer(Of T)(ByVal obj As T,
  94.                                                ByVal format As SerializationFormat) As Object
  95.  
  96.        Select format
  97.  
  98.            Case SerializationFormat.Binary
  99.                Return New BinaryFormatter()
  100.  
  101.            Case SerializationFormat.Xml
  102.                Return New XmlSerializer(obj.GetType)
  103.  
  104.            Case Else
  105.                Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat")
  106.  
  107.        End Select
  108.  
  109.    End Function
  110.  
  111. #End Region
  112.  
  113. #Region " Public Methods "
  114.  
  115.    ''' ----------------------------------------------------------------------------------------------------
  116.    ''' <summary>
  117.    ''' Serializes the data of an Object to the specified file, using the specified serialization format.
  118.    ''' </summary>
  119.    ''' ----------------------------------------------------------------------------------------------------
  120.    ''' <typeparam name="T">
  121.    ''' </typeparam>
  122.    '''
  123.    ''' <param name="obj">
  124.    ''' The object to be serialized.
  125.    ''' </param>
  126.    '''
  127.    ''' <param name="filepath">
  128.    ''' The filepath where to save the serialized data.
  129.    ''' </param>
  130.    '''
  131.    ''' <param name="format">
  132.    ''' The serialization format.
  133.    ''' </param>
  134.    ''' ----------------------------------------------------------------------------------------------------
  135.    <DebuggerStepThrough>
  136.    <DebuggerHidden>
  137.    Public Shared Sub Serialize(Of T)(ByVal obj As T,
  138.                                      ByVal filepath As String,
  139.                                      ByVal format As SerializationFormat)
  140.  
  141.        Dim serializer As Object = SerializationUtil.GetSerializer(obj, format)
  142.  
  143.        Using fs As New FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)
  144.  
  145.            Select Case serializer.GetType
  146.  
  147.                Case GetType(BinaryFormatter)
  148.                    DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)
  149.  
  150.                Case GetType(XmlSerializer)
  151.                    DirectCast(serializer, XmlSerializer).Serialize(fs, obj)
  152.  
  153.            End Select
  154.  
  155.        End Using
  156.  
  157.    End Sub
  158.  
  159.    ''' ----------------------------------------------------------------------------------------------------
  160.    ''' <summary>
  161.    ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
  162.    ''' </summary>
  163.    ''' ----------------------------------------------------------------------------------------------------
  164.    ''' <typeparam name="T">
  165.    ''' </typeparam>
  166.    '''
  167.    ''' <param name="filepath">
  168.    ''' The filepath where from deserialize the serialized data.
  169.    ''' </param>
  170.    '''
  171.    ''' <param name="format">
  172.    ''' The serialization format.
  173.    ''' </param>
  174.    ''' ----------------------------------------------------------------------------------------------------
  175.    <DebuggerStepThrough>
  176.    <DebuggerHidden>
  177.    Public Shared Function Deserialize(Of T)(ByVal filepath As String,
  178.                                             ByVal format As SerializationFormat) As T
  179.  
  180.        Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)
  181.  
  182.        Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
  183.  
  184.            Select Case serializer.GetType
  185.  
  186.                Case GetType(BinaryFormatter)
  187.                    Return DirectCast(DirectCast(serializer, BinaryFormatter).Deserialize(fs), T)
  188.  
  189.                Case GetType(XmlSerializer)
  190.                    Return DirectCast(DirectCast(serializer, XmlSerializer).Deserialize(fs), T)
  191.  
  192.            End Select
  193.  
  194.        End Using
  195.  
  196.    End Function
  197.  
  198.    ''' ----------------------------------------------------------------------------------------------------
  199.    ''' <summary>
  200.    ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
  201.    ''' </summary>
  202.    ''' ----------------------------------------------------------------------------------------------------
  203.    ''' <typeparam name="T">
  204.    ''' </typeparam>
  205.    '''
  206.    ''' <param name="filepath">
  207.    ''' The filepath where from deserialize the serialized data.
  208.    ''' </param>
  209.    '''
  210.    ''' <param name="format">
  211.    ''' The serialization format.
  212.    ''' </param>
  213.    ''' ----------------------------------------------------------------------------------------------------
  214.    <DebuggerStepThrough>
  215.    <DebuggerHidden>
  216.    Public Shared Sub Deserialize(Of T)(ByRef refObj As T,
  217.                                        ByVal filepath As String,
  218.                                        ByVal format As SerializationFormat)
  219.  
  220.        refObj = SerializationUtil.Deserialize(Of T)(filepath, format)
  221.  
  222.    End Sub
  223.  
  224.    ''' ----------------------------------------------------------------------------------------------------
  225.    ''' <summary>
  226.    ''' Determines whether the specified <see cref="Type"/> can be serialized.
  227.    ''' </summary>
  228.    ''' ----------------------------------------------------------------------------------------------------
  229.    ''' <typeparam name="T">
  230.    ''' The <see cref="Type"/> to check.
  231.    ''' </typeparam>
  232.    ''' ----------------------------------------------------------------------------------------------------
  233.    ''' <returns>
  234.    ''' <c>True</c> if the specified <see cref="Type"/> can be serialized; otherwise, <c>False</c>.
  235.    ''' </returns>
  236.    ''' ----------------------------------------------------------------------------------------------------
  237.    Public Shared Function IsTypeSerializable(Of T)() As Boolean
  238.  
  239.        Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))
  240.  
  241.    End Function
  242.  
  243.    ''' ----------------------------------------------------------------------------------------------------
  244.    ''' <summary>
  245.    ''' Determines whether the specified <see cref="Type"/> can be serialized.
  246.    ''' </summary>
  247.    ''' ----------------------------------------------------------------------------------------------------
  248.    ''' <typeparam name="T">
  249.    ''' </typeparam>
  250.    '''
  251.    ''' <param name="type">
  252.    ''' The <see cref="Type"/> to check.
  253.    ''' </param>
  254.    ''' ----------------------------------------------------------------------------------------------------
  255.    ''' <returns>
  256.    ''' <c>True</c> if the specified <see cref="Type"/> can be serialized; otherwise, <c>False</c>.
  257.    ''' </returns>
  258.    ''' ----------------------------------------------------------------------------------------------------
  259.    Public Shared Function IsTypeSerializable(Of T)(ByVal type As T) As Boolean
  260.  
  261.        Return SerializationUtil.IsTypeSerializable(Of T)()
  262.  
  263.    End Function
  264.  
  265.    ''' ----------------------------------------------------------------------------------------------------
  266.    ''' <summary>
  267.    ''' Determines whether the specified object can be serialized.
  268.    ''' </summary>
  269.    ''' ----------------------------------------------------------------------------------------------------
  270.    ''' <typeparam name="T">
  271.    ''' </typeparam>
  272.    '''
  273.    ''' <param name="obj">
  274.    ''' The object to check.
  275.    ''' </param>
  276.    ''' ----------------------------------------------------------------------------------------------------
  277.    ''' <returns>
  278.    ''' <c>True</c> if the specified object can be serialized; otherwise, <c>False</c>.
  279.    ''' </returns>
  280.    ''' ----------------------------------------------------------------------------------------------------
  281.    Public Shared Function IsObjectSerializable(Of T)(ByVal obj As T,
  282.                                                      ByVal format As SerializationFormat) As Boolean
  283.  
  284.        Dim serializer As Object = SerializationUtil.GetSerializer(obj, format)
  285.  
  286.        Using fs As New MemoryStream
  287.  
  288.            Try
  289.                Select Case serializer.GetType
  290.  
  291.                    Case GetType(BinaryFormatter)
  292.                        DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)
  293.  
  294.                    Case GetType(XmlSerializer)
  295.                        DirectCast(serializer, XmlSerializer).Serialize(fs, obj)
  296.  
  297.                End Select
  298.  
  299.                Return True
  300.  
  301.            Catch ex As InvalidOperationException
  302.                Return False
  303.  
  304.            Catch ex As Exception
  305.                Throw
  306.  
  307.            End Try
  308.  
  309.        End Using
  310.  
  311.    End Function
  312.  
  313. #End Region
  314.  
  315. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #489 en: 19 Septiembre 2015, 10:04 am »

ResourceUtil.vb, es el comienzo de una class para administrar los recursos de la aplicación actual, aunque por el momento solo tiene un método genérico GetResources(Of T) que cómo su nombre nidica, obtiene los recursos del tipo especificado.

Para un código mucho más completo y extenso que sirve para administrar un archivo de recurso de .Net (resource.ResX) vease este otro aporte:
ResXManager.vb

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-June-2015
  4. ' ***********************************************************************
  5. ' <copyright file="ResourceUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Public Members Summary "
  11.  
  12. #Region " Functions "
  13.  
  14. ' ResourceUtil.GetResources(OF T)
  15.  
  16. #End Region
  17.  
  18. #End Region
  19.  
  20. #Region " Option Statements "
  21.  
  22. Option Strict On
  23. Option Explicit On
  24. Option Infer Off
  25.  
  26. #End Region
  27.  
  28. #Region " Imports "
  29.  
  30. Imports System
  31. Imports System.Globalization
  32.  
  33. #End Region
  34.  
  35. ''' <summary>
  36. ''' Contains related application's managed resource utilities.
  37. ''' </summary>
  38. Public NotInheritable Class ResourceUtil
  39.  
  40. #Region " Constructors "
  41.  
  42.    ''' ----------------------------------------------------------------------------------------------------
  43.    ''' <summary>
  44.    ''' Prevents a default instance of the <see cref="ResourceUtil"/> class from being created.
  45.    ''' </summary>
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    <DebuggerStepThrough>
  48.    Private Sub New()
  49.    End Sub
  50.  
  51. #End Region
  52.  
  53. #Region " Public Methods "
  54.  
  55.    ''' ----------------------------------------------------------------------------------------------------
  56.    ''' <remarks>
  57.    ''' Title : Get Application Resources Of Type...
  58.    ''' Author: Elektro
  59.    ''' Date  : 16-June-2015
  60.    ''' </remarks>
  61.    ''' ----------------------------------------------------------------------------------------------------
  62.    ''' <example> Get all String resources.
  63.    ''' <code>
  64.    ''' Dim resources As IEnumerable(Of DictionaryEntry) = GetResources(Of Bitmap)()
  65.    '''
  66.    ''' For Each resource As DictionaryEntry In resources
  67.    '''
  68.    '''     MsgBox(resource.Key)            '  Resource Name
  69.    '''     MsgBox(resource.Value.ToString) '  Resource Data
  70.    '''
  71.    ''' Next resource
  72.    ''' </code>
  73.    ''' </example>
  74.    ''' ----------------------------------------------------------------------------------------------------
  75.    ''' <summary>
  76.    ''' Gets the application resources of the specified type.
  77.    ''' </summary>
  78.    ''' ----------------------------------------------------------------------------------------------------
  79.    ''' <typeparam name="T">
  80.    ''' The type of the resource to find.
  81.    ''' </typeparam>
  82.    '''
  83.    ''' <param name="culture">
  84.    ''' The resource culture
  85.    ''' </param>
  86.    ''' ----------------------------------------------------------------------------------------------------
  87.    ''' <returns>
  88.    ''' <see cref="IEnumerable(Of DictionaryEntry)"/>.
  89.    ''' </returns>
  90.    ''' ----------------------------------------------------------------------------------------------------
  91.    <DebuggerStepThrough>
  92.    Public Shared Function GetResources(Of T)(Optional ByVal culture As CultureInfo = Nothing) As IEnumerable(Of DictionaryEntry)
  93.  
  94.        Return From resource As DictionaryEntry
  95.               In My.Resources.ResourceManager.
  96.                               GetResourceSet(If(culture Is Nothing,
  97.                                                 CultureInfo.CurrentCulture,
  98.                                                 culture), createIfNotExists:=True, tryParents:=True).Cast(Of DictionaryEntry)()
  99.               Where TypeOf resource.Value Is T
  100.  
  101.    End Function
  102.  
  103. #End Region
  104.  
  105. End Class










Un simple ejemplo de uso de la librería AndroidLib para .Net
https://github.com/regaw-leinad/AndroidLib

Otros ejemplos oficiales:
https://github.com/regaw-leinad/AndroidLib-Samples-VB

Source:
Código
  1. Imports RegawMOD.Android
  2.  
  3. Public Class Form1
  4.  
  5.    Dim android As AndroidController
  6.    Dim device As Device
  7.    Dim serial As String
  8.  
  9.    Private Sub Test() Handles MyBase.Shown
  10.  
  11.        ' Usually, you want to load this at startup, may take up to 5 seconds to initialize/set up resources/start server.
  12.        Me.android = AndroidController.Instance
  13.  
  14.        Using Me.android
  15.  
  16.            ' Always call UpdateDeviceList() before using AndroidController on devices, to get the most updated list.
  17.            Me.android.UpdateDeviceList()
  18.  
  19.            If Me.android.HasConnectedDevices Then
  20.  
  21.                Me.serial = android.ConnectedDevices(0)
  22.                Me.device = android.GetConnectedDevice(serial)
  23.  
  24.                device.BuildProp.Keys.
  25.                    ForEach(Sub(propertyName As String)
  26.  
  27.                                Console.WriteLine(String.Format("{0}: {1}",
  28.                                                                propertyName,
  29.                                                                device.BuildProp.GetProp(propertyName)))
  30.  
  31.                            End Sub)
  32.  
  33.            End If
  34.  
  35.        End Using
  36.  
  37.    End Sub
  38.  
  39. End Class
En línea



Páginas: 1 ... 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 [49] 50 51 52 53 54 55 56 57 58 59 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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