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

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


+  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 ... 32 33 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 526,932 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #460 en: 14 Abril 2015, 13:09 pm »

Una helper class para manejar los servicios de Windows.

Por el momento puede listar, iniciar, detener, y determinar el estado o el modo de inicio de un servicio.
(no lo he testeado mucho en profundidad)

Ejemplos de uso:
Código
  1.        Dim svcName As String = "themes"
  2.        Dim svcDisplayName As String = ServiceUtils.GetDisplayName(svcName)
  3.        Dim svcStatus As ServiceControllerStatus = ServiceUtils.GetStatus(svcName)
  4.        Dim svcStartMode As ServiceUtils.SvcStartMode = ServiceUtils.GetStartMode(svcName)
  5.  
  6.        ServiceUtils.SetStartMode(svcName, ServiceUtils.SvcStartMode.Automatic)
  7.        ServiceUtils.SetStatus(svcName, ServiceUtils.SvcStatus.Stop, wait:=True, throwOnStatusMissmatch:=True)

Source code:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 14-April-2015
  4. ' ***********************************************************************
  5. ' <copyright file="ServiceUtils.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Dim svcName As String = "themes"
  13. 'Dim svcDisplayName As String = ServiceUtils.GetDisplayName(svcName)
  14. 'Dim svcStatus As ServiceControllerStatus = ServiceUtils.GetStatus(svcName)
  15. 'Dim svcStartMode As ServiceUtils.SvcStartMode = ServiceUtils.GetStartMode(svcName)
  16.  
  17. 'ServiceUtils.SetStartMode(svcName, ServiceUtils.SvcStartMode.Automatic)
  18. 'ServiceUtils.SetStatus(svcName, ServiceUtils.SvcStatus.Stop, wait:=True, throwOnStatusMissmatch:=True)
  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 Microsoft.Win32
  33. Imports System.ServiceProcess
  34.  
  35. #End Region
  36.  
  37. ''' <summary>
  38. ''' Contains related Windows service tools.
  39. ''' </summary>
  40. Public NotInheritable Class ServiceUtils
  41.  
  42. #Region " Enumerations "
  43.  
  44.    ''' <summary>
  45.    ''' Indicates the status of a service.
  46.    ''' </summary>
  47.    Public Enum SvcStatus
  48.  
  49.        ''' <summary>
  50.        ''' The service is running.
  51.        ''' </summary>
  52.        Start
  53.  
  54.        ''' <summary>
  55.        ''' The service is stopped.
  56.        ''' </summary>
  57.        [Stop]
  58.  
  59.    End Enum
  60.  
  61.    ''' <summary>
  62.    ''' Indicates the start mode of a service.
  63.    ''' </summary>
  64.    Public Enum SvcStartMode As Integer
  65.  
  66.        ''' <summary>
  67.        ''' Indicates that the service has not a start mode defined.
  68.        ''' Since a service should have a start mode defined, this means an error occured retrieving the start mode.
  69.        ''' </summary>
  70.        Undefinied = 0
  71.  
  72.        ''' <summary>
  73.        ''' Indicates that the service is to be started (or was started) by the operating system, at system start-up.
  74.        ''' The service is started after other auto-start services are started plus a short delay.
  75.        ''' </summary>
  76.        AutomaticDelayed = 1
  77.  
  78.        ''' <summary>
  79.        ''' Indicates that the service is to be started (or was started) by the operating system, at system start-up.
  80.        ''' If an automatically started service depends on a manually started service,
  81.        ''' the manually started service is also started automatically at system startup.
  82.        ''' </summary>
  83.        Automatic = 2 'ServiceStartMode.Automatic
  84.  
  85.        ''' <summary>
  86.        ''' Indicates that the service is started only manually,
  87.        ''' by a user (using the Service Control Manager) or by an application.
  88.        ''' </summary>
  89.        Manual = 3 'ServiceStartMode.Manual
  90.  
  91.        ''' <summary>
  92.        ''' Indicates that the service is disabled, so that it cannot be started by a user or application.
  93.        ''' </summary>
  94.        Disabled = 4 ' ServiceStartMode.Disabled
  95.  
  96.    End Enum
  97.  
  98. #End Region
  99.  
  100. #Region " Public Methods "
  101.  
  102.    ''' <summary>
  103.    ''' Retrieves all the services on the local computer, except for the device driver services.
  104.    ''' </summary>
  105.    ''' <returns>IEnumerable(Of ServiceController).</returns>
  106.    Public Shared Function GetServices() As IEnumerable(Of ServiceController)
  107.  
  108.        Return ServiceController.GetServices.AsEnumerable
  109.  
  110.    End Function
  111.  
  112.    ''' <summary>
  113.    ''' Gets the name of a service.
  114.    ''' </summary>
  115.    ''' <param name="svcDisplayName">The service's display name.</param>
  116.    ''' <returns>The service name.</returns>
  117.    ''' <exception cref="ArgumentException">Any service found with the specified display name.;svcDisplayName</exception>
  118.    Public Shared Function GetName(ByVal svcDisplayName As String) As String
  119.  
  120.        Dim svc As ServiceController = (From service As ServiceController In ServiceController.GetServices()
  121.                                        Where service.DisplayName.Equals(svcDisplayName, StringComparison.OrdinalIgnoreCase)
  122.                                        ).FirstOrDefault
  123.  
  124.        If svc Is Nothing Then
  125.            Throw New ArgumentException("Any service found with the specified display name.", "svcDisplayName")
  126.  
  127.        Else
  128.            Using svc
  129.                Return svc.ServiceName
  130.            End Using
  131.  
  132.        End If
  133.  
  134.    End Function
  135.  
  136.    ''' <summary>
  137.    ''' Gets the display name of a service.
  138.    ''' </summary>
  139.    ''' <param name="svcName">The service name.</param>
  140.    ''' <returns>The service's display name.</returns>
  141.    ''' <exception cref="ArgumentException">Any service found with the specified name.;svcName</exception>
  142.    Public Shared Function GetDisplayName(ByVal svcName As String) As String
  143.  
  144.        Dim svc As ServiceController = (From service As ServiceController In ServiceController.GetServices()
  145.                                        Where service.ServiceName.Equals(svcName, StringComparison.OrdinalIgnoreCase)
  146.                                        ).FirstOrDefault
  147.  
  148.        If svc Is Nothing Then
  149.            Throw New ArgumentException("Any service found with the specified name.", "svcName")
  150.  
  151.        Else
  152.            Using svc
  153.                Return svc.DisplayName
  154.            End Using
  155.  
  156.        End If
  157.  
  158.    End Function
  159.  
  160.    ''' <summary>
  161.    ''' Gets the status of a service.
  162.    ''' </summary>
  163.    ''' <param name="svcName">The service name.</param>
  164.    ''' <returns>The service status.</returns>
  165.    ''' <exception cref="ArgumentException">Any service found with the specified name.;svcName</exception>
  166.    Public Shared Function GetStatus(ByVal svcName As String) As ServiceControllerStatus
  167.  
  168.        Dim svc As ServiceController =
  169.            (From service As ServiceController In ServiceController.GetServices()
  170.             Where service.ServiceName.Equals(svcName, StringComparison.OrdinalIgnoreCase)
  171.            ).FirstOrDefault
  172.  
  173.        If svc Is Nothing Then
  174.            Throw New ArgumentException("Any service found with the specified name.", "svcName")
  175.  
  176.        Else
  177.            Using svc
  178.                Return svc.Status
  179.            End Using
  180.  
  181.        End If
  182.  
  183.    End Function
  184.  
  185.    ''' <summary>
  186.    ''' Gets the start mode of a service.
  187.    ''' </summary>
  188.    ''' <param name="svcName">The service name.</param>
  189.    ''' <returns>The service's start mode.</returns>
  190.    ''' <exception cref="ArgumentException">Any service found with the specified name.</exception>
  191.    ''' <exception cref="Exception">Registry value "Start" not found for service.</exception>
  192.    ''' <exception cref="Exception">Registry value "DelayedAutoStart" not found for service.</exception>
  193.    Public Shared Function GetStartMode(ByVal svcName As String) As SvcStartMode
  194.  
  195.        Dim reg As RegistryKey = Nothing
  196.        Dim startModeValue As Integer = 0
  197.        Dim delayedAutoStartValue As Integer = 0
  198.  
  199.        Try
  200.            reg = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\" & svcName, writable:=False)
  201.  
  202.            If reg Is Nothing Then
  203.                Throw New ArgumentException("Any service found with the specified name.", paramName:="svcName")
  204.  
  205.            Else
  206.                startModeValue = Convert.ToInt32(reg.GetValue("Start", defaultValue:=-1))
  207.                delayedAutoStartValue = Convert.ToInt32(reg.GetValue("DelayedAutoStart", defaultValue:=0))
  208.  
  209.                If startModeValue = -1 Then
  210.                    Throw New Exception(String.Format("Registry value ""Start"" not found for service '{0}'.", svcName))
  211.                    Return SvcStartMode.Undefinied
  212.  
  213.                Else
  214.                    Return DirectCast([Enum].Parse(GetType(SvcStartMode),
  215.                                                   (startModeValue - delayedAutoStartValue).ToString), SvcStartMode)
  216.  
  217.                End If
  218.  
  219.            End If
  220.  
  221.        Catch ex As Exception
  222.            Throw
  223.  
  224.        Finally
  225.            If reg IsNot Nothing Then
  226.                reg.Dispose()
  227.            End If
  228.  
  229.        End Try
  230.  
  231.    End Function
  232.  
  233.    ''' <summary>
  234.    ''' Gets the start mode of a service.
  235.    ''' </summary>
  236.    ''' <param name="svc">The service.</param>
  237.    ''' <returns>The service's start mode.</returns>
  238.    Public Shared Function GetStartMode(ByVal svc As ServiceController) As SvcStartMode
  239.  
  240.        Return GetStartMode(svc.ServiceName)
  241.  
  242.    End Function
  243.  
  244.    ''' <summary>
  245.    ''' Sets the start mode of a service.
  246.    ''' </summary>
  247.    ''' <param name="svcName">The service name.</param>
  248.    ''' <param name="startMode">The start mode.</param>
  249.    ''' <exception cref="ArgumentException">Any service found with the specified name.</exception>
  250.    ''' <exception cref="ArgumentException">Unexpected value.</exception>
  251.    Public Shared Sub SetStartMode(ByVal svcName As String,
  252.                                   ByVal startMode As SvcStartMode)
  253.  
  254.        Dim reg As RegistryKey = Nothing
  255.  
  256.        Try
  257.            reg = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\" & svcName, writable:=True)
  258.  
  259.            If reg Is Nothing Then
  260.                Throw New ArgumentException("Any service found with the specified name.", paramName:="svcName")
  261.  
  262.            Else
  263.  
  264.                Select Case startMode
  265.  
  266.                    Case SvcStartMode.AutomaticDelayed
  267.                        reg.SetValue("DelayedAutoStart", 1, RegistryValueKind.DWord)
  268.                        reg.SetValue("Start", SvcStartMode.Automatic, RegistryValueKind.DWord)
  269.  
  270.                    Case SvcStartMode.Automatic, SvcStartMode.Manual, SvcStartMode.Disabled
  271.                        reg.SetValue("DelayedAutoStart", 0, RegistryValueKind.DWord)
  272.                        reg.SetValue("Start", startMode, RegistryValueKind.DWord)
  273.  
  274.                    Case Else
  275.                        Throw New ArgumentException("Unexpected value.", paramName:="startMode")
  276.  
  277.                End Select
  278.  
  279.            End If
  280.  
  281.        Catch ex As Exception
  282.            Throw
  283.  
  284.        Finally
  285.            If reg IsNot Nothing Then
  286.                reg.Dispose()
  287.            End If
  288.  
  289.        End Try
  290.  
  291.    End Sub
  292.  
  293.    ''' <summary>
  294.    ''' Sets the start mode of a service.
  295.    ''' </summary>
  296.    ''' <param name="svc">The service.</param>
  297.    ''' <param name="startMode">The start mode.</param>
  298.    Public Shared Sub SetStartMode(ByVal svc As ServiceController,
  299.                                   ByVal startMode As SvcStartMode)
  300.  
  301.        SetStartMode(svc.ServiceName, startMode)
  302.  
  303.    End Sub
  304.  
  305.    ''' <summary>
  306.    ''' Sets the status of a service.
  307.    ''' </summary>
  308.    ''' <param name="svcName">The service name.</param>
  309.    ''' <param name="status">The desired service status.</param>
  310.    ''' <param name="wait">if set to <c>true</c> waits for the status change completition.</param>
  311.    ''' <param name="throwOnStatusMissmatch">
  312.    ''' If set to <c>true</c> throws an error when attempting to start a service that is started,
  313.    ''' or attempting to stop a service that is stopped.
  314.    ''' </param>
  315.    ''' <exception cref="ArgumentException">Any service found with the specified name.;svcName</exception>
  316.    ''' <exception cref="ArgumentException">Cannot start service because it is disabled.</exception>
  317.    ''' <exception cref="ArgumentException">Cannot start service because a dependant service is disabled.</exception>
  318.    ''' <exception cref="ArgumentException">The service is already running or pendng to run it.</exception>
  319.    ''' <exception cref="ArgumentException">The service is already stopped or pendng to stop it.</exception>
  320.    ''' <exception cref="ArgumentException">Unexpected enumeration value.</exception>
  321.    ''' <exception cref="Exception"></exception>
  322.    Public Shared Sub SetStatus(ByVal svcName As String,
  323.                                ByVal status As SvcStatus,
  324.                                Optional wait As Boolean = False,
  325.                                Optional ByVal throwOnStatusMissmatch As Boolean = False)
  326.  
  327.        Dim svc As ServiceController = Nothing
  328.  
  329.        Try
  330.            svc = (From service As ServiceController In ServiceController.GetServices()
  331.                   Where service.ServiceName.Equals(svcName, StringComparison.OrdinalIgnoreCase)
  332.                  ).FirstOrDefault
  333.  
  334.            If svc Is Nothing Then
  335.                Throw New ArgumentException("Any service found with the specified name.", "svcName")
  336.  
  337.            ElseIf GetStartMode(svc) = SvcStartMode.Disabled Then
  338.                Throw New Exception(String.Format("Cannot start or stop service '{0}' because it is disabled.", svcName))
  339.  
  340.            Else
  341.  
  342.                Select Case status
  343.  
  344.                    Case SvcStatus.Start
  345.  
  346.                        Select Case svc.Status
  347.  
  348.                            Case ServiceControllerStatus.Stopped,
  349.                                 ServiceControllerStatus.StopPending,
  350.                                 ServiceControllerStatus.Paused,
  351.                                 ServiceControllerStatus.PausePending
  352.  
  353.                                For Each dependantSvc As ServiceController In svc.ServicesDependedOn
  354.  
  355.                                    If GetStartMode(dependantSvc) = SvcStartMode.Disabled Then
  356.                                        Throw New Exception(String.Format("Cannot start service '{0}' because a dependant service '{1}' is disabled.",
  357.                                                                          svcName, dependantSvc.ServiceName))
  358.                                        Exit Select
  359.                                    End If
  360.  
  361.                                Next dependantSvc
  362.  
  363.                                svc.Start()
  364.                                If wait Then
  365.                                    svc.WaitForStatus(ServiceControllerStatus.Running)
  366.                                End If
  367.  
  368.                            Case ServiceControllerStatus.Running,
  369.                                 ServiceControllerStatus.StartPending,
  370.                                 ServiceControllerStatus.ContinuePending
  371.  
  372.                                If throwOnStatusMissmatch Then
  373.                                    Throw New Exception(String.Format("The service '{0}' is already running or pendng to run it.", svcName))
  374.                                End If
  375.  
  376.                        End Select
  377.  
  378.                    Case SvcStatus.Stop
  379.  
  380.                        Select Case svc.Status
  381.  
  382.                            Case ServiceControllerStatus.Running,
  383.                                 ServiceControllerStatus.StartPending,
  384.                                 ServiceControllerStatus.ContinuePending
  385.  
  386.                                svc.Stop()
  387.                                If wait Then
  388.                                    svc.WaitForStatus(ServiceControllerStatus.Stopped)
  389.                                End If
  390.  
  391.                            Case ServiceControllerStatus.Stopped,
  392.                                 ServiceControllerStatus.StopPending,
  393.                                 ServiceControllerStatus.Paused,
  394.                                 ServiceControllerStatus.PausePending
  395.  
  396.                                If throwOnStatusMissmatch Then
  397.                                    Throw New Exception(String.Format("The service '{0}' is already stopped or pendng to stop it.", svcName))
  398.                                End If
  399.  
  400.                        End Select
  401.  
  402.                    Case Else
  403.                        Throw New ArgumentException("Unexpected enumeration value.", paramName:="status")
  404.  
  405.                End Select
  406.  
  407.            End If
  408.  
  409.        Catch ex As Exception
  410.            Throw
  411.  
  412.        Finally
  413.            If svc IsNot Nothing Then
  414.                svc.Close()
  415.            End If
  416.  
  417.        End Try
  418.  
  419.    End Sub
  420.  
  421. #End Region
  422.  
  423. End Class


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #461 en: 10 Mayo 2015, 17:08 pm »

PathUtil, una class para administrar los directorios de la variable de entorno PATH, y las extensiones de la variable de entorno PATHEXT.

( IMPORTANTE: Esta class depende de mi otra Class RegEdit, que pueden descargar aquí: http://foro.elhacker.net/net/libreria_de_snippets_compartan_aqui_sus_snippets-t378770.0.html;msg2003658#msg2003658 )



Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 09-April-2015
  4. ' ***********************************************************************
  5. ' <copyright file="PathUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Explicit On
  13. Option Strict On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Path Util "
  19.  
  20. Namespace Tools
  21.  
  22.    ''' <summary>
  23.    ''' Contains related PATH and PATHEXT registry tools.
  24.    ''' </summary>
  25.    Public NotInheritable Class PathUtil
  26.  
  27. #Region " Properties "
  28.  
  29.        ''' <summary>
  30.        ''' Gets the registry path of the Environment subkey for the current user.
  31.        ''' </summary>
  32.        ''' <value>The registry path of the Environment subkey for the current user.</value>
  33.        Public Shared ReadOnly Property EnvironmentPathCurrentUser As String
  34.            Get
  35.                Return "HKEY_CURRENT_USER\Environment"
  36.            End Get
  37.        End Property
  38.  
  39.        ''' <summary>
  40.        ''' Gets the registry path of the Environment subkey for all users.
  41.        ''' </summary>
  42.        ''' <value>The registry path of the Environment subkey for all users.</value>
  43.        Public Shared ReadOnly Property EnvironmentPathAllUsers As String
  44.            Get
  45.                Return "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
  46.            End Get
  47.        End Property
  48.  
  49.        ''' <summary>
  50.        ''' Gets the default data of the PATH registry value of a 32-Bit Windows.
  51.        ''' </summary>
  52.        ''' <value>The default data of the PATH registry value of a 32-Bit Windows.</value>
  53.        Public Shared ReadOnly Property DefaultPathDataWin32 As String
  54.            Get
  55.                Return "C:\Windows;C:\Windows\System32;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0"
  56.            End Get
  57.        End Property
  58.  
  59.        ''' <summary>
  60.        ''' Gets the default data of the PATH registry value of a 64-Bit Windows.
  61.        ''' </summary>
  62.        ''' <value>The default data of the PATH registry value of a 64-Bit Windows.</value>
  63.        Public Shared ReadOnly Property DefaultPathDataWin64 As String
  64.            Get
  65.                Return "C:\Windows;C:\Windows\System32;C:\Windows\System32\Wbem;C:\Windows\SysWOW64;C:\Windows\System32\WindowsPowerShell\v1.0"
  66.            End Get
  67.        End Property
  68.  
  69.        ''' <summary>
  70.        ''' Gets the default data of the PATHEXt registry value.
  71.        ''' </summary>
  72.        ''' <value>The default data of the PATHEXt registry value.</value>
  73.        Public Shared ReadOnly Property DefaultPathExtData As String
  74.            Get
  75.                Return ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE"
  76.            End Get
  77.        End Property
  78.  
  79.        ''' <summary>
  80.        ''' Gets the registry export string format.
  81.        ''' </summary>
  82.        ''' <value>The registry export string format.</value>
  83.        Private Shared ReadOnly Property ExportStringFormat As String
  84.            Get
  85.                Return "Windows Registry Editor Version 5.00{0}{0}" &
  86.                       "[HKEY_CURRENT_USER\Environment]{0}" &
  87.                       """PATH""=""{1}""{0}" &
  88.                       """PATHEXT""=""{2}""{0}{0}" &
  89.                       "[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]{0}" &
  90.                       """PATH""=""{3}""{0}" &
  91.                       """PATHEXT""=""{4}"""
  92.            End Get
  93.        End Property
  94.  
  95. #End Region
  96.  
  97. #Region " Enumerations "
  98.  
  99.        ''' <summary>
  100.        ''' Specifies the registry user mode.
  101.        ''' </summary>
  102.        Public Enum UserMode
  103.  
  104.            ''' <summary>
  105.            ''' The current user (HKCU).
  106.            ''' </summary>
  107.            Current = 0
  108.  
  109.            ''' <summary>
  110.            ''' All users (HKLM).
  111.            ''' </summary>
  112.            AllUsers = 1
  113.  
  114.        End Enum
  115.  
  116. #End Region
  117.  
  118. #Region " Constructors "
  119.  
  120.        ''' <summary>
  121.        ''' Prevents a default instance of the <see cref="PathUtil"/> class from being created.
  122.        ''' </summary>
  123.        Private Sub New()
  124.        End Sub
  125.  
  126. #End Region
  127.  
  128. #Region " Public Methods "
  129.  
  130.        ''' <summary>
  131.        ''' Gets the default data of the PATH value for the registry of the specified user (as String).
  132.        ''' </summary>
  133.        ''' <returns>The default data of the PATH value for the registry of the specified user.</returns>
  134.        Public Shared Function GetDefaultPathDataString() As String
  135.  
  136.            If Not Environment.Is64BitOperatingSystem Then
  137.                Return DefaultPathDataWin32
  138.            Else
  139.                Return DefaultPathDataWin64
  140.            End If
  141.  
  142.        End Function
  143.  
  144.        ''' <summary>
  145.        ''' Gets the default data of the PATH value for the registry of the specified user (as Enumerable).
  146.        ''' </summary>
  147.        ''' <returns>The default data of the PATH value for the registry of the specified user.</returns>
  148.        Public Shared Function GetDefaultPathDataList() As IEnumerable(Of String)
  149.  
  150.            If Not Environment.Is64BitOperatingSystem Then
  151.                Return DefaultPathDataWin32.Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
  152.            Else
  153.                Return DefaultPathDataWin64.Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
  154.            End If
  155.  
  156.        End Function
  157.  
  158.        ''' <summary>
  159.        ''' Gets the data of the PATH value on the registry of the specified user (as String).
  160.        ''' </summary>
  161.        ''' <param name="userMode">The user mode.</param>
  162.        ''' <returns>The data of the PATH value on the registry of the specified user.</returns>
  163.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  164.        Public Shared Function GetPathDataString(ByVal userMode As UserMode) As String
  165.  
  166.            Select Case userMode
  167.  
  168.                Case PathUtil.UserMode.Current
  169.                    Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH")
  170.  
  171.                Case PathUtil.UserMode.AllUsers
  172.                    Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH")
  173.  
  174.                Case Else
  175.                    Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  176.  
  177.            End Select
  178.  
  179.        End Function
  180.  
  181.        ''' <summary>
  182.        ''' Gets the data of the PATH value on the registry of the specified user (as Enumerable).
  183.        ''' </summary>
  184.        ''' <param name="userMode">The user mode.</param>
  185.        ''' <returns>The data of the PATH value on the registry of the specified user.</returns>
  186.        Public Shared Function GetPathDataList(ByVal userMode As UserMode) As IEnumerable(Of String)
  187.  
  188.            Return GetPathDataString(userMode).Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
  189.  
  190.        End Function
  191.  
  192.        ''' <summary>
  193.        ''' Gets the data of the PATHEXT value on the registry of the specified user (as String).
  194.        ''' </summary>
  195.        ''' <param name="userMode">The user mode.</param>
  196.        ''' <returns>The data of the PATHEXT value on the registry of the specified user.</returns>
  197.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  198.        Public Shared Function GetPathExtDataString(ByVal userMode As UserMode) As String
  199.  
  200.            Select Case userMode
  201.  
  202.                Case PathUtil.UserMode.Current
  203.                    Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT")
  204.  
  205.                Case PathUtil.UserMode.AllUsers
  206.                    Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT")
  207.  
  208.                Case Else
  209.                    Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  210.  
  211.            End Select
  212.  
  213.        End Function
  214.  
  215.        ''' <summary>
  216.        ''' Gets data of the data of the PATHEXT value on the registry of the specified user (as Enumerable).
  217.        ''' </summary>
  218.        ''' <param name="userMode">The user mode.</param>
  219.        ''' <returns>The data of the PATHEXT value on the registry of the specified user.</returns>
  220.        Public Shared Function GetPathExtDataList(ByVal userMode As UserMode) As IEnumerable(Of String)
  221.  
  222.            Return GetPathExtDataString(userMode).Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
  223.  
  224.        End Function
  225.  
  226.        ''' <summary>
  227.        ''' Determines whether the PATH value exists on the registry of the specified user.
  228.        ''' </summary>
  229.        ''' <param name="userMode">The user mode.</param>
  230.        ''' <returns><c>true</c> if PATH value exists, <c>false</c> otherwise.</returns>
  231.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  232.        Public Shared Function PathExists(ByVal userMode As UserMode) As Boolean
  233.  
  234.            Select Case userMode
  235.  
  236.                Case PathUtil.UserMode.Current
  237.                    Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH")
  238.  
  239.                Case PathUtil.UserMode.AllUsers
  240.                    Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH")
  241.  
  242.                Case Else
  243.                    Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  244.  
  245.            End Select
  246.  
  247.        End Function
  248.  
  249.        ''' <summary>
  250.        ''' Determines whether the PATHEXT value exists on the registry of the specified user.
  251.        ''' </summary>
  252.        ''' <param name="userMode">The user mode.</param>
  253.        ''' <returns><c>true</c> if PATHEXT value exists, <c>false</c> otherwise.</returns>
  254.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  255.        Public Shared Function PathExtExists(ByVal userMode As UserMode) As Boolean
  256.  
  257.            Select Case userMode
  258.  
  259.                Case PathUtil.UserMode.Current
  260.                    Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT")
  261.  
  262.                Case PathUtil.UserMode.AllUsers
  263.                    Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT")
  264.  
  265.                Case Else
  266.                    Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  267.  
  268.            End Select
  269.  
  270.        End Function
  271.  
  272.        ''' <summary>
  273.        ''' Exports the PATH and PATHEXT values to a target registry file.
  274.        ''' </summary>
  275.        ''' <param name="filepath">The filepath.</param>
  276.        ''' <exception cref="Exception"></exception>
  277.        Public Shared Sub Export(ByVal filepath As String)
  278.  
  279.            Try
  280.                IO.File.WriteAllText(filepath,
  281.                                     String.Format(ExportStringFormat,
  282.                                                   Environment.NewLine,
  283.                                                   GetPathDataString(UserMode.Current),
  284.                                                   GetPathExtDataString(UserMode.Current),
  285.                                                   GetPathDataString(UserMode.AllUsers),
  286.                                                   GetPathExtDataString(UserMode.AllUsers)),
  287.                                     encoding:=System.Text.Encoding.Unicode)
  288.  
  289.            Catch ex As Exception
  290.                Throw
  291.  
  292.            End Try
  293.  
  294.        End Sub
  295.  
  296.        ''' <summary>
  297.        ''' Creates a PATH value on the registry of the specified user and optionally fills the value with the specified data.
  298.        ''' </summary>
  299.        ''' <param name="userMode">The user mode.</param>
  300.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  301.        Public Shared Sub CreatePath(ByVal userMode As UserMode,
  302.                                     Optional data As String = "")
  303.  
  304.            Try
  305.                Select Case userMode
  306.  
  307.                    Case PathUtil.UserMode.Current
  308.                        RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH", valueData:=data)
  309.  
  310.                    Case PathUtil.UserMode.AllUsers
  311.                        RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH", valueData:=data)
  312.  
  313.                    Case Else
  314.                        Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  315.  
  316.                End Select
  317.  
  318.            Catch ex As Exception
  319.                Throw
  320.  
  321.            End Try
  322.  
  323.        End Sub
  324.  
  325.        ''' <summary>
  326.        ''' Creates a PATHEXT value on the registry of the specified user and optionally fills the value with the specified data..
  327.        ''' </summary>
  328.        ''' <param name="userMode">The user mode.</param>
  329.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  330.        Public Shared Sub CreatePathExt(ByVal userMode As UserMode,
  331.                                        Optional data As String = "")
  332.  
  333.            Try
  334.                Select Case userMode
  335.  
  336.                    Case PathUtil.UserMode.Current
  337.                        RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT", valueData:=data)
  338.  
  339.                    Case PathUtil.UserMode.AllUsers
  340.                        RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT", valueData:=data)
  341.  
  342.                    Case Else
  343.                        Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  344.  
  345.                End Select
  346.  
  347.            Catch ex As Exception
  348.                Throw
  349.  
  350.            End Try
  351.  
  352.        End Sub
  353.  
  354.        ''' <summary>
  355.        ''' Adds a directory into the PATH registry value of the specified user.
  356.        ''' </summary>
  357.        ''' <param name="userMode">The user mode.</param>
  358.        ''' <param name="directory">The directory path.</param>
  359.        ''' <exception cref="ArgumentException">Directory contains invalid character(s).;directory</exception>
  360.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  361.        Public Shared Sub AddDirectory(ByVal userMode As UserMode,
  362.                                       ByVal directory As String)
  363.  
  364.            If directory.Any(Function(c As Char) IO.Path.GetInvalidPathChars.Contains(c)) Then
  365.                Throw New ArgumentException(message:="Directory contains invalid character(s).", paramName:="directory")
  366.  
  367.            Else
  368.  
  369.                Select Case userMode
  370.  
  371.                    Case PathUtil.UserMode.Current
  372.                        RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH",
  373.                                                       valueData:=String.Join(";"c, GetPathDataList(userMode).Concat({directory}).Distinct).Trim(";"c))
  374.  
  375.                    Case PathUtil.UserMode.AllUsers
  376.                        RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH",
  377.                                                       valueData:=String.Join(";"c, GetPathDataList(userMode).Concat({directory}).Distinct).Trim(";"c))
  378.  
  379.                    Case Else
  380.                        Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  381.  
  382.                End Select
  383.  
  384.            End If
  385.  
  386.        End Sub
  387.  
  388.        ''' <summary>
  389.        ''' Adds a file extension into the PATHEXT registry value of the specified user.
  390.        ''' </summary>
  391.        ''' <param name="userMode">The user mode.</param>
  392.        ''' <param name="extension">The file extension.</param>
  393.        ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception>
  394.        Public Shared Sub AddExtension(ByVal userMode As UserMode,
  395.                                       ByVal extension As String)
  396.  
  397.            If Not extension.StartsWith("."c) Then ' Fix extension.
  398.                extension.Insert(0, "."c)
  399.            End If
  400.  
  401.            Select Case userMode
  402.  
  403.                Case PathUtil.UserMode.Current
  404.                    RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT",
  405.                                                   valueData:=String.Join(";"c, GetPathExtDataList(userMode).Concat({extension})).Trim(";"c))
  406.  
  407.                Case PathUtil.UserMode.AllUsers
  408.                    RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT",
  409.                                                   valueData:=String.Join(";"c, GetPathExtDataList(userMode).Concat({extension})).Trim(";"c))
  410.  
  411.                Case Else
  412.                    Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode")
  413.  
  414.            End Select
  415.  
  416.        End Sub
  417.  
  418.        ''' <summary>
  419.        ''' Deletes a directory from the PATH registry value of the specified user.
  420.        ''' </summary>
  421.        ''' <param name="userMode">The user mode.</param>
  422.        ''' <param name="directory">The directory path.</param>
  423.        Public Shared Sub DeleteDirectory(ByVal userMode As UserMode,
  424.                                          ByVal directory As String)
  425.  
  426.            Dim dirs As IEnumerable(Of String) =
  427.                From dir As String In GetPathDataList(userMode)
  428.                Where Not dir.ToLower.Equals(directory, StringComparison.OrdinalIgnoreCase)
  429.  
  430.            CreatePath(userMode, data:=String.Join(";"c, dirs))
  431.  
  432.        End Sub
  433.  
  434.        ''' <summary>
  435.        ''' Deletes a directory from the PATH registry value of the specified user.
  436.        ''' </summary>
  437.        ''' <param name="userMode">The user mode.</param>
  438.        ''' <param name="index">The directory index, 0 = First.</param>
  439.        ''' <exception cref="IndexOutOfRangeException">Directory index is out of range.</exception>
  440.        Public Shared Sub DeleteDirectory(ByVal userMode As UserMode,
  441.                                          ByVal index As Integer)
  442.  
  443.            Dim dirs As List(Of String) = GetPathDataList(userMode).ToList
  444.  
  445.            If (dirs.Count > index) Then
  446.                dirs.RemoveAt(index)
  447.            Else
  448.                Throw New IndexOutOfRangeException(Message:="Directory index is out of range.")
  449.            End If
  450.  
  451.            CreatePath(userMode, data:=String.Join(";"c, dirs))
  452.  
  453.        End Sub
  454.  
  455.        ''' <summary>
  456.        ''' Deletes a file extension from the PATHEXT registry value of the specified user.
  457.        ''' </summary>
  458.        ''' <param name="userMode">The user mode.</param>
  459.        ''' <param name="extension">The file extension.</param>
  460.        Public Shared Sub DeleteExtension(ByVal userMode As UserMode,
  461.                                          ByVal extension As String)
  462.  
  463.            If Not extension.StartsWith("."c) Then ' Fix extension.
  464.                extension.Insert(0, "."c)
  465.            End If
  466.  
  467.            Dim exts As IEnumerable(Of String) =
  468.                From ext As String In GetPathExtDataList(userMode)
  469.                Where Not ext.ToLower.Equals(extension, StringComparison.OrdinalIgnoreCase)
  470.  
  471.            CreatePath(userMode, data:=String.Join(";"c, exts))
  472.  
  473.        End Sub
  474.  
  475.        ''' <summary>
  476.        ''' Deletes a file extension from the PATHEXT registry value of the specified user.
  477.        ''' </summary>
  478.        ''' <param name="userMode">The user mode.</param>
  479.        ''' <param name="index">The file extension index, 0 = First.</param>
  480.        ''' <exception cref="IndexOutOfRangeException">File extension index is out of range.</exception>
  481.        Public Shared Sub DeleteExtension(ByVal userMode As UserMode,
  482.                                          ByVal index As Integer)
  483.  
  484.            Dim exts As List(Of String) = GetPathExtDataList(userMode).ToList
  485.  
  486.            If (exts.Count > index) Then
  487.                exts.RemoveAt(index)
  488.            Else
  489.                Throw New IndexOutOfRangeException(Message:="File extension index is out of range.")
  490.            End If
  491.  
  492.            CreatePathExt(userMode, data:=String.Join(";"c, exts))
  493.  
  494.        End Sub
  495.  
  496.        ''' <summary>
  497.        ''' Determines whether the PATH registry value of the specified user contains a directory.
  498.        ''' </summary>
  499.        ''' <param name="usermode">The usermode.</param>
  500.        ''' <param name="directory">The directory path.</param>
  501.        ''' <returns><c>true</c> if contains the specified directory; <c>false</c> otherwise.</returns>
  502.        Public Shared Function ContainsDirectory(ByVal usermode As UserMode,
  503.                                                 ByVal directory As String) As Boolean
  504.  
  505.            Return GetPathDataList(usermode).Any(Function(dir As String) dir.Equals(directory, StringComparison.OrdinalIgnoreCase))
  506.  
  507.        End Function
  508.  
  509.        ''' <summary>
  510.        ''' Determines whether the PATHEXT registry value of the specified user contains a directory.
  511.        ''' </summary>
  512.        ''' <param name="usermode">The usermode.</param>
  513.        ''' <param name="extension">The file extension.</param>
  514.        ''' <returns><c>true</c> if contains the specified file extension; <c>false</c> otherwise.</returns>
  515.        Public Shared Function ContainsExtension(ByVal usermode As UserMode,
  516.                                                 ByVal extension As String) As Boolean
  517.  
  518.            If Not extension.StartsWith("."c) Then ' Fix extension.
  519.                extension.Insert(0, "."c)
  520.            End If
  521.  
  522.            Return GetPathExtDataList(usermode).Any(Function(ext As String) ext.Equals(extension, StringComparison.OrdinalIgnoreCase))
  523.  
  524.        End Function
  525.  
  526. #End Region
  527.  
  528.    End Class
  529.  
  530. End Namespace
  531.  
  532. #End Region
  533.  


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #462 en: 2 Junio 2015, 09:56 am »

Una Class para administrar un archivo de recursos de .Net ( file.resx )

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-March-2015
  4. ' ***********************************************************************
  5. ' <copyright file="ResXManager.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Strict On
  13. Option Explicit On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Usage Examples "
  19.  
  20. 'Imports System.IO
  21. 'Imports System.Text
  22.  
  23. 'Public Class Form1
  24.  
  25. '    Private Sub Test() Handles MyBase.Shown
  26.  
  27. '        Dim resX As New ResXManager(Path.Combine(Application.StartupPath, "MyResources.resx"))
  28. '        With resX
  29.  
  30. '            ' Create or replace the ResX file.
  31. '            .Create(replace:=True)
  32.  
  33. '            ' Add a string resource.
  34. '            .AddResource(Of String)("String Resource", "Hello World!", "String Comment")
  35. '            ' Add a bitmap resource.
  36. '            .AddResource(Of Bitmap)("Bitmap Resource", SystemIcons.Information.ToBitmap, "Bitmap Comment")
  37. '            ' Add a binary resource.
  38. '            .AddResource(Of Byte())("Binary Resource", File.ReadAllBytes("C:\file.mp3"), "Binary Comment")
  39.  
  40. '        End With
  41.  
  42. '        ' *******************************************************************************************************
  43.  
  44. '        ' Get the string resource.
  45. '        Dim stringResource As ResXManager.Resource(Of String) =
  46. '            resX.FindResource(Of String)("String Resource", StringComparison.OrdinalIgnoreCase)
  47.  
  48. '        ' Get the bitmap resource.
  49. '        Dim bitmapResource As ResXManager.Resource(Of Bitmap) =
  50. '            resX.FindResource(Of Bitmap)("Bitmap Resource", StringComparison.OrdinalIgnoreCase)
  51.  
  52. '        ' Get the binary resource.
  53. '        Dim binaryResource As ResXManager.Resource(Of Byte()) =
  54. '            resX.FindResource(Of Byte())("Binary Resource", StringComparison.OrdinalIgnoreCase)
  55.  
  56. '        ' *******************************************************************************************************
  57.  
  58. '        ' Get the string data.
  59. '        Dim stringData As String = stringResource.Data
  60.  
  61. '        ' Get the bitmap data.
  62. '        Dim bitmapData As Bitmap = bitmapResource.Data
  63.  
  64. '        ' Get the binary data.
  65. '        Dim binaryData As Byte() = binaryResource.Data
  66.  
  67. '        ' *******************************************************************************************************
  68.  
  69. '        ' Get all the resources at once.
  70. '        Dim resources As IEnumerable(Of ResXManager.Resource) = resX.Resources
  71.  
  72. '        ' Get all the resources of specific Type at once.
  73. '        Dim stringResources As IEnumerable(Of ResXManager.Resource(Of String)) = resX.FindResources(Of String)()
  74.  
  75. '        ' *******************************************************************************************************
  76.  
  77. '        ' Get all the resource datas at once from Resource collection.
  78. '        Dim resourceDatas As IEnumerable(Of Object) =
  79. '            From res As ResXManager.Resource In resX.Resources
  80. '            Select res.Data
  81.  
  82. '        ' Get all the resource datas of specific Type at once from Resource collection.
  83. '        Dim stringResourceDatas As IEnumerable(Of String) =
  84. '            From res As ResXManager.Resource In resX.Resources
  85. '            Where res.Type Is GetType(String)
  86. '            Select DirectCast(res.Data, String)
  87.  
  88. '        ' *******************************************************************************************************
  89.  
  90. '        ' Treat the string data as you like.
  91. '        MessageBox.Show(stringData, String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information)
  92.  
  93. '        ' Treat the bitmap data as you like.
  94. '        Me.Icon = Icon.FromHandle(bitmapData.GetHicon)
  95.  
  96. '        ' Treat the binary data as you like.
  97. '        File.WriteAllBytes("C:\new file.mp3", binaryData)
  98.  
  99. '        ' *******************************************************************************************************
  100.  
  101. '        ' Iterate all the resources.
  102. '        For Each res As ResXManager.Resource In resX.Resources
  103.  
  104. '            Dim sb As New StringBuilder
  105.  
  106. '            sb.AppendLine(String.Format("Name...: {0}", res.Name))
  107. '            sb.AppendLine(String.Format("Comment: {0}", res.Comment))
  108. '            sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString))
  109. '            sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString))
  110.  
  111. '            MsgBox(sb.ToString)
  112. '        Next
  113.  
  114. '        ' Iterate all the resources of specific Type.
  115. '        For Each res As ResXManager.Resource(Of String) In resX.FindResources(Of String)()
  116.  
  117. '            Dim sb As New StringBuilder
  118.  
  119. '            sb.AppendLine(String.Format("Name...: {0}", res.Name))
  120. '            sb.AppendLine(String.Format("Comment: {0}", res.Comment))
  121. '            sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString))
  122. '            sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString))
  123.  
  124. '            MsgBox(sb.ToString)
  125. '        Next
  126.  
  127. '        ' *******************************************************************************************************
  128.  
  129. '        ' Remove a resource.
  130. '        resX.RemoveResource("Binary Resource")
  131.  
  132. '        '  GC.Collect()
  133.  
  134. '    End Sub
  135.  
  136. 'End Class
  137.  
  138. #End Region
  139.  
  140. #Region " Imports "
  141.  
  142. Imports System.ComponentModel
  143. Imports System.ComponentModel.Design
  144. Imports System.IO
  145. Imports System.Resources
  146.  
  147. #End Region
  148.  
  149. ''' <summary>
  150. ''' Manages a .Net managed resource file.
  151. ''' </summary>
  152. Public NotInheritable Class ResXManager
  153.  
  154. #Region " Properties "
  155.  
  156.    ''' <summary>
  157.    ''' Gets the .Net managed resource file path.
  158.    ''' </summary>
  159.    ''' <value>The .Net managed resource filepath.</value>
  160.    Public ReadOnly Property FilePath As String
  161.        Get
  162.            Return Me.filePath1
  163.        End Get
  164.    End Property
  165.    ''' <summary>
  166.    ''' The .Net managed resource file path.
  167.    ''' </summary>
  168.    Private ReadOnly filePath1 As String
  169.  
  170.    ''' <summary>
  171.    ''' Gets the resources contained in the .Net managed resource file.
  172.    ''' </summary>
  173.    ''' <value>The resources.</value>
  174.    Public ReadOnly Property Resources As IEnumerable(Of Resource)
  175.        Get
  176.            Return GetResources()
  177.        End Get
  178.    End Property
  179.  
  180. #End Region
  181.  
  182. #Region " Types "
  183.  
  184. #Region " Resource "
  185.  
  186.    ''' <summary>
  187.    ''' Defines a resource of a .Net managed resource file.
  188.    ''' </summary>
  189.    <Serializable>
  190.    Public NotInheritable Class Resource
  191.  
  192. #Region " Properties "
  193.  
  194.        ''' <summary>
  195.        ''' Gets the resource name.
  196.        ''' </summary>
  197.        ''' <value>The resource name.</value>
  198.        Public ReadOnly Property Name As String
  199.            Get
  200.                Return Me.name1
  201.            End Get
  202.        End Property
  203.        Private ReadOnly name1 As String
  204.  
  205.        ''' <summary>
  206.        ''' Gets the resource data.
  207.        ''' </summary>
  208.        ''' <value>The resource data.</value>
  209.        Public ReadOnly Property Data As Object
  210.            Get
  211.                Return Me.data1
  212.            End Get
  213.        End Property
  214.        Private ReadOnly data1 As Object
  215.  
  216.        ''' <summary>
  217.        ''' Gets the resource type.
  218.        ''' </summary>
  219.        ''' <value>The resource type.</value>
  220.        Public ReadOnly Property Type As Type
  221.            Get
  222.                Return Data.GetType
  223.            End Get
  224.        End Property
  225.  
  226.        ''' <summary>
  227.        ''' Gets the resource comment.
  228.        ''' </summary>
  229.        ''' <value>The resource comment.</value>
  230.        Public ReadOnly Property Comment As String
  231.            Get
  232.                Return comment1
  233.            End Get
  234.        End Property
  235.        Private ReadOnly comment1 As String
  236.  
  237.        ''' <summary>
  238.        ''' Represents a <see cref="Resource"/> instance that is <c>Nothing</c>.
  239.        ''' </summary>
  240.        ''' <value><c>Nothing</c></value>
  241.        <EditorBrowsable(EditorBrowsableState.Advanced)>
  242.        Public Shared ReadOnly Property Empty As Resource
  243.            Get
  244.                Return Nothing
  245.            End Get
  246.        End Property
  247.  
  248. #End Region
  249.  
  250. #Region " Constructors "
  251.  
  252.        ''' <summary>
  253.        ''' Initializes a new instance of the <see cref="Resource"/> class.
  254.        ''' </summary>
  255.        ''' <param name="name">The resource name.</param>
  256.        ''' <param name="data">The resource data.</param>
  257.        ''' <param name="comment">The resource comment.</param>
  258.        Public Sub New(ByVal name As String,
  259.                       ByVal data As Object,
  260.                       ByVal comment As String)
  261.  
  262.            Me.name1 = name
  263.            Me.data1 = data
  264.            Me.comment1 = comment
  265.  
  266.        End Sub
  267.  
  268.        ''' <summary>
  269.        ''' Prevents a default instance of the <see cref="Resource"/> class from being created.
  270.        ''' </summary>
  271.        Private Sub New()
  272.        End Sub
  273.  
  274. #End Region
  275.  
  276. #Region " Hidden Methods "
  277.  
  278.        ''' <summary>
  279.        ''' Determines whether the specified System.Object instances are considered equal.
  280.        ''' </summary>
  281.        <EditorBrowsable(EditorBrowsableState.Never)>
  282.        Public Shadows Function Equals(ByVal obj As Object) As Boolean
  283.            Return MyBase.Equals(obj)
  284.        End Function
  285.  
  286.        ''' <summary>
  287.        ''' Serves as a hash function for a particular type.
  288.        ''' </summary>
  289.        <EditorBrowsable(EditorBrowsableState.Never)>
  290.        Public Shadows Function GetHashCode() As Integer
  291.            Return MyBase.GetHashCode
  292.        End Function
  293.  
  294.        ''' <summary>
  295.        ''' Gets the System.Type of the current instance.
  296.        ''' </summary>
  297.        ''' <returns>The exact runtime type of the current instance.</returns>
  298.        <EditorBrowsable(EditorBrowsableState.Never)>
  299.        Public Shadows Function [GetType]() As Type
  300.            Return MyBase.GetType
  301.        End Function
  302.  
  303.        ''' <summary>
  304.        ''' Returns a String that represents the current object.
  305.        ''' </summary>
  306.        <EditorBrowsable(EditorBrowsableState.Never)>
  307.        Public Shadows Function ToString() As String
  308.            Return MyBase.ToString
  309.        End Function
  310.  
  311. #End Region
  312.  
  313.    End Class
  314.  
  315. #End Region
  316.  
  317. #Region " Resource(Of T) "
  318.  
  319.    ''' <summary>
  320.    ''' Defines a resource of a .Net managed resource file.
  321.    ''' </summary>
  322.    <Serializable>
  323.    Public NotInheritable Class Resource(Of T)
  324.  
  325. #Region " Properties "
  326.  
  327.        ''' <summary>
  328.        ''' Gets the resource name.
  329.        ''' </summary>
  330.        ''' <value>The resource name.</value>
  331.        Public ReadOnly Property Name As String
  332.            Get
  333.                Return Me.name1
  334.            End Get
  335.        End Property
  336.        Private ReadOnly name1 As String
  337.  
  338.        ''' <summary>
  339.        ''' Gets the resource data.
  340.        ''' </summary>
  341.        ''' <value>The resource data.</value>
  342.        Public ReadOnly Property Data As T
  343.            Get
  344.                Return Me.data1
  345.            End Get
  346.        End Property
  347.        Private ReadOnly data1 As T
  348.  
  349.        ''' <summary>
  350.        ''' Gets the resource type.
  351.        ''' </summary>
  352.        ''' <value>The resource type.</value>
  353.        Public ReadOnly Property Type As Type
  354.            Get
  355.                Return GetType(T)
  356.            End Get
  357.        End Property
  358.  
  359.        ''' <summary>
  360.        ''' Gets the resource comment.
  361.        ''' </summary>
  362.        ''' <value>The resource comment.</value>
  363.        Public ReadOnly Property Comment As String
  364.            Get
  365.                Return comment1
  366.            End Get
  367.        End Property
  368.        Private ReadOnly comment1 As String
  369.  
  370. #End Region
  371.  
  372. #Region " Constructors "
  373.  
  374.        ''' <summary>
  375.        ''' Initializes a new instance of the <see cref="Resource(Of T)"/> class.
  376.        ''' </summary>
  377.        ''' <param name="name">The resource name.</param>
  378.        ''' <param name="data">The resource data.</param>
  379.        ''' <param name="comment">The resource comment.</param>
  380.        Public Sub New(ByVal name As String,
  381.                       ByVal data As T,
  382.                       ByVal comment As String)
  383.  
  384.            Me.name1 = name
  385.            Me.data1 = data
  386.            Me.comment1 = comment
  387.  
  388.        End Sub
  389.  
  390.        ''' <summary>
  391.        ''' Prevents a default instance of the <see cref="Resource(Of T)"/> class from being created.
  392.        ''' </summary>
  393.        Private Sub New()
  394.        End Sub
  395.  
  396. #End Region
  397.  
  398. #Region " Hidden Methods "
  399.  
  400.        ''' <summary>
  401.        ''' Determines whether the specified System.Object instances are considered equal.
  402.        ''' </summary>
  403.        <EditorBrowsable(EditorBrowsableState.Never)>
  404.        Public Shadows Function Equals(ByVal obj As Object) As Boolean
  405.            Return MyBase.Equals(obj)
  406.        End Function
  407.  
  408.        ''' <summary>
  409.        ''' Serves as a hash function for a particular type.
  410.        ''' </summary>
  411.        <EditorBrowsable(EditorBrowsableState.Never)>
  412.        Public Shadows Function GetHashCode() As Integer
  413.            Return MyBase.GetHashCode
  414.        End Function
  415.  
  416.        ''' <summary>
  417.        ''' Gets the System.Type of the current instance.
  418.        ''' </summary>
  419.        ''' <returns>The exact runtime type of the current instance.</returns>
  420.        <EditorBrowsable(EditorBrowsableState.Never)>
  421.        Public Shadows Function [GetType]() As Type
  422.            Return MyBase.GetType
  423.        End Function
  424.  
  425.        ''' <summary>
  426.        ''' Returns a String that represents the current object.
  427.        ''' </summary>
  428.        <EditorBrowsable(EditorBrowsableState.Never)>
  429.        Public Shadows Function ToString() As String
  430.            Return MyBase.ToString
  431.        End Function
  432.  
  433. #End Region
  434.  
  435.    End Class
  436.  
  437. #End Region
  438.  
  439. #End Region
  440.  
  441. #Region " Constructors "
  442.  
  443.    ''' <summary>
  444.    ''' Initializes a new instance of the <see cref="ResXManager"/> class.
  445.    ''' </summary>
  446.    ''' <param name="resxFilePath">The .Net managed resource filepath.</param>
  447.    Public Sub New(ByVal resxFilePath As String)
  448.        Me.filePath1 = resxFilePath
  449.    End Sub
  450.  
  451.    ''' <summary>
  452.    ''' Prevents a default instance of the <see cref="ResXManager"/> class from being created.
  453.    ''' </summary>
  454.    Private Sub New()
  455.    End Sub
  456.  
  457. #End Region
  458.  
  459. #Region " Public Methods "
  460.  
  461.    ''' <summary>
  462.    ''' Creates the .Net managed resource file.
  463.    ''' </summary>
  464.    ''' <param name="replace">if set to <c>true</c>, replaces any existent file.</param>
  465.    ''' <exception cref="System.Exception"></exception>
  466.    Public Sub Create(Optional ByVal replace As Boolean = False)
  467.  
  468.        If Not replace AndAlso File.Exists(Me.filePath1) Then
  469.            Throw New Exception(String.Format("Resource file already exists: {0}", Me.filePath1))
  470.            Exit Sub
  471.        End If
  472.  
  473.        Dim resXWritter As ResXResourceWriter = Nothing
  474.        Try
  475.            resXWritter = New ResXResourceWriter(Me.filePath1)
  476.            Using resXWritter
  477.                resXWritter.Generate()
  478.            End Using
  479.  
  480.        Catch ex As Exception
  481.            Throw
  482.  
  483.        Finally
  484.            If resXWritter IsNot Nothing Then
  485.                resXWritter.Close()
  486.            End If
  487.  
  488.        End Try
  489.  
  490.    End Sub
  491.  
  492.    ''' <summary>
  493.    ''' Adds a resource into the .Net managed resource file.
  494.    ''' </summary>
  495.    ''' <param name="name">The resource name.</param>
  496.    ''' <param name="data">The resource data.</param>
  497.    ''' <param name="comment">The resource comment.</param>
  498.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  499.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  500.    Public Sub AddResource(ByVal name As String,
  501.                           ByVal data As Object,
  502.                           Optional ByVal comment As String = Nothing)
  503.  
  504.        Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment)
  505.  
  506.    End Sub
  507.  
  508.    ''' <summary>
  509.    ''' Adds a specified resource of the specified type into the .Net managed resource file.
  510.    ''' </summary>
  511.    ''' <typeparam name="T"></typeparam>
  512.    ''' <param name="name">The resource name.</param>
  513.    ''' <param name="data">The resource data.</param>
  514.    ''' <param name="comment">The resource comment.</param>
  515.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  516.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  517.    Public Sub AddResource(Of T)(ByVal name As String,
  518.                                 ByVal data As T,
  519.                                 Optional ByVal comment As String = Nothing)
  520.  
  521.        Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment)
  522.  
  523.    End Sub
  524.  
  525.    ''' <summary>
  526.    ''' Replaces a resource by the specified name inside the .Net managed resource file.
  527.    ''' </summary>
  528.    ''' <param name="name">The resource name.</param>
  529.    ''' <param name="data">The resource data.</param>
  530.    ''' <param name="comment">The resource comment.</param>
  531.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  532.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  533.    Public Sub ReplaceResource(ByVal name As String,
  534.                               ByVal data As Object,
  535.                               Optional ByVal comment As String = Nothing)
  536.  
  537.        Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment)
  538.  
  539.    End Sub
  540.  
  541.    ''' <summary>
  542.    ''' Replaces a resource by the specified name of the specified type inside the .Net managed resource file.
  543.    ''' </summary>
  544.    ''' <typeparam name="T"></typeparam>
  545.    ''' <param name="name">The resource name.</param>
  546.    ''' <param name="data">The resource data.</param>
  547.    ''' <param name="comment">The resource comment.</param>
  548.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  549.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  550.    Public Sub ReplaceResource(Of T)(ByVal name As String,
  551.                                     ByVal data As T,
  552.                                     Optional ByVal comment As String = Nothing)
  553.  
  554.        Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment)
  555.  
  556.    End Sub
  557.  
  558.    ''' <summary>
  559.    ''' Finds a resource by the specified name of specified type inside the .Net managed resource file.
  560.    ''' </summary>
  561.    ''' <typeparam name="T"></typeparam>
  562.    ''' <param name="name">The resource name.</param>
  563.    ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
  564.    ''' <returns>The resource.</returns>
  565.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  566.    ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
  567.    ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
  568.    Public Function FindResource(Of T)(ByVal name As String,
  569.                                       Optional ByVal stringComparison As StringComparison =
  570.                                                      StringComparison.OrdinalIgnoreCase) As Resource(Of T)
  571.  
  572.        If Not File.Exists(Me.filePath1) Then
  573.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  574.            Exit Function
  575.        End If
  576.  
  577.        ' Read the ResX file.
  578.        Dim resX As ResXResourceReader = Nothing
  579.        Dim res As Resource(Of T) = Nothing
  580.        Try
  581.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  582.            Using resX
  583.  
  584.                For Each entry As DictionaryEntry In resX
  585.  
  586.                    If entry.Key.ToString.Equals(name, stringComparison) Then
  587.  
  588.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  589.  
  590.                        res = New Resource(Of T)(name:=node.Name,
  591.                                                 data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T),
  592.                                                 comment:=node.Comment)
  593.                        Exit For
  594.  
  595.                    End If
  596.  
  597.                Next entry
  598.  
  599.            End Using ' resX
  600.  
  601.            Return res
  602.  
  603.        Catch ex As Exception
  604.            Throw
  605.  
  606.        Finally
  607.            If resX IsNot Nothing Then
  608.                resX.Close()
  609.            End If
  610.  
  611.        End Try
  612.  
  613.    End Function
  614.  
  615.    ''' <summary>
  616.    ''' Finds a resource by the specified name inside the .Net managed resource file.
  617.    ''' </summary>
  618.    ''' <param name="name">The resource name.</param>
  619.    ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
  620.    ''' <returns>The resource.</returns>
  621.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  622.    ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
  623.    ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
  624.    Public Function FindResource(ByVal name As String,
  625.                                 Optional ByVal stringComparison As StringComparison =
  626.                                                StringComparison.OrdinalIgnoreCase) As Resource
  627.  
  628.        If Not File.Exists(Me.filePath1) Then
  629.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  630.            Exit Function
  631.        End If
  632.  
  633.        ' Read the ResX file.
  634.        Dim resX As ResXResourceReader = Nothing
  635.        Dim res As Resource = Nothing
  636.        Try
  637.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  638.            Using resX
  639.  
  640.                For Each entry As DictionaryEntry In resX
  641.  
  642.                    If entry.Key.ToString.Equals(name, stringComparison) Then
  643.  
  644.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  645.  
  646.                        res = New Resource(name:=node.Name,
  647.                                           data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)),
  648.                                           comment:=node.Comment)
  649.                        Exit For
  650.  
  651.                    End If
  652.  
  653.                Next entry
  654.  
  655.            End Using ' resX
  656.  
  657.            Return res
  658.  
  659.        Catch ex As Exception
  660.            Throw
  661.  
  662.        Finally
  663.            If resX IsNot Nothing Then
  664.                resX.Close()
  665.            End If
  666.  
  667.        End Try
  668.  
  669.    End Function
  670.  
  671.    ''' <summary>
  672.    ''' Finds the resources of the specified type inside the .Net managed resource file.
  673.    ''' </summary>
  674.    ''' <typeparam name="T"></typeparam>
  675.    ''' <returns>The resource.</returns>
  676.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  677.    ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
  678.    ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
  679.    Public Iterator Function FindResources(Of T)() As IEnumerable(Of Resource(Of T))
  680.  
  681.        If Not File.Exists(Me.filePath1) Then
  682.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  683.            Exit Function
  684.        End If
  685.  
  686.        ' Read the ResX file.
  687.        Dim resX As ResXResourceReader = Nothing
  688.        Try
  689.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  690.            Using resX
  691.  
  692.                For Each entry As DictionaryEntry In resX
  693.  
  694.                    Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  695.  
  696.                    If node.GetValue(DirectCast(Nothing, ITypeResolutionService)).GetType Is GetType(T) Then
  697.  
  698.                        Yield New Resource(Of T)(name:=node.Name,
  699.                                           data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T),
  700.                                           comment:=node.Comment)
  701.  
  702.                    End If
  703.  
  704.                Next entry
  705.  
  706.            End Using ' resX
  707.  
  708.        Catch ex As Exception
  709.            Throw
  710.  
  711.        Finally
  712.            If resX IsNot Nothing Then
  713.                resX.Close()
  714.            End If
  715.  
  716.        End Try
  717.  
  718.    End Function
  719.  
  720.    ''' <summary>
  721.    ''' Removes a resource by the specified name from the .Net managed resource file.
  722.    ''' </summary>
  723.    ''' <param name="name">The resource name.</param>
  724.    ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
  725.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  726.    ''' <exception cref="System.ArgumentException">Any resource found matching the specified name.;name</exception>
  727.    Public Sub RemoveResource(ByVal name As String,
  728.                              Optional ByVal stringComparison As StringComparison =
  729.                                             StringComparison.OrdinalIgnoreCase)
  730.  
  731.        If Not File.Exists(Me.filePath1) Then
  732.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  733.            Exit Sub
  734.        End If
  735.  
  736.        If Me.FindResource(name, stringComparison) Is Nothing Then
  737.            Throw New ArgumentException("Any resource found matching the specified name.", "name")
  738.            Exit Sub
  739.        End If
  740.  
  741.        Dim resources As New List(Of ResXDataNode)
  742.        Dim resX As ResXResourceReader = Nothing
  743.        Dim resXWritter As ResXResourceWriter = Nothing
  744.  
  745.        Try
  746.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  747.            Using resX
  748.  
  749.                For Each entry As DictionaryEntry In resX
  750.  
  751.                    If Not entry.Key.ToString.Equals(name, stringComparison) Then
  752.  
  753.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  754.                        resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment})
  755.  
  756.                    End If
  757.  
  758.                Next entry
  759.  
  760.            End Using
  761.  
  762.            ' Add the resource in the ResX file.
  763.            ' Note: This will replace the current ResX file.
  764.            resXWritter = New ResXResourceWriter(Me.filePath1)
  765.            Using resXWritter
  766.  
  767.                ' Add the retrieved resources into the ResX file.
  768.                If resources IsNot Nothing Then
  769.                    For Each resourceItem As ResXDataNode In resources
  770.                        resXWritter.AddResource(resourceItem)
  771.                    Next resourceItem
  772.                End If
  773.  
  774.                resXWritter.Generate()
  775.  
  776.            End Using ' resXWritter
  777.  
  778.        Catch ex As Exception
  779.            Throw
  780.  
  781.        Finally
  782.            If resX IsNot Nothing Then
  783.                resX.Close()
  784.            End If
  785.  
  786.            If resXWritter IsNot Nothing Then
  787.                resXWritter.Close()
  788.            End If
  789.  
  790.            resources.Clear()
  791.  
  792.        End Try
  793.  
  794.    End Sub
  795.  
  796. #End Region
  797.  
  798. #Region " Private Methods "
  799.  
  800.    ''' <summary>
  801.    ''' Adds or replaces a resource into the .Net managed resource file.
  802.    ''' </summary>
  803.    ''' <param name="replace">if set to <c>true</c>, the resource will be replaced.</param>
  804.    ''' <param name="name">The resource name.</param>
  805.    ''' <param name="data">The resource data.</param>
  806.    ''' <param name="comment">The resource comment.</param>
  807.    ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
  808.    ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
  809.    Private Sub AddResource(ByVal replace As Boolean,
  810.                            ByVal name As String,
  811.                            ByVal data As Object,
  812.                            ByVal comment As String)
  813.  
  814.        If Not File.Exists(Me.filePath1) Then
  815.            Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
  816.            Exit Sub
  817.        End If
  818.  
  819.        Dim resources As New List(Of ResXDataNode)
  820.        Dim resX As ResXResourceReader = Nothing
  821.        Dim resXWritter As ResXResourceWriter = Nothing
  822.  
  823.        Try
  824.            resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  825.            Using resX
  826.  
  827.                For Each entry As DictionaryEntry In resX
  828.  
  829.                    If Not replace AndAlso entry.Key.ToString.Equals(name, StringComparison.OrdinalIgnoreCase) Then
  830.                        Throw New ArgumentException("A resource with the same name already exists in the table.", "name")
  831.  
  832.                    Else
  833.                        Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  834.                        resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment})
  835.  
  836.                    End If
  837.  
  838.                Next entry
  839.  
  840.            End Using
  841.  
  842.            ' Add the resource in the ResX file.
  843.            ' Note: This will replace the current ResX file.
  844.            resXWritter = New ResXResourceWriter(Me.filePath1)
  845.            Using resXWritter
  846.  
  847.                ' Add the retrieved resources into the ResX file.
  848.                If resources IsNot Nothing Then
  849.                    For Each resourceItem As ResXDataNode In resources
  850.                        resXWritter.AddResource(resourceItem)
  851.                    Next resourceItem
  852.                End If
  853.  
  854.                ' Add the specified resource into the ResX file.
  855.                resXWritter.AddResource(New ResXDataNode(name, data) With {.Name = name, .Comment = comment})
  856.                resXWritter.Generate()
  857.  
  858.            End Using ' resXWritter
  859.  
  860.        Catch ex As Exception
  861.            Throw
  862.  
  863.        Finally
  864.            If resX IsNot Nothing Then
  865.                resX.Close()
  866.            End If
  867.  
  868.            If resXWritter IsNot Nothing Then
  869.                resXWritter.Close()
  870.            End If
  871.  
  872.            resources.Clear()
  873.  
  874.        End Try
  875.  
  876.    End Sub
  877.  
  878.    ''' <summary>
  879.    ''' Gets all the resources contained in the .Net managed resource file.
  880.    ''' </summary>
  881.    ''' <returns>IEnumerable(Of Resource).</returns>
  882.    Private Iterator Function GetResources() As IEnumerable(Of Resource)
  883.  
  884.        ' Read the ResX file.
  885.        Using resX As New Resources.ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
  886.  
  887.            For Each entry As DictionaryEntry In resX
  888.  
  889.                Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
  890.  
  891.                Yield New Resource(name:=node.Name,
  892.                                   data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)),
  893.                                   comment:=node.Comment)
  894.  
  895.            Next entry
  896.  
  897.        End Using ' resX
  898.  
  899.    End Function
  900.  
  901. #End Region
  902.  
  903. #Region " Hidden Methods "
  904.  
  905.    ''' <summary>
  906.    ''' Determines whether the specified System.Object instances are considered equal.
  907.    ''' </summary>
  908.    <EditorBrowsable(EditorBrowsableState.Never)>
  909.    Public Shadows Function Equals(ByVal obj As Object) As Boolean
  910.        Return MyBase.Equals(obj)
  911.    End Function
  912.  
  913.    ''' <summary>
  914.    ''' Serves as a hash function for a particular type.
  915.    ''' </summary>
  916.    <EditorBrowsable(EditorBrowsableState.Never)>
  917.    Public Shadows Function GetHashCode() As Integer
  918.        Return MyBase.GetHashCode
  919.    End Function
  920.  
  921.    ''' <summary>
  922.    ''' Gets the System.Type of the current instance.
  923.    ''' </summary>
  924.    ''' <returns>The exact runtime type of the current instance.</returns>
  925.    <EditorBrowsable(EditorBrowsableState.Never)>
  926.    Public Shadows Function [GetType]() As Type
  927.        Return MyBase.GetType
  928.    End Function
  929.  
  930.    ''' <summary>
  931.    ''' Returns a String that represents the current object.
  932.    ''' </summary>
  933.    <EditorBrowsable(EditorBrowsableState.Never)>
  934.    Public Shadows Function ToString() As String
  935.        Return MyBase.ToString
  936.    End Function
  937.  
  938. #End Region
  939.  
  940. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #463 en: 7 Junio 2015, 10:41 am »

Un aspecto para utilizar con la librería Postsharp, para difundir un poquito la programación orientada a aspectos (AOP).

Este aspecto en particular sirve para definir un valor mínimo y máximo para un miembro público de una class (Ej: Una propiedad Byte, Short, Integer, Long, etc...),
con esto nos aseguramos de que el valor asignado nunca supere el máximo ...ni el mínimo.

Hay bastante repetición de código ya que al parecer la Class no se puede hacer genérica.

Ejemplo de uso:
Código
  1. Imports PostSharp.Aspects
  2.  
  3. Public Class MyClass
  4.  
  5.    <RangeAttribute(0S, SByte.MaxValue)>
  6.    Dim sByteValue As SByte
  7.  
  8.    <RangeAttribute(0S, Byte.MaxValue)>
  9.    Dim ByteValue As Byte
  10.  
  11.    <RangeAttribute(0S, Short.MaxValue)>
  12.    Dim Int16Value As Short
  13.  
  14.    <RangeAttribute(0US, UShort.MaxValue)>
  15.    Dim UInt16Value As UShort
  16.  
  17.    <RangeAttribute(0I, Integer.MaxValue)>
  18.    Dim Int32Value As Integer
  19.  
  20.    <RangeAttribute(0UI, UInteger.MaxValue)>
  21.    Dim UInt32Value As UInteger
  22.  
  23.    <RangeAttribute(0L, Long.MaxValue)>
  24.    Dim Int64Value As Long
  25.  
  26.    <RangeAttribute(0UL, ULong.MaxValue)>
  27.    Dim UInt64Value As ULong
  28.  
  29.    <RangeAttribute(0.0F, Single.MaxValue)>
  30.    Dim SglValue As Single
  31.  
  32.    <RangeAttribute(0.0R, Double.MaxValue)>
  33.    Dim DblValue As Double
  34.  
  35. End Class

Código fuente:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 07-June-2015
  4. ' ***********************************************************************
  5. ' <copyright file="RangeAttribute.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Imports PostSharp.Aspects
  13. '
  14. 'Public Class Myclass
  15. '
  16. '    <RangeAttribute(0S, SByte.MaxValue)>
  17. '    Dim sByteValue As SByte
  18. '
  19. '    <RangeAttribute(0S, Byte.MaxValue)>
  20. '    Dim ByteValue As Byte
  21. '
  22. '    <RangeAttribute(0S, Short.MaxValue)>
  23. '    Dim Int16Value As Short
  24. '
  25. '    <RangeAttribute(0US, UShort.MaxValue)>
  26. '    Dim UInt16Value As UShort
  27. '
  28. '    <RangeAttribute(0I, Integer.MaxValue)>
  29. '    Dim Int32Value As Integer
  30. '
  31. '    <RangeAttribute(0UI, UInteger.MaxValue)>
  32. '    Dim UInt32Value As UInteger
  33. '
  34. '    <RangeAttribute(0L, Long.MaxValue)>
  35. '    Dim Int64Value As Long
  36. '
  37. '    <RangeAttribute(0UL, ULong.MaxValue)>
  38. '    Dim UInt64Value As ULong
  39. '
  40. '    <RangeAttribute(0.0F, Single.MaxValue)>
  41. '    Dim SglValue As Single
  42. '
  43. '    <RangeAttribute(0.0R, Double.MaxValue)>
  44. '    Dim DblValue As Double
  45. '
  46. 'End Class
  47.  
  48. #End Region
  49.  
  50. #Region " Imports "
  51.  
  52. Imports PostSharp.Aspects
  53.  
  54. #End Region
  55.  
  56. #Region " Range Attribute "
  57.  
  58. ''' <summary>
  59. ''' Aspect that when applied to a property, defines its minimum and maximum value.
  60. ''' </summary>
  61. <Serializable>
  62. Public Class RangeAttribute : Inherits LocationInterceptionAspect
  63.  
  64. #Region " Properties "
  65.  
  66.    ''' <summary>
  67.    ''' Gets or sets the minimum value.
  68.    ''' </summary>
  69.    Private Property Min As Object
  70.  
  71.    ''' <summary>
  72.    ''' Gets or sets the maximum value.
  73.    ''' </summary>
  74.    Private Property Max As Object
  75.  
  76. #End Region
  77.  
  78. #Region " Constructors "
  79.  
  80.    ''' <summary>
  81.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="SByte"/> datatype.
  82.    ''' </summary>
  83.    ''' <param name="minInt8">The minimum <see cref="SByte"/> value.</param>
  84.    ''' <param name="maxInt8">The maximum <see cref="SByte"/> value.</param>
  85.    Public Sub New(ByVal minInt8 As SByte, ByVal maxInt8 As SByte)
  86.  
  87.        Me.Min = minInt8
  88.        Me.Max = maxInt8
  89.  
  90.    End Sub
  91.  
  92.    ''' <summary>
  93.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Byte"/> datatype.
  94.    ''' </summary>
  95.    ''' <param name="minUInt8">The minimum <see cref="Byte"/> value.</param>
  96.    ''' <param name="maxUInt8">The maximum <see cref="Byte"/> value.</param>
  97.    Public Sub New(ByVal minUInt8 As Byte, ByVal maxUInt8 As Byte)
  98.  
  99.        Me.Min = minUInt8
  100.        Me.Max = maxUInt8
  101.  
  102.    End Sub
  103.  
  104.    ''' <summary>
  105.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Short"/> datatype.
  106.    ''' </summary>
  107.    ''' <param name="minInt16">The minimum <see cref="Short"/> value.</param>
  108.    ''' <param name="maxInt16">The maximum <see cref="Short"/> value.</param>
  109.    Public Sub New(ByVal minInt16 As Short, ByVal maxInt16 As Short)
  110.  
  111.        Me.Min = minInt16
  112.        Me.Max = maxInt16
  113.  
  114.    End Sub
  115.  
  116.    ''' <summary>
  117.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="UShort"/> datatype.
  118.    ''' </summary>
  119.    ''' <param name="minUInt16">The minimum <see cref="UShort"/> value.</param>
  120.    ''' <param name="maxUInt16">The maximum <see cref="UShort"/> value.</param>
  121.    Public Sub New(ByVal minUInt16 As UShort, ByVal maxUInt16 As UShort)
  122.  
  123.        Me.Min = minUInt16
  124.        Me.Max = maxUInt16
  125.  
  126.    End Sub
  127.  
  128.    ''' <summary>
  129.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Integer"/> datatype.
  130.    ''' </summary>
  131.    ''' <param name="minInt32">The minimum <see cref="Integer"/> value.</param>
  132.    ''' <param name="maxInt32">The maximum <see cref="Integer"/> value.</param>
  133.    Public Sub New(ByVal minInt32 As Integer, ByVal maxInt32 As Integer)
  134.  
  135.        Me.Min = minInt32
  136.        Me.Max = maxInt32
  137.  
  138.    End Sub
  139.  
  140.    ''' <summary>
  141.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="UInteger"/> datatype.
  142.    ''' </summary>
  143.    ''' <param name="minUInt32">The minimum <see cref="UInteger"/> value.</param>
  144.    ''' <param name="maxUInt32">The maximum <see cref="UInteger"/> value.</param>
  145.    Public Sub New(ByVal minUInt32 As UInteger, ByVal maxUInt32 As UInteger)
  146.  
  147.        Me.Min = minUInt32
  148.        Me.Max = maxUInt32
  149.  
  150.    End Sub
  151.  
  152.    ''' <summary>
  153.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Long"/> datatype.
  154.    ''' </summary>
  155.    ''' <param name="minInt64">The minimum <see cref="Long"/> value.</param>
  156.    ''' <param name="maxInt64">The maximum <see cref="Long"/> value.</param>
  157.    Public Sub New(ByVal minInt64 As Long, ByVal maxInt64 As Long)
  158.  
  159.        Me.Min = minInt64
  160.        Me.Max = maxInt64
  161.  
  162.    End Sub
  163.  
  164.    ''' <summary>
  165.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="ULong"/> datatype.
  166.    ''' </summary>
  167.    ''' <param name="minUInt64">The minimum <see cref="ULong"/> value.</param>
  168.    ''' <param name="maxUInt64">The maximum <see cref="ULong"/> value.</param>
  169.    Public Sub New(ByVal minUInt64 As ULong, ByVal maxUInt64 As ULong)
  170.  
  171.        Me.Min = minUInt64
  172.        Me.Max = maxUInt64
  173.  
  174.    End Sub
  175.  
  176.    ''' <summary>
  177.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Single"/> datatype.
  178.    ''' </summary>
  179.    ''' <param name="minSingle">The minimum <see cref="Single"/> value.</param>
  180.    ''' <param name="maxSingle">The maximum <see cref="Single"/> value.</param>
  181.    Public Sub New(ByVal minSingle As Single, ByVal maxSingle As Single)
  182.  
  183.        Me.Min = minSingle
  184.        Me.Max = maxSingle
  185.  
  186.    End Sub
  187.  
  188.    ''' <summary>
  189.    ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Double"/> datatype.
  190.    ''' </summary>
  191.    ''' <param name="minDouble">The minimum <see cref="Double"/> value.</param>
  192.    ''' <param name="maxDouble">The maximum <see cref="Double"/> value.</param>
  193.    Public Sub New(ByVal minDouble As Double, ByVal maxDouble As Double)
  194.  
  195.        Me.Min = minDouble
  196.        Me.Max = maxDouble
  197.  
  198.    End Sub
  199.  
  200.    ''' <summary>
  201.    ''' Prevents a default instance of the <see cref="RangeAttribute"/> class from being created.
  202.    ''' </summary>
  203.    Private Sub New()
  204.    End Sub
  205.  
  206. #End Region
  207.  
  208. #Region " Methods "
  209.  
  210.    ''' <summary>
  211.    ''' Method invoked <i>instead</i> of the <c>Set</c> semantic of the field or property to which the current aspect is applied,
  212.    ''' i.e. when the value of this field or property is changed.
  213.    ''' </summary>
  214.    ''' <param name="args">Advice arguments.</param>
  215.    Public Overrides Sub OnSetValue(ByVal args As LocationInterceptionArgs)
  216.  
  217.        Dim value As Object = args.Value
  218.  
  219.        Select Case True
  220.  
  221.            Case TypeOf value Is SByte
  222.                If DirectCast(value, SByte) < CSByte(Me.Min) Then
  223.                    value = Me.Min
  224.                ElseIf DirectCast(value, SByte) > CSByte(Me.Max) Then
  225.                    value = Me.Max
  226.                End If
  227.                args.SetNewValue(CSByte(value))
  228.  
  229.            Case TypeOf value Is Byte
  230.                If DirectCast(value, Byte) < CByte(Me.Min) Then
  231.                    value = Me.Min
  232.                ElseIf DirectCast(value, Byte) > CByte(Me.Max) Then
  233.                    value = Me.Max
  234.                End If
  235.                args.SetNewValue(CByte(value))
  236.  
  237.            Case TypeOf value Is Short
  238.                If DirectCast(value, Short) < CShort(Me.Min) Then
  239.                    value = Me.Min
  240.                ElseIf DirectCast(value, Short) > CShort(Me.Max) Then
  241.                    value = Me.Max
  242.                End If
  243.                args.SetNewValue(CShort(value))
  244.  
  245.            Case TypeOf value Is UShort
  246.                If DirectCast(value, UShort) < CUShort(Me.Min) Then
  247.                    value = Me.Min
  248.                ElseIf DirectCast(value, UShort) > CUShort(Me.Max) Then
  249.                    value = Me.Max
  250.                End If
  251.                args.SetNewValue(CUShort(value))
  252.  
  253.            Case TypeOf value Is Integer
  254.                If DirectCast(value, Integer) < CInt(Me.Min) Then
  255.                    value = Me.Min
  256.                ElseIf DirectCast(value, Integer) > CInt(Me.Max) Then
  257.                    value = Me.Max
  258.                End If
  259.                args.SetNewValue(CInt(value))
  260.  
  261.            Case TypeOf value Is UInteger
  262.                If DirectCast(value, UInteger) < CUInt(Me.Min) Then
  263.                    value = Me.Min
  264.                ElseIf DirectCast(value, UInteger) > CUInt(Me.Max) Then
  265.                    value = Me.Max
  266.                End If
  267.                args.SetNewValue(CUInt(value))
  268.  
  269.            Case TypeOf value Is Long
  270.                If DirectCast(value, Long) < CLng(Me.Min) Then
  271.                    value = Me.Min
  272.                ElseIf DirectCast(value, Long) > CLng(Me.Max) Then
  273.                    value = Me.Max
  274.                End If
  275.                args.SetNewValue(CLng(value))
  276.  
  277.            Case TypeOf value Is ULong
  278.                If DirectCast(value, ULong) < CULng(Me.Min) Then
  279.                    value = Me.Min
  280.                ElseIf DirectCast(value, ULong) > CULng(Me.Max) Then
  281.                    value = Me.Max
  282.                End If
  283.                args.SetNewValue(CULng(value))
  284.  
  285.            Case TypeOf value Is Single
  286.                If DirectCast(value, Single) < CSng(Me.Min) Then
  287.                    value = Me.Min
  288.                ElseIf DirectCast(value, Single) > CSng(Me.Max) Then
  289.                    value = Me.Max
  290.                End If
  291.                args.SetNewValue(CSng(value))
  292.  
  293.            Case TypeOf value Is Double
  294.                If DirectCast(value, Double) < CDbl(Me.Min) Then
  295.                    value = Me.Min
  296.                ElseIf DirectCast(value, Double) > CDbl(Me.Max) Then
  297.                    value = Me.Max
  298.                End If
  299.                args.SetNewValue(CDbl(value))
  300.  
  301.        End Select
  302.  
  303.    End Sub
  304.  
  305. #End Region
  306.  
  307. End Class
  308.  
  309. #End Region
« Última modificación: 7 Junio 2015, 10:46 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #464 en: 15 Junio 2015, 20:01 pm »

Comparto este snippet para compilar código fuente en tiempo de ejecución, una DLL, una app CLI o GUI, desde un string o desde un archivo que contenga el código guente.

Es útil por ejemplo para bindear archivos, o embedir tablas de recursos en una dll, o simplemente para compilar un código de C# o VB.Net.

Ejemplo de uso:
Código
  1. Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider
  2.  
  3.     Dim resultVB As CompilerResults =
  4.         CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider,
  5.                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  6.                                     targetFile:="C:\VB Assembly.dll",
  7.                                     resources:={"C:\MyResources.resx"},
  8.                                     referencedAssemblies:={"System.dll"},
  9.                                     mainClassName:="MainNamespace.MainClass",
  10.                                     sourceCode:=<a>
  11.                                                 Imports System
  12.  
  13.                                                 Namespace MainNamespace
  14.  
  15.                                                     Public NotInheritable MainClass
  16.  
  17.                                                     End Class
  18.  
  19.                                                 End Namespace
  20.                                                 </a>.Value)
  21.  
  22.     Dim warnings As IEnumerable(Of CompilerError) =
  23.         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  24.         Where ce.IsWarning
  25.  
  26.     Dim errors As IEnumerable(Of CompilerError) =
  27.         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  28.         Where Not ce.IsWarning
  29.  
  30.     For Each war As CompilerError In warnings
  31.         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  32.     Next war
  33.  
  34.     For Each err As CompilerError In errors
  35.         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  36.     Next err
  37.  
  38. End Using

Código fuente:
Código
  1.        ''' <summary>
  2.        ''' Specifies a <see cref="CompilerParameters"></see> target assembly.
  3.        ''' </summary>
  4.        Public Enum TargetAssembly As Integer
  5.  
  6.            ''' <summary>
  7.            ''' A Command line interface executable.
  8.            ''' </summary>
  9.            Cli = 0
  10.  
  11.            ''' <summary>
  12.            ''' A Graphical user interface executable.
  13.            ''' </summary>
  14.            Gui = 1
  15.  
  16.            ''' <summary>
  17.            ''' A Dynamic-link library.
  18.            ''' </summary>
  19.            Dll = 2
  20.  
  21.        End Enum
  22.  
  23.        ''' <remarks>
  24.        ''' *****************************************************************
  25.        ''' Title : Compile Assembly (from reaource).
  26.        ''' Author: Elektro
  27.        ''' Date  : 14-June-2015
  28.        ''' Usage :
  29.        '''
  30.        ''' Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider
  31.        '''
  32.        '''     Dim resultVB As CompilerResults =
  33.        '''         CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider,
  34.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  35.        '''                                     targetFile:="C:\VB Assembly.dll",
  36.        '''                                     resources:={"C:\MyResources.resx"},
  37.        '''                                     referencedAssemblies:={"System.dll"},
  38.        '''                                     mainClassName:="MainNamespace.MainClass",
  39.        '''                                     sourceCode:=<a>
  40.        '''                                                 Imports System
  41.        '''
  42.        '''                                                 Namespace MainNamespace
  43.        '''
  44.        '''                                                     Public NotInheritable MainClass
  45.        '''
  46.        '''                                                     End Class
  47.        '''
  48.        '''                                                 End Namespace
  49.        '''                                                 </a>.Value)
  50.        '''
  51.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  52.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  53.        '''         Where ce.IsWarning
  54.        '''
  55.        '''     Dim errors As IEnumerable(Of CompilerError) =
  56.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  57.        '''         Where Not ce.IsWarning
  58.        '''
  59.        '''     For Each war As CompilerError In warnings
  60.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  61.        '''     Next war
  62.        '''
  63.        '''     For Each err As CompilerError In errors
  64.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  65.        '''     Next err
  66.        '''
  67.        ''' End Using
  68.        ''' -----------------------------------------------------------------
  69.        ''' Using csCodeProvider As New Microsoft.CSharp.CSharpCodeProvider
  70.        '''
  71.        '''     Dim resultCS As CompilerResults =
  72.        '''         CodeDomUtil.CompileAssembly(codeProvider:=csCodeProvider,
  73.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  74.        '''                                     targetFile:="C:\C# Assembly.dll",
  75.        '''                                     resources:={"C:\MyResources.resx"},
  76.        '''                                     referencedAssemblies:={"System.dll"},
  77.        '''                                     mainClassName:="MainNamespace.MainClass",
  78.        '''                                     sourceCode:=<a>
  79.        '''                                                 using System;
  80.        '''
  81.        '''                                                 namespace MainNamespace
  82.        '''                                                 {
  83.        '''                                                     class MainClass
  84.        '''                                                     {
  85.        '''
  86.        '''                                                     }
  87.        '''                                                 }
  88.        '''                                                 </a>.Value)
  89.        '''
  90.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  91.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  92.        '''         Where ce.IsWarning
  93.        '''
  94.        '''     Dim errors As IEnumerable(Of CompilerError) =
  95.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  96.        '''         Where Not ce.IsWarning
  97.        '''
  98.        '''     For Each war As CompilerError In warnings
  99.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  100.        '''     Next war
  101.        '''
  102.        '''     For Each err As CompilerError In errors
  103.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  104.        '''     Next err
  105.        '''
  106.        ''' End Using
  107.        ''' *****************************************************************
  108.        ''' </remarks>
  109.        ''' <summary>
  110.        ''' Compiles a .Net assembly as executable or link library.
  111.        ''' </summary>
  112.        ''' <param name="codeProvider">The code provider.</param>
  113.        ''' <param name="targetAssembly">The kind of assembly to generate.</param>
  114.        ''' <param name="targetFile">The target file to create.</param>
  115.        ''' <param name="resources">The embedded resources (if any).</param>
  116.        ''' <param name="referencedAssemblies">The referenced assemblies (if any).</param>
  117.        ''' <param name="mainClassName">The code to compile (if any).</param>
  118.        ''' <param name="sourceCode">The sourcecode to compile (if any).</param>
  119.        ''' <exception cref="Exception">The current CodeDomProvider does not support resource embedding.</exception>
  120.        ''' <exception cref="NotImplementedException">Default sourcecode is not implemented for the specified CodeDomProvider. Please, set a sourcecode yourself.</exception>
  121.        ''' <returns>The results of the compiler operation.</returns>
  122.        Public Shared Function CompileAssembly(ByVal codeProvider As CodeDomProvider,
  123.                                               ByVal targetAssembly As TargetAssembly,
  124.                                               ByVal targetFile As String,
  125.                                               Optional ByVal resources As IEnumerable(Of String) = Nothing,
  126.                                               Optional ByVal referencedAssemblies As IEnumerable(Of String) = Nothing,
  127.                                               Optional ByVal mainClassName As String = "MainNamespace.MainClass",
  128.                                               Optional ByVal sourceCode As String = Nothing) As CompilerResults
  129.  
  130.            ' Set a default assembly reference.
  131.            If referencedAssemblies Is Nothing Then
  132.                referencedAssemblies = {"System.dll"}
  133.            End If
  134.  
  135.            Dim cp As New CompilerParameters
  136.            With cp
  137.  
  138.                ' Set compiler arguments.
  139.                Select Case targetAssembly
  140.  
  141.                    Case CodeDomUtil.TargetAssembly.Gui
  142.                        .CompilerOptions = "/optimize /target:winexe"
  143.  
  144.                    Case Else
  145.                        .CompilerOptions = "/optimize"
  146.  
  147.                End Select
  148.  
  149.                ' Generate an exe or a dll.
  150.                .GenerateExecutable = (targetAssembly <> CodeDomUtil.TargetAssembly.Dll)
  151.  
  152.                ' Save the assembly as a physical file.
  153.                .GenerateInMemory = False
  154.  
  155.                ' Generate debug information (pdb).
  156.                .IncludeDebugInformation = False
  157.  
  158.                ' Set the assembly file name to generate.
  159.                .OutputAssembly = targetFile
  160.  
  161.                ' Add an assembly reference.
  162.                .ReferencedAssemblies.AddRange(referencedAssemblies.ToArray)
  163.  
  164.                ' Set a temporary files collection.
  165.                ' The TempFileCollection stores the temporary files generated during a build in the current directory.
  166.                .TempFiles = New TempFileCollection(tempdir:=IO.Path.GetTempPath(), keepFiles:=True)
  167.  
  168.                ' Set whether to treat all warnings as errors.
  169.                .TreatWarningsAsErrors = False
  170.  
  171.                ' Set the level at which the compiler should start displaying warnings.
  172.                ' 0 - Turns off emission of all warning messages.
  173.                ' 1 - Displays severe warning messages.
  174.                ' 2 - Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
  175.                ' 3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
  176.                ' 4 - Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.
  177.                .WarningLevel = 3
  178.  
  179.                ' Set the embedded resource file of the assembly.
  180.                If codeProvider.Supports(GeneratorSupport.Resources) AndAlso (resources IsNot Nothing) Then
  181.                    .EmbeddedResources.AddRange(resources.ToArray)
  182.  
  183.                ElseIf (Not codeProvider.Supports(GeneratorSupport.Resources)) AndAlso (resources IsNot Nothing) Then
  184.                    Throw New Exception(message:="The current CodeDomProvider does not support resource embedding.")
  185.  
  186.                End If
  187.  
  188.                ' Specify the class that contains the main method of the executable.
  189.                If codeProvider.Supports(GeneratorSupport.EntryPointMethod) Then
  190.  
  191.                    .MainClass = mainClassName
  192.  
  193.                    If (TypeOf codeProvider Is Microsoft.VisualBasic.VBCodeProvider) AndAlso
  194.                       (String.IsNullOrEmpty(sourceCode)) AndAlso
  195.                       .GenerateExecutable Then
  196.  
  197.                        sourceCode =
  198.                            <a>
  199.                            Imports System
  200.  
  201.                            Namespace MainNamespace
  202.  
  203.                                Module MainClass
  204.  
  205.                                    Sub Main()
  206.                                    End Sub
  207.  
  208.                                End Module
  209.  
  210.                            End Namespace
  211.                            </a>.Value
  212.  
  213.                    ElseIf (TypeOf codeProvider Is Microsoft.VisualBasic.VBCodeProvider) AndAlso
  214.                           (String.IsNullOrEmpty(sourceCode)) AndAlso
  215.                           Not .GenerateExecutable Then
  216.  
  217.                        sourceCode =
  218.                            <a>
  219.                            Imports System
  220.  
  221.                            Namespace MainNamespace
  222.  
  223.                                Public NotInheritable MainClass
  224.  
  225.                                End Class
  226.  
  227.                            End Namespace
  228.                            </a>.Value
  229.  
  230.                    ElseIf (TypeOf codeProvider Is Microsoft.CSharp.CSharpCodeProvider) AndAlso
  231.                           (String.IsNullOrEmpty(sourceCode)) AndAlso
  232.                          .GenerateExecutable Then
  233.  
  234.                        sourceCode =
  235.                            <a>
  236.                            using System;
  237.  
  238.                            namespace MainNamespace
  239.                            {
  240.                                class MainClass
  241.                                {
  242.                                    static void Main(string[] args)
  243.                                    {
  244.  
  245.                                    }
  246.                                }
  247.                            }
  248.                            </a>.Value
  249.  
  250.                    ElseIf (TypeOf codeProvider Is Microsoft.CSharp.CSharpCodeProvider) AndAlso
  251.                           (String.IsNullOrEmpty(sourceCode)) AndAlso
  252.                           Not .GenerateExecutable Then
  253.  
  254.                        sourceCode =
  255.                            <a>
  256.                            using System;
  257.  
  258.                            namespace MainNamespace
  259.                            {
  260.                                class MainClass
  261.                                {
  262.  
  263.                                }
  264.                            }
  265.                            </a>.Value
  266.  
  267.                    ElseIf String.IsNullOrEmpty(sourceCode) Then
  268.                        Throw New NotImplementedException(message:="Default sourcecode is not implemented for the specified CodeDomProvider. Please, specify a sourcecode.")
  269.  
  270.                    End If
  271.  
  272.                End If
  273.  
  274.            End With
  275.  
  276.            Return codeProvider.CompileAssemblyFromSource(cp, sourceCode)
  277.  
  278.        End Function
  279.  
  280.        ''' <remarks>
  281.        ''' *****************************************************************
  282.        ''' Title : Compile Assembly (from file).
  283.        ''' Author: Elektro
  284.        ''' Date  : 14-June-2015
  285.        ''' Usage :
  286.        '''
  287.        ''' Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider
  288.        '''
  289.        '''     Dim resultVB As CompilerResults =
  290.        '''         CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider,
  291.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  292.        '''                                     sourceFile:="C:\SourceCode.vb",
  293.        '''                                     targetFile:="C:\VB Assembly.dll",
  294.        '''                                     resources:={"C:\MyResources.resx"},
  295.        '''                                     referencedAssemblies:={"System.dll"},
  296.        '''                                     mainClassName:="MainNamespace.MainClass")
  297.        '''
  298.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  299.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  300.        '''         Where ce.IsWarning
  301.        '''
  302.        '''     Dim errors As IEnumerable(Of CompilerError) =
  303.        '''         From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)()
  304.        '''         Where Not ce.IsWarning
  305.        '''
  306.        '''     For Each war As CompilerError In warnings
  307.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  308.        '''     Next war
  309.        '''
  310.        '''     For Each err As CompilerError In errors
  311.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  312.        '''     Next err
  313.        '''
  314.        ''' End Using
  315.        ''' -----------------------------------------------------------------
  316.        ''' Using csCodeProvider As New Microsoft.CSharp.CSharpCodeProvider
  317.        '''
  318.        '''     Dim resultCS As CompilerResults =
  319.        '''         CodeDomUtil.CompileAssembly(codeProvider:=csCodeProvider,
  320.        '''                                     targetAssembly:=CodeDomUtil.TargetAssembly.Dll,
  321.        '''                                     sourceFile:="C:\SourceCode.cs",
  322.        '''                                     targetFile:="C:\CS Assembly.dll",
  323.        '''                                     resources:={"C:\MyResources.resx"},
  324.        '''                                     referencedAssemblies:={"System.dll"},
  325.        '''                                     mainClassName:="MainNamespace.MainClass")
  326.        '''
  327.        '''     Dim warnings As IEnumerable(Of CompilerError) =
  328.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  329.        '''         Where ce.IsWarning
  330.        '''
  331.        '''     Dim errors As IEnumerable(Of CompilerError) =
  332.        '''         From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)()
  333.        '''         Where Not ce.IsWarning
  334.        '''
  335.        '''     For Each war As CompilerError In warnings
  336.        '''         Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText))
  337.        '''     Next war
  338.        '''
  339.        '''     For Each err As CompilerError In errors
  340.        '''         Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText))
  341.        '''     Next err
  342.        '''
  343.        ''' End Using
  344.        ''' *****************************************************************
  345.        ''' </remarks>
  346.        ''' <summary>
  347.        ''' Compiles a .Net assembly as executable or link library.
  348.        ''' </summary>
  349.        ''' <param name="codeProvider">The code provider.</param>
  350.        ''' <param name="targetAssembly">The kind of assembly to generate.</param>
  351.        ''' <param name="sourceFile">The source file to compile.</param>
  352.        ''' <param name="targetFile">The target file to create.</param>
  353.        ''' <param name="resources">The embedded resources (if any).</param>
  354.        ''' <param name="referencedAssemblies">The referenced assemblies (if any).</param>
  355.        ''' <param name="mainClassName">The code to compile (if any).</param>
  356.        ''' <exception cref="Exception">The current CodeDomProvider does not support resource embedding.</exception>
  357.        ''' <returns>The results of the compiler operation.</returns>
  358.        Public Shared Function CompileAssembly(ByVal codeProvider As CodeDomProvider,
  359.                                               ByVal targetAssembly As TargetAssembly,
  360.                                               ByVal sourceFile As String,
  361.                                               ByVal targetFile As String,
  362.                                               Optional ByVal resources As IEnumerable(Of String) = Nothing,
  363.                                               Optional ByVal referencedAssemblies As IEnumerable(Of String) = Nothing,
  364.                                               Optional ByVal mainClassName As String = "MainNamespace.MainClass") As CompilerResults
  365.  
  366.            ' Set a default assembly reference.
  367.            If referencedAssemblies Is Nothing Then
  368.                referencedAssemblies = {"System.dll"}
  369.            End If
  370.  
  371.            Dim cp As New CompilerParameters
  372.            With cp
  373.  
  374.                ' Set compiler arguments.
  375.                Select Case targetAssembly
  376.  
  377.                    Case CodeDomUtil.TargetAssembly.Gui
  378.                        .CompilerOptions = "/optimize /target:winexe"
  379.  
  380.                    Case Else
  381.                        .CompilerOptions = "/optimize"
  382.  
  383.                End Select
  384.  
  385.                ' Generate an exe or a dll.
  386.                .GenerateExecutable = (targetAssembly <> CodeDomUtil.TargetAssembly.Dll)
  387.  
  388.                ' Save the assembly as a physical file.
  389.                .GenerateInMemory = False
  390.  
  391.                ' Generate debug information (pdb).
  392.                .IncludeDebugInformation = False
  393.  
  394.                ' Set the assembly file name to generate.
  395.                .OutputAssembly = targetFile
  396.  
  397.                ' Add an assembly reference.
  398.                .ReferencedAssemblies.AddRange(referencedAssemblies.ToArray)
  399.  
  400.                ' Set a temporary files collection.
  401.                ' The TempFileCollection stores the temporary files generated during a build in the current directory.
  402.                .TempFiles = New TempFileCollection(tempdir:=IO.Path.GetTempPath(), keepFiles:=True)
  403.  
  404.                ' Set whether to treat all warnings as errors.
  405.                .TreatWarningsAsErrors = False
  406.  
  407.                ' Set the level at which the compiler should start displaying warnings.
  408.                ' 0 - Turns off emission of all warning messages.
  409.                ' 1 - Displays severe warning messages.
  410.                ' 2 - Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
  411.                ' 3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
  412.                ' 4 - Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.
  413.                .WarningLevel = 3
  414.  
  415.                ' Set the embedded resource file of the assembly.
  416.                If codeProvider.Supports(GeneratorSupport.Resources) AndAlso (resources IsNot Nothing) Then
  417.                    .EmbeddedResources.AddRange(resources.ToArray)
  418.  
  419.                ElseIf (Not codeProvider.Supports(GeneratorSupport.Resources)) AndAlso (resources IsNot Nothing) Then
  420.                    Throw New Exception(message:="The current CodeDomProvider does not support resource embedding.")
  421.  
  422.                End If
  423.  
  424.                ' Specify the class that contains the main method of the executable.
  425.                If codeProvider.Supports(GeneratorSupport.EntryPointMethod) Then
  426.                    .MainClass = mainClassName
  427.                End If
  428.  
  429.            End With
  430.  
  431.            Return codeProvider.CompileAssemblyFromFile(cp, {sourceFile})
  432.  
  433.        End Function
  434.  
  435.    End Class
  436.  
« Última modificación: 15 Junio 2015, 20:04 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #465 en: 16 Junio 2015, 13:03 pm »

¿Habeis sentido alguna vez la necesidad de mover una o varias filas de un DataGridView preservando el valor de algunas celdas en el transcurso?, pues yo si, así que comparto este código rehusable que me parece bastante sofisticado para llevar a cabo esa tarea, soporta multi-selección de filas, pero es para manipular directamente las filas de un DataGridViev, no el datasource.

Ejemplo de uso:
Código
  1. Me.DataGridView1.MoveSelectedRows(DataGridViewMoveRowDirection.Up)
Código
  1. Me.DataGridView1.MoveSelectedRows(DataGridViewMoveRowDirection.Up, {0, 2})

Código fuente:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 16-June-2015
  4. ' ***********************************************************************
  5. ' <copyright file="DataGridViewExtensions.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Strict On
  13. Option Explicit On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports System.Runtime.CompilerServices
  21. Imports System.Windows.Forms
  22.  
  23. #End Region
  24.  
  25. ''' <summary>
  26. ''' Contains two methods for moving DataRows up/down.
  27. ''' You could easily tweak the code to work for say a ListBox.
  28. ''' </summary>
  29. ''' <remarks></remarks>
  30. Public Module DataGridViewExtensions
  31.  
  32. #Region " Enumerations "
  33.  
  34.    ''' <summary>
  35.    ''' Specifies a direction to move the rows.
  36.    ''' </summary>
  37.    Public Enum DataGridViewMoveRowDirection As Integer
  38.  
  39.        ''' <summary>
  40.        ''' Move row up.
  41.        ''' </summary>
  42.        Up = 0
  43.  
  44.        ''' <summary>
  45.        ''' Move row down.
  46.        ''' </summary>
  47.        Down = 1
  48.  
  49.    End Enum
  50.  
  51. #End Region
  52.  
  53. #Region " Public Methods "
  54.  
  55.    ''' <summary>
  56.    ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>.
  57.    ''' </summary>
  58.    ''' <param name="sender">The <see cref="DataGridView"/>.</param>
  59.    ''' <param name="direction">The row-move direction.</param>
  60.    <DebuggerStepThrough()>
  61.    <Extension()>
  62.    Public Sub MoveSelectedRows(ByVal sender As DataGridView,
  63.                                ByVal direction As DataGridViewMoveRowDirection)
  64.  
  65.        DoRowsMove(sender, direction)
  66.  
  67.    End Sub
  68.  
  69.    ''' <summary>
  70.    ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>.
  71.    ''' </summary>
  72.    ''' <param name="sender">The <see cref="DataGridView"/>.</param>
  73.    ''' <param name="direction">The row-move direction.</param>
  74.    ''' <param name="preserveCellsIndex">A sequence of cell indexes to preserve its cell values when moving the row(s).</param>
  75.    <DebuggerStepThrough()>
  76.    <Extension()>
  77.    Public Sub MoveSelectedRows(ByVal sender As DataGridView,
  78.                                ByVal direction As DataGridViewMoveRowDirection,
  79.                                ByVal preserveCellsIndex As IEnumerable(Of Integer))
  80.  
  81.        DoRowsMove(sender, direction, preserveCellsIndex)
  82.  
  83.    End Sub
  84.  
  85. #End Region
  86.  
  87. #Region " Private Methods "
  88.  
  89.    ''' <summary>
  90.    ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>.
  91.    ''' </summary>
  92.    ''' <param name="dgv">The <see cref="DataGridView"/>.</param>
  93.    ''' <param name="direction">The row-move direction.</param>
  94.    ''' <param name="preserveCellsIndex">Optionally, a sequence of cell indexes to preserve its cell values when moving the row(s).</param>
  95.    <DebuggerStepThrough()>
  96.    Private Sub DoRowsMove(ByVal dgv As DataGridView,
  97.                           ByVal direction As DataGridViewMoveRowDirection,
  98.                           Optional ByVal preserveCellsIndex As IEnumerable(Of Integer) = Nothing)
  99.  
  100.        ' Keeps tracks of a cell value to preserve, to swap them when moving rows.
  101.        Dim oldCellValue As Object
  102.        Dim newCellValue As Object
  103.  
  104.        ' Short row collection reference.
  105.        Dim rows As DataGridViewRowCollection = dgv.Rows
  106.  
  107.        ' Keeps track of the current row.
  108.        Dim curRow As DataGridViewRow
  109.  
  110.        ' The maximum row index.
  111.        Dim lastRowIndex As Integer =
  112.            If(dgv.AllowUserToAddRows,
  113.               rows.Count - 2,
  114.               rows.Count - 1)
  115.  
  116.        ' List of hash codes of the selected rows.
  117.        Dim selectedRows As New List(Of Integer)
  118.  
  119.        ' Get the hash codes of the selected rows
  120.        For i As Integer = 0 To (rows.Count - 1)
  121.            If (rows(i).IsNewRow = False) AndAlso (rows(i).Selected) Then
  122.                selectedRows.Add(rows(i).GetHashCode)
  123.                rows(i).Selected = False
  124.            End If
  125.        Next i
  126.  
  127.        ' Move the selected rows up or down.
  128.        Select Case direction
  129.  
  130.            Case DataGridViewMoveRowDirection.Up
  131.                For i As Integer = 0 To lastRowIndex
  132.  
  133.                    If Not rows(i).IsNewRow Then
  134.  
  135.                        If (selectedRows.Contains(rows(i).GetHashCode)) AndAlso
  136.                           (i - 1 >= 0) AndAlso
  137.                           (Not selectedRows.Contains(rows(i - 1).GetHashCode)) Then
  138.  
  139.                            curRow = rows(i)
  140.                            rows.Remove(curRow)
  141.                            rows.Insert(i - 1, curRow)
  142.  
  143.                            If preserveCellsIndex IsNot Nothing Then
  144.  
  145.                                For Each cellIndex As Integer In preserveCellsIndex
  146.                                    oldCellValue = curRow.Cells(cellIndex).Value
  147.                                    newCellValue = rows(i).Cells(cellIndex).Value
  148.  
  149.                                    rows(i).Cells(cellIndex).Value = oldCellValue
  150.                                    curRow.Cells(cellIndex).Value = newCellValue
  151.                                Next cellIndex
  152.  
  153.                            End If
  154.  
  155.                        End If
  156.  
  157.                    End If
  158.  
  159.                Next i
  160.  
  161.            Case DataGridViewMoveRowDirection.Down
  162.                For i As Integer = lastRowIndex To 0 Step -1
  163.  
  164.                    If Not rows(i).IsNewRow Then
  165.  
  166.                        If (selectedRows.Contains(rows(i).GetHashCode)) AndAlso
  167.                           (i + 1 <= lastRowIndex) AndAlso
  168.                           (Not selectedRows.Contains(rows(i + 1).GetHashCode)) Then
  169.  
  170.                            curRow = rows(i)
  171.                            rows.Remove(curRow)
  172.                            rows.Insert(i + 1, curRow)
  173.  
  174.                            If preserveCellsIndex IsNot Nothing Then
  175.  
  176.                                For Each cellIndex As Integer In preserveCellsIndex
  177.                                    oldCellValue = curRow.Cells(cellIndex).Value
  178.                                    newCellValue = rows(i).Cells(cellIndex).Value
  179.  
  180.                                    rows(i).Cells(cellIndex).Value = oldCellValue
  181.                                    curRow.Cells(cellIndex).Value = newCellValue
  182.                                Next cellIndex
  183.  
  184.                            End If
  185.  
  186.                        End If
  187.  
  188.                    End If
  189.  
  190.                Next i
  191.  
  192.        End Select
  193.  
  194.        ' Restore selected rows.
  195.        For i As Integer = 0 To (rows.Count - 1)
  196.  
  197.            If Not rows(i).IsNewRow Then
  198.                rows(i).Selected = selectedRows.Contains(rows(i).GetHashCode)
  199.            End If
  200.  
  201.        Next i
  202.  
  203.    End Sub
  204.  
  205. #End Region
  206.  
  207. End Module

Saludos!
« Última modificación: 16 Junio 2015, 14:07 pm por Eleкtro » En línea



nolasco281


Desconectado Desconectado

Mensajes: 319


Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #466 en: 19 Junio 2015, 06:27 am »

Hola Eleкtro.

Disculpas las molestias pero el primer link de la pag 1 de snippets que es de mediafire no funciona ni tampoco el de la pagina 36 Actualizada la colección de snippets con un total de 544 Snippets
talvez puedas compartirlos en otro compila o volver a subir ese no habia teniado el gusto de ver el tema y me parece muy bueno.

Saludos.
En línea

Lo que se puede imaginar... se puede programar.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #467 en: 19 Junio 2015, 07:03 am »

Hola Eleкtro.

Disculpas las molestias pero el primer link de la pag 1 de snippets que es de mediafire no funciona ni tampoco el de la pagina 36 Actualizada la colección de snippets con un total de 544 Snippets
talvez puedas compartirlos en otro compila o volver a subir ese no habia teniado el gusto de ver el tema y me parece muy bueno.

Saludos.

Hmmm... antes de nada, ¡Gracias por avisar!, pero estoy preparando una actualización importante, hay muchos snippets antiguos que necesitan una refactorización completa, otros es mejor eliminarlos o adaptarlos para otros propósitos, y en fin, un lio, prefiero no resubir nada de momento hasta que no "limpie" todos los snippets, y son unos 700 (me está llevando meses xD).

De todas formas, aquí puedes descargar una versión más reciente de la colección de snippets:


(si prefieres no usar el exe, puedes desempaquetar su contenido con la aplicación InnoUnp para InnoSetup)

Saludos!
« Última modificación: 19 Junio 2015, 07:05 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

Una Class para manipular archivos de texto.

Diagrama de clase:


Ejemplo de uso:
Código
  1.        Using txtFile As New TextfileStream("C:\File.txt", Encoding.Default)
  2.  
  3.            txtFile.Lock()
  4.  
  5.            txtFile.Lines.Add("Test")
  6.            txtFile.Lines(0) = "Hello World!"
  7.            txtFile.Save()
  8.  
  9.            Dim lineIndex As Integer
  10.            Dim lineCount As Integer = txtFile.Lines.Count
  11.            Dim textFormat As String =
  12.                Environment.NewLine &
  13.                String.Join(ControlChars.NewLine,
  14.                            From line As String In txtFile.Lines
  15.                            Select String.Format("{0}: {1}",
  16.                            Interlocked.Increment(lineIndex).ToString(New String("0"c, lineCount.ToString.Length)), line))
  17.  
  18.            Console.WriteLine(String.Format("FilePath: {0}", txtFile.Filepath))
  19.            Console.WriteLine(String.Format("Encoding: {0}", txtFile.Encoding.WebName))
  20.            Console.WriteLine(String.Format("Lines   : {0}", textFormat))
  21.  
  22.        End Using
  23.  

Código fuente:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 18-June-2015
  4. ' ***********************************************************************
  5. ' <copyright file="TextfileStream.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Using txtFile As New TextfileStream("C:\File.txt")
  13. '
  14. '    txtFile.Lock()
  15. '
  16. '    txtFile.Lines.Add("Test")
  17. '    txtFile.Lines(0) = "Hello World!"
  18. '    txtFile.Save()
  19. '
  20. '    Dim lineIndex As Integer
  21. '    Dim lineCount As Integer = txtFile.Lines.Count
  22. '    Dim textFormat As String =
  23. '        Environment.NewLine &
  24. '        String.Join(ControlChars.NewLine,
  25. '                    From line As String In txtFile.Lines
  26. '                    Select String.Format("{0}: {1}",
  27. '                    Interlocked.Increment(lineIndex).ToString(New String("0"c, lineCount.ToString.Length)), line))
  28. '
  29. '    Console.WriteLine(String.Format("FilePath: {0}", txtFile.Filepath))
  30. '    Console.WriteLine(String.Format("Encoding: {0}", txtFile.Encoding.WebName))
  31. '    Console.WriteLine(String.Format("Lines   : {0}", textFormat))
  32. '
  33. 'End Using
  34.  
  35. #End Region
  36.  
  37. #Region " Option Statements "
  38.  
  39. Option Strict On
  40. Option Explicit On
  41. Option Infer Off
  42.  
  43. #End Region
  44.  
  45. #Region " Imports "
  46.  
  47. Imports Microsoft.Win32.SafeHandles
  48. Imports System
  49. Imports System.Collections.Generic
  50. Imports System.ComponentModel
  51. Imports System.IO
  52. Imports System.Linq
  53. Imports System.Text
  54.  
  55. #End Region
  56.  
  57. #Region " Textfile "
  58.  
  59. ''' <summary>
  60. ''' Reads and manages the contents of a textfile.
  61. ''' It encapsulates a <see cref="System.IO.FileStream"/> to access the textfile.
  62. ''' </summary>
  63. Public NotInheritable Class TextfileStream : Implements IDisposable
  64.  
  65. #Region " Properties "
  66.  
  67.    ''' ----------------------------------------------------------------------------------------------------
  68.    ''' <summary>
  69.    ''' Gets the textfile path.
  70.    ''' </summary>
  71.    ''' ----------------------------------------------------------------------------------------------------
  72.    ''' <value>
  73.    ''' The textfile path.
  74.    ''' </value>
  75.    ''' ----------------------------------------------------------------------------------------------------
  76.    Public ReadOnly Property Filepath As String
  77.        Get
  78.            Return Me.filepathB
  79.        End Get
  80.    End Property
  81.    ''' <summary>
  82.    ''' (Backing field)
  83.    ''' The textfile path.
  84.    ''' </summary>
  85.    Private ReadOnly filepathB As String
  86.  
  87.    ''' ----------------------------------------------------------------------------------------------------
  88.    ''' <summary>
  89.    ''' Gets the textfile <see cref="Encoding"/>.
  90.    ''' </summary>
  91.    ''' ----------------------------------------------------------------------------------------------------
  92.    ''' <value>
  93.    ''' The textfile <see cref="Encoding"/>.
  94.    ''' </value>
  95.    ''' ----------------------------------------------------------------------------------------------------
  96.    Public ReadOnly Property Encoding As Encoding
  97.        Get
  98.            Return Me.encodingB
  99.        End Get
  100.    End Property
  101.    ''' <summary>
  102.    ''' (Backing field)
  103.    ''' The textfile <see cref="Encoding"/>.
  104.    ''' </summary>
  105.    Private ReadOnly encodingB As Encoding = Encoding.Default
  106.  
  107.    ''' ----------------------------------------------------------------------------------------------------
  108.    ''' <summary>
  109.    ''' Gets or sets the textfile lines.
  110.    ''' </summary>
  111.    ''' ----------------------------------------------------------------------------------------------------
  112.    ''' <value>
  113.    ''' The textfile lines.
  114.    ''' </value>
  115.    ''' ----------------------------------------------------------------------------------------------------
  116.    Public Property Lines As TexfileLines
  117.        Get
  118.            Return Me.linesB
  119.        End Get
  120.        Set(ByVal value As TexfileLines)
  121.            Me.linesB = value
  122.        End Set
  123.    End Property
  124.    ''' <summary>
  125.    ''' (Backing field)
  126.    ''' The textfile lines.
  127.    ''' </summary>
  128.    Private linesB As TexfileLines
  129.  
  130.    ''' ----------------------------------------------------------------------------------------------------
  131.    ''' <summary>
  132.    ''' Gets the <see cref="System.IO.FileStream"/> instance that exposes a <see cref="System.IO.Stream"/> around the textfile.
  133.    ''' </summary>
  134.    ''' ----------------------------------------------------------------------------------------------------
  135.    ''' <value>
  136.    ''' The <see cref="System.IO.FileStream"/> instance.
  137.    ''' </value>
  138.    ''' ----------------------------------------------------------------------------------------------------
  139.    Private ReadOnly Property fs As FileStream
  140.        Get
  141.            Return Me.fsB
  142.        End Get
  143.    End Property
  144.    ''' <summary>
  145.    ''' (Backing Field)
  146.    ''' The <see cref="System.IO.FileStream"/> instance that exposes a <see cref="System.IO.Stream"/> around the textfile.
  147.    ''' </summary>
  148.    Private ReadOnly fsB As FileStream
  149.  
  150.    ''' ----------------------------------------------------------------------------------------------------
  151.    ''' <summary>
  152.    ''' Gets a <see cref="Microsoft.Win32.SafeHandles.SafeFileHandle"/> object that represents the operating system file handle of the textfile.
  153.    ''' </summary>
  154.    ''' ----------------------------------------------------------------------------------------------------
  155.    ''' <value>
  156.    ''' A <see cref="Microsoft.Win32.SafeHandles.SafeFileHandle"/> object that represents the operating system file handle of the textfile.
  157.    ''' </value>
  158.    ''' ----------------------------------------------------------------------------------------------------
  159.    Public ReadOnly Property FileHandle As SafeFileHandle
  160.        Get
  161.            Return Me.fs.SafeFileHandle
  162.        End Get
  163.    End Property
  164.    ''' <summary>
  165.    ''' (Backing Field)
  166.    ''' A <see cref="Microsoft.Win32.SafeHandles.SafeFileHandle"/> object that represents the operating system file handle of the textfile.
  167.    ''' </summary>
  168.    Private ReadOnly fileHandleB As SafeFileHandle
  169.  
  170. #End Region
  171.  
  172. #Region " Sub-Classes "
  173.  
  174.    ''' <summary>
  175.    ''' Defines a <see cref="System.Collections.Generic.List(Of String)"/> that contains the text-lines of a textfile.
  176.    ''' </summary>
  177.    Partial Public NotInheritable Class TexfileLines : Inherits List(Of String)
  178.  
  179. #Region " Properties "
  180.  
  181.        ''' ----------------------------------------------------------------------------------------------------
  182.        ''' <summary>
  183.        ''' Gets the number of blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>.
  184.        ''' </summary>
  185.        ''' ----------------------------------------------------------------------------------------------------
  186.        ''' <value>
  187.        ''' The number of blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>.
  188.        ''' </value>
  189.        ''' ----------------------------------------------------------------------------------------------------
  190.        Public ReadOnly Property CountBlank As Integer
  191.            Get
  192.                Return (From line As String In Me
  193.                        Where String.IsNullOrEmpty(line) OrElse
  194.                              String.IsNullOrWhiteSpace(line)).Count
  195.            End Get
  196.        End Property
  197.  
  198.        ''' ----------------------------------------------------------------------------------------------------
  199.        ''' <summary>
  200.        ''' Gets the number of non-blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>.
  201.        ''' </summary>
  202.        ''' ----------------------------------------------------------------------------------------------------
  203.        ''' <value>
  204.        ''' The number of non-blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>.
  205.        ''' </value>
  206.        ''' ----------------------------------------------------------------------------------------------------
  207.        Public ReadOnly Property CountNonBlank As Integer
  208.            Get
  209.                Return (From line As String In Me
  210.                        Where Not String.IsNullOrEmpty(line) AndAlso
  211.                              Not String.IsNullOrWhiteSpace(line)).Count
  212.            End Get
  213.        End Property
  214.  
  215. #End Region
  216.  
  217. #Region " Constructors "
  218.  
  219.        ''' ----------------------------------------------------------------------------------------------------
  220.        ''' <summary>
  221.        ''' Initializes a new instance of the <see cref="TexfileLines"/> class.
  222.        ''' </summary>
  223.        ''' ----------------------------------------------------------------------------------------------------
  224.        Public Sub New()
  225.        End Sub
  226.  
  227.        ''' ----------------------------------------------------------------------------------------------------
  228.        ''' <summary>
  229.        ''' Initializes a new instance of the <see cref="TexfileLines"/> class.
  230.        ''' </summary>
  231.        ''' ----------------------------------------------------------------------------------------------------
  232.        ''' <param name="lines">
  233.        ''' The text-lines.
  234.        ''' </param>
  235.        ''' ----------------------------------------------------------------------------------------------------
  236.        Public Sub New(ByVal lines As IEnumerable(Of String))
  237.  
  238.            Me.AddRange(lines)
  239.  
  240.        End Sub
  241.  
  242. #End Region
  243.  
  244. #Region " Public Methods "
  245.  
  246.        ''' ----------------------------------------------------------------------------------------------------
  247.        ''' <summary>
  248.        ''' Randomizes the elements of the <see cref="System.Collections.Generic.List(Of T)"/>.
  249.        ''' </summary>
  250.        ''' ----------------------------------------------------------------------------------------------------
  251.        ''' <returns>
  252.        ''' An <see cref="IEnumerable(Of String)"/> that contains the randomized elements.
  253.        ''' </returns>
  254.        ''' ----------------------------------------------------------------------------------------------------
  255.        <DebuggerStepThrough>
  256.        Public Function Randomize() As IEnumerable(Of String)
  257.  
  258.            Dim rand As New Random
  259.  
  260.            Return From line As String In Me
  261.                   Order By rand.Next
  262.  
  263.        End Function
  264.  
  265.        ''' ----------------------------------------------------------------------------------------------------
  266.        ''' <summary>
  267.        ''' Removes the elements at the specified indexes of the <see cref="System.Collections.Generic.List(Of T)"/>.
  268.        ''' </summary>
  269.        ''' ----------------------------------------------------------------------------------------------------
  270.        ''' <param name="indexes">
  271.        ''' The zero-based indexes of the elements to remove.
  272.        ''' </param>
  273.        ''' ----------------------------------------------------------------------------------------------------
  274.        ''' <exception cref="IndexOutOfRangeException">
  275.        ''' </exception>
  276.        ''' ----------------------------------------------------------------------------------------------------
  277.        <DebuggerStepThrough>
  278.        Public Overloads Sub RemoveAt(ByVal indexes As IEnumerable(Of Integer))
  279.  
  280.            Dim lineCount As Integer = Me.Count
  281.  
  282.            Select Case indexes.Max
  283.  
  284.                Case Is < 0, Is > lineCount
  285.                    Throw New IndexOutOfRangeException()
  286.  
  287.                Case Else
  288.                    Dim tmpRef As IEnumerable(Of String) =
  289.                        Me.Select(Function(line As String, index As Integer)
  290.                                      Return New With
  291.                                             {
  292.                                                 Key .line = line,
  293.                                                 Key .index = index + 1
  294.                                             }
  295.                                  End Function).
  296.                           Where(Function(con) Not indexes.Contains(con.index)).
  297.                           Select(Function(con) con.line)
  298.  
  299.                    Me.Clear()
  300.                    Me.AddRange(tmpRef)
  301.                    tmpRef = Nothing
  302.  
  303.            End Select
  304.  
  305.        End Sub
  306.  
  307.        ''' ----------------------------------------------------------------------------------------------------
  308.        ''' <summary>
  309.        ''' Removes all leading and trailing occurrences of a set of characters from all the elements of the <see cref="System.Collections.Generic.List(Of T)"/>.
  310.        ''' </summary>  
  311.        ''' ----------------------------------------------------------------------------------------------------
  312.        ''' <param name="trimChars">
  313.        ''' An array of Unicode characters to remove.
  314.        ''' If <paramref name="trimChars"></paramref> is <c>Nothing</c> or an empty array, Unicode white-space characters are removed instead.
  315.        ''' </param>
  316.        ''' ----------------------------------------------------------------------------------------------------
  317.        ''' <returns>
  318.        ''' The <see cref="IEnumerable(Of String)"/> that remains after all occurrences of the specified characters are removed from the start and the end of the elements.
  319.        ''' </returns>
  320.        ''' ----------------------------------------------------------------------------------------------------
  321.        <DebuggerStepThrough>
  322.        Public Function Trim(Optional ByVal trimChars As Char() = Nothing) As IEnumerable(Of String)
  323.  
  324.            Return From line As String In Me
  325.                   Select line.Trim(trimChars)
  326.  
  327.        End Function
  328.  
  329.        ''' ----------------------------------------------------------------------------------------------------
  330.        ''' <summary>
  331.        ''' Removes all leading occurrences of a set of characters from all the elements of the <see cref="System.Collections.Generic.List(Of T)"/>.
  332.        ''' </summary>
  333.        ''' ----------------------------------------------------------------------------------------------------
  334.        ''' <param name="trimChars">
  335.        ''' An array of Unicode characters to remove.
  336.        ''' If <paramref name="trimChars"></paramref> is <c>Nothing</c> or an empty array, Unicode white-space characters are removed instead.
  337.        ''' </param>
  338.        ''' ----------------------------------------------------------------------------------------------------
  339.        ''' <returns>
  340.        ''' The <see cref="IEnumerable(Of String)"/> that remains after all occurrences of the specified characters are removed from the start of the elements.
  341.        ''' </returns>
  342.        ''' ----------------------------------------------------------------------------------------------------
  343.        <DebuggerStepThrough>
  344.        Public Function TrimStart(Optional ByVal trimChars As Char() = Nothing) As IEnumerable(Of String)
  345.  
  346.            Return From line As String In Me
  347.                   Select line.TrimStart(trimChars)
  348.  
  349.        End Function
  350.  
  351.        ''' ----------------------------------------------------------------------------------------------------
  352.        ''' <summary>
  353.        ''' Removes all trailing occurrences of a set of characters from all the elements of the <see cref="System.Collections.Generic.List(Of T)"/>.
  354.        ''' </summary>
  355.        ''' ----------------------------------------------------------------------------------------------------
  356.        ''' <param name="trimChars">
  357.        ''' An array of Unicode characters to remove.
  358.        ''' If <paramref name="trimChars"></paramref> is <c>Nothing</c> or an empty array, Unicode white-space characters are removed instead.
  359.        ''' </param>
  360.        ''' ----------------------------------------------------------------------------------------------------
  361.        ''' <returns>
  362.        ''' The <see cref="IEnumerable(Of String)"/> that remains after all occurrences of the specified characters are removed from the end of the elements.
  363.        ''' </returns>
  364.        ''' ----------------------------------------------------------------------------------------------------
  365.        <DebuggerStepThrough>
  366.        Public Function TrimEnd(Optional ByVal trimChars As Char() = Nothing) As IEnumerable(Of String)
  367.  
  368.            Return From line As String In Me
  369.                   Select line.TrimEnd(trimChars)
  370.  
  371.        End Function
  372.  
  373. #End Region
  374.  
  375.    End Class
  376.  
  377. #End Region
  378.  
  379. #Region " Constructors "
  380.  
  381.    ''' ----------------------------------------------------------------------------------------------------
  382.    ''' <summary>
  383.    ''' Prevents a default instance of the <see cref="TextfileStream"/> class from being created.
  384.    ''' </summary>
  385.    ''' ----------------------------------------------------------------------------------------------------
  386.    Private Sub New()
  387.    End Sub
  388.  
  389.    ''' ----------------------------------------------------------------------------------------------------
  390.    ''' <summary>
  391.    ''' Initializes a new instance of the <see cref="TextfileStream"/> class.
  392.    ''' </summary>
  393.    ''' ----------------------------------------------------------------------------------------------------
  394.    ''' <param name="filepath">
  395.    ''' The textfile path.
  396.    ''' If the path doesn't exists, the file will be created.
  397.    ''' </param>
  398.    '''
  399.    ''' <param name="encoding">
  400.    ''' The file encoding used to read the textfile.
  401.    ''' If <paramref name="encoding"></paramref> value is <c>Nothing</c>, an attempt to detect the encoding will be realized,
  402.    ''' if the attempt to detect the file encoding fails, <see cref="Encoding.Default"/> will be used.
  403.    ''' </param>
  404.    ''' ----------------------------------------------------------------------------------------------------
  405.    ''' <exception cref="FileNotFoundException">
  406.    ''' File not found.
  407.    ''' </exception>
  408.    ''' ----------------------------------------------------------------------------------------------------
  409.    <DebuggerStepThrough>
  410.    Public Sub New(ByVal filepath As String,
  411.                   Optional ByVal encoding As Encoding = Nothing)
  412.  
  413.        If Not File.Exists(filepath) Then
  414.            Throw New FileNotFoundException(message:="File not found.", fileName:=filepath)
  415.  
  416.        Else
  417.            Me.filepathB = filepath
  418.            Me.encodingB = encoding
  419.  
  420.            If Me.encodingB Is Nothing Then
  421.                Me.encodingB = Me.GetEncoding
  422.            End If
  423.  
  424.            Me.linesB = New TexfileLines(File.ReadAllLines(Me.filepathB, Me.encodingB))
  425.            Me.fsB = New FileStream(filepath, FileMode.OpenOrCreate)
  426.  
  427.        End If
  428.  
  429.    End Sub
  430.  
  431. #End Region
  432.  
  433. #Region " Public Methods "
  434.  
  435.    ''' ----------------------------------------------------------------------------------------------------
  436.    ''' <summary>
  437.    ''' Prevents other processes from reading or writing to the textfile.
  438.    ''' </summary>
  439.    ''' ----------------------------------------------------------------------------------------------------
  440.    <DebuggerStepThrough>
  441.    Public Sub Lock()
  442.  
  443.        Me.fsB.Lock(0, Me.fsB.Length)
  444.  
  445.    End Sub
  446.  
  447.    ''' ----------------------------------------------------------------------------------------------------
  448.    ''' <summary>
  449.    ''' Allows access by other processes to read or write to a textfile that was previously locked.
  450.    ''' </summary>
  451.    ''' ----------------------------------------------------------------------------------------------------
  452.    <DebuggerStepThrough>
  453.    Public Sub Unlock()
  454.  
  455.        Me.fsB.Unlock(0, Me.fsB.Length)
  456.  
  457.    End Sub
  458.  
  459.    ''' ----------------------------------------------------------------------------------------------------
  460.    ''' <summary>
  461.    ''' Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
  462.    ''' </summary>
  463.    ''' ----------------------------------------------------------------------------------------------------
  464.    <DebuggerStepThrough>
  465.    Public Sub Close()
  466.        Me.fsB.Close()
  467.    End Sub
  468.  
  469.    ''' ----------------------------------------------------------------------------------------------------
  470.    ''' <summary>
  471.    ''' Save the lines of the current textfile, in the current textfile.
  472.    ''' Note that the <see cref="Save"></see> method should be called to apply any realized changes in the lines of the textfile
  473.    ''' before disposing this <see cref="TextfileStream"></see> instance.
  474.    ''' </summary>
  475.    ''' ----------------------------------------------------------------------------------------------------
  476.    ''' <param name="encoding">
  477.    ''' The file encoding used to write the textfile.
  478.    ''' </param>
  479.    ''' ----------------------------------------------------------------------------------------------------
  480.    <DebuggerStepThrough>
  481.    Public Sub Save(Optional ByVal encoding As Encoding = Nothing)
  482.  
  483.        If encoding Is Nothing Then
  484.            encoding = Me.encodingB
  485.        End If
  486.  
  487.        Dim bytes As Byte() = encoding.GetBytes(Me.ToString)
  488.  
  489.        Me.fs.SetLength(bytes.Length)
  490.        Me.fs.Write(bytes, 0, bytes.Length)
  491.  
  492.    End Sub
  493.  
  494.    ''' ----------------------------------------------------------------------------------------------------
  495.    ''' <summary>
  496.    ''' Save the lines of the current textfile, in the target textfile.
  497.    ''' </summary>
  498.    ''' ----------------------------------------------------------------------------------------------------
  499.    ''' <param name="filepath">
  500.    ''' The target filepath where to save the text.
  501.    ''' </param>
  502.    '''
  503.    ''' <param name="encoding">
  504.    ''' The file encoding used to write the textfile.
  505.    ''' </param>
  506.    ''' ----------------------------------------------------------------------------------------------------
  507.    <DebuggerStepThrough>
  508.    Public Sub Save(ByVal filepath As String,
  509.                    Optional ByVal encoding As Encoding = Nothing)
  510.  
  511.        If encoding Is Nothing Then
  512.            encoding = Me.encodingB
  513.        End If
  514.  
  515.        Using fs As New FileStream(filepath, FileMode.OpenOrCreate)
  516.  
  517.            Dim bytes As Byte() = encoding.GetBytes(Me.ToString)
  518.  
  519.            fs.SetLength(bytes.Length)
  520.            fs.Write(bytes, 0, bytes.Length)
  521.  
  522.        End Using
  523.  
  524.    End Sub
  525.  
  526.    ''' ----------------------------------------------------------------------------------------------------
  527.    ''' <summary>
  528.    ''' Returns a <see cref="String"/> that represents this instance.
  529.    ''' </summary>
  530.    ''' ----------------------------------------------------------------------------------------------------
  531.    ''' <returns>
  532.    ''' A <see cref="String"/> that represents this instance.
  533.    ''' </returns>
  534.    ''' ----------------------------------------------------------------------------------------------------
  535.    <DebuggerStepThrough>
  536.    Public Overrides Function ToString() As String
  537.  
  538.        Return String.Join(ControlChars.NewLine, Me.linesB)
  539.  
  540.    End Function
  541.  
  542. #End Region
  543.  
  544. #Region " Private Methods "
  545.  
  546.    ''' ----------------------------------------------------------------------------------------------------
  547.    ''' <summary>
  548.    ''' Determines the <see cref="Encoding"/> of the current textfile.
  549.    ''' </summary>
  550.    ''' ----------------------------------------------------------------------------------------------------
  551.    ''' <returns>
  552.    ''' If the encoding can be detected, the return value is the detected <see cref="Encoding"/>,
  553.    ''' if the encoding can't be detected, the return value is <see cref="Encoding.Default"/>.
  554.    ''' </returns>
  555.    ''' ----------------------------------------------------------------------------------------------------
  556.    <DebuggerStepThrough>
  557.    Private Function GetEncoding() As Encoding
  558.  
  559.        Dim encoding As Encoding = Nothing
  560.        Dim bytes As Byte() = File.ReadAllBytes(Me.filepathB)
  561.  
  562.        For Each encodingInfo As EncodingInfo In encoding.GetEncodings()
  563.  
  564.            Dim currentEncoding As Encoding = encodingInfo.GetEncoding()
  565.            Dim preamble As Byte() = currentEncoding.GetPreamble()
  566.            Dim match As Boolean = True
  567.  
  568.            If (preamble.Length > 0) AndAlso (preamble.Length <= bytes.Length) Then
  569.  
  570.                For i As Integer = 0 To (preamble.Length - 1)
  571.  
  572.                    If preamble(i) <> bytes(i) Then
  573.                        match = False
  574.                        Exit For
  575.                    End If
  576.  
  577.                Next i
  578.  
  579.            Else
  580.                match = False
  581.  
  582.            End If
  583.  
  584.            If match Then
  585.                encoding = currentEncoding
  586.                Exit For
  587.            End If
  588.  
  589.        Next encodingInfo
  590.  
  591.        If encoding Is Nothing Then
  592.            Return encoding.Default
  593.  
  594.        Else
  595.            Return encoding
  596.  
  597.        End If
  598.  
  599.    End Function
  600.  
  601. #End Region
  602.  
  603. #Region " IDisposable "
  604.  
  605.    ''' ----------------------------------------------------------------------------------------------------
  606.    ''' <summary>
  607.    ''' To detect redundant calls when disposing.
  608.    ''' </summary>
  609.    ''' ----------------------------------------------------------------------------------------------------
  610.    Private isDisposed As Boolean = False
  611.  
  612.    ''' ----------------------------------------------------------------------------------------------------
  613.    ''' <summary>
  614.    ''' Prevent calls to methods after disposing.
  615.    ''' </summary>
  616.    ''' ----------------------------------------------------------------------------------------------------
  617.    ''' <exception cref="System.ObjectDisposedException"></exception>
  618.    ''' ----------------------------------------------------------------------------------------------------
  619.    Private Sub DisposedCheck()
  620.  
  621.        If Me.isDisposed Then
  622.            Throw New ObjectDisposedException(Me.GetType.FullName)
  623.        End If
  624.  
  625.    End Sub
  626.  
  627.    ''' ----------------------------------------------------------------------------------------------------
  628.    ''' <summary>
  629.    ''' Releases all the resources used by this <see cref="TextfileStream"></see> instance.
  630.    ''' </summary>
  631.    ''' ----------------------------------------------------------------------------------------------------
  632.    Public Sub Dispose() Implements IDisposable.Dispose
  633.        Me.Dispose(isDisposing:=True)
  634.        GC.SuppressFinalize(obj:=Me)
  635.    End Sub
  636.  
  637.    ''' ----------------------------------------------------------------------------------------------------
  638.    ''' <summary>
  639.    ''' Releases unmanaged and - optionally - managed resources.
  640.    ''' </summary>
  641.    ''' ----------------------------------------------------------------------------------------------------
  642.    ''' <param name="isDisposing">
  643.    ''' <c>True</c> to release both managed and unmanaged resources;
  644.    ''' <c>False</c> to release only unmanaged resources.
  645.    ''' </param>
  646.    ''' ----------------------------------------------------------------------------------------------------
  647.    Protected Sub Dispose(ByVal isDisposing As Boolean)
  648.  
  649.        If Not Me.isDisposed Then
  650.  
  651.            If isDisposing Then
  652.  
  653.                If Me.fsB IsNot Nothing Then
  654.                    Me.fsB.Close()
  655.                    Me.linesB.Clear()
  656.                End If
  657.  
  658.            End If
  659.  
  660.        End If
  661.  
  662.        Me.isDisposed = True
  663.  
  664.    End Sub
  665.  
  666. #End Region
  667.  
  668. End Class
  669.  
  670. #End Region
« Última modificación: 19 Junio 2015, 10:40 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.Net !! (Compartan aquí sus snippets)
« Respuesta #469 en: 19 Junio 2015, 12:34 pm »

Un pequeño código para crear nuevas cuentas de usuario en el equipo.

Ejemplo de uso:
Código
  1.        CreateUserAccount(username:="Elektro",
  2.                          password:="",
  3.                          displayName:="Elektro account.",
  4.                          description:="This is a test user-account.",
  5.                          canChangePwd:=True,
  6.                          pwdExpires:=False,
  7.                          groupSid:=WellKnownSidType.BuiltinAdministratorsSid)

Código fuente:
Código
  1.    ''' ----------------------------------------------------------------------------------------------------
  2.    ''' <remarks>
  3.    ''' Title : Create user-account.
  4.    ''' Author: Elektro
  5.    ''' Date  : 19-June-2015
  6.    ''' </remarks>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    ''' <example>
  9.    ''' CreateUserAccount(username:="Elektro",
  10.    '''                   password:="",
  11.    '''                   displayName:="Elektro Account.",
  12.    '''                   description:="This is a test user-account.",
  13.    '''                   canChangePwd:=True,
  14.    '''                   pwdExpires:=False,
  15.    '''                   groupSid:=WellKnownSidType.BuiltinAdministratorsSid)
  16.    ''' </example>
  17.    ''' ----------------------------------------------------------------------------------------------------
  18.    ''' <summary>
  19.    ''' Creates a new user account in the current machine.
  20.    ''' This function does not adds the user to the machine.
  21.    ''' </summary>
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <param name="username">
  24.    ''' The user name.
  25.    ''' </param>
  26.    '''
  27.    ''' <param name="password">
  28.    ''' The user password.
  29.    ''' If this value is empty, account is set to don't require a password.
  30.    ''' </param>
  31.    '''
  32.    ''' <param name="displayName">
  33.    ''' The display name of the user account.
  34.    ''' </param>
  35.    '''
  36.    ''' <param name="description">
  37.    ''' The description of the user account.
  38.    ''' </param>
  39.    '''
  40.    ''' <param name="canChangePwd">
  41.    ''' A value that indicates whether the user can change its password.
  42.    ''' </param>
  43.    '''
  44.    ''' <param name="pwdExpires">
  45.    ''' A value that indicates whether the password should expire.
  46.    ''' </param>
  47.    ''' ----------------------------------------------------------------------------------------------------
  48.    ''' <returns>
  49.    ''' An <see cref="UserPrincipal"/> object that contains the user data.
  50.    ''' </returns>
  51.    ''' ----------------------------------------------------------------------------------------------------
  52.    <DebuggerStepThrough>
  53.    Public Shared Function CreateUserAccount(ByVal username As String,
  54.                                             ByVal password As String,
  55.                                             ByVal displayName As String,
  56.                                             ByVal description As String,
  57.                                             ByVal canChangePwd As Boolean,
  58.                                             ByVal pwdExpires As Boolean) As UserPrincipal
  59.  
  60.        Using context As New PrincipalContext(ContextType.Machine)
  61.  
  62.            Dim user As New UserPrincipal(context)
  63.  
  64.            With user
  65.  
  66.                .Name = username
  67.  
  68.                .SetPassword(password)
  69.                .PasswordNotRequired = String.IsNullOrEmpty(password)
  70.  
  71.                .DisplayName = displayName
  72.                .Description = description
  73.  
  74.                .UserCannotChangePassword = canChangePwd
  75.                .PasswordNeverExpires = pwdExpires
  76.  
  77.                .Enabled = True
  78.                .Save()
  79.  
  80.            End With
  81.  
  82.            Return user
  83.  
  84.        End Using
  85.  
  86.    End Function
  87.  
  88.    ''' ----------------------------------------------------------------------------------------------------
  89.    ''' <remarks>
  90.    ''' Title : Add user-account.
  91.    ''' Author: Elektro
  92.    ''' Date  : 19-June-2015
  93.    ''' </remarks>
  94.    ''' ----------------------------------------------------------------------------------------------------
  95.    ''' <example>
  96.    ''' AddUserAccount(username:="Elektro",
  97.    '''                password:="",
  98.    '''                displayName:="Elektro Account.",
  99.    '''                description:="This is a test user-account.",
  100.    '''                canChangePwd:=True,
  101.    '''                pwdExpires:=False,
  102.    '''                groupSid:=WellKnownSidType.BuiltinAdministratorsSid)
  103.    ''' </example>
  104.    ''' ----------------------------------------------------------------------------------------------------
  105.    ''' <summary>
  106.    ''' Adds a new user account in the current machine.
  107.    ''' </summary>
  108.    ''' ----------------------------------------------------------------------------------------------------
  109.    ''' <param name="username">
  110.    ''' The user name.
  111.    ''' </param>
  112.    '''
  113.    ''' <param name="password">
  114.    ''' The user password.
  115.    ''' If this value is empty, account is set to don't require a password.
  116.    ''' </param>
  117.    '''
  118.    ''' <param name="displayName">
  119.    ''' The display name of the user account.
  120.    ''' </param>
  121.    '''
  122.    ''' <param name="description">
  123.    ''' The description of the user account.
  124.    ''' </param>
  125.    '''
  126.    ''' <param name="canChangePwd">
  127.    ''' A value that indicates whether the user can change its password.
  128.    ''' </param>
  129.    '''
  130.    ''' <param name="pwdExpires">
  131.    ''' A value that indicates whether the password should expire.
  132.    ''' </param>
  133.    '''
  134.    ''' <param name="groupSid">
  135.    ''' A <see cref="WellKnownSidType"/> security identifier (SID) that determines the account group where to add the user.
  136.    ''' </param>
  137.    ''' ----------------------------------------------------------------------------------------------------
  138.    <DebuggerStepThrough>
  139.    Public Shared Sub AddUserAccount(ByVal username As String,
  140.                                     ByVal password As String,
  141.                                     ByVal displayName As String,
  142.                                     ByVal description As String,
  143.                                     ByVal canChangePwd As Boolean,
  144.                                     ByVal pwdExpires As Boolean,
  145.                                     Optional ByVal groupSid As WellKnownSidType = WellKnownSidType.BuiltinUsersSid)
  146.  
  147.        Using context As New PrincipalContext(ContextType.Machine)
  148.  
  149.            Using user As UserPrincipal = CreateUserAccount(username, password, displayName, description, canChangePwd, pwdExpires)
  150.  
  151.                Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.Sid, New SecurityIdentifier(groupSid, Nothing).Value)
  152.  
  153.                    group.Members.Add(user)
  154.                    group.Save()
  155.  
  156.                End Using ' group
  157.  
  158.            End Using ' user
  159.  
  160.        End Using ' context
  161.  
  162.    End Sub
  163.  
  164.    ''' ----------------------------------------------------------------------------------------------------
  165.    ''' <remarks>
  166.    ''' Title : Add user-account.
  167.    ''' Author: Elektro
  168.    ''' Date  : 19-June-2015
  169.    ''' </remarks>
  170.    ''' ----------------------------------------------------------------------------------------------------
  171.    ''' <example>
  172.    ''' AddUserAccount(user:=myUserPrincipal, groupSid:=WellKnownSidType.BuiltinAdministratorsSid)
  173.    ''' </example>
  174.    ''' ----------------------------------------------------------------------------------------------------
  175.    ''' <summary>
  176.    ''' Adds a new user account in the current machine.
  177.    ''' </summary>
  178.    ''' ----------------------------------------------------------------------------------------------------
  179.    ''' <param name="user">
  180.    ''' An <see cref="UserPrincipal"/> object that contains the user data.
  181.    ''' </param>
  182.    '''
  183.    ''' <param name="groupSid">
  184.    ''' A <see cref="WellKnownSidType"/> security identifier (SID) that determines the account group where to add the user.
  185.    ''' </param>
  186.    ''' ----------------------------------------------------------------------------------------------------
  187.    <DebuggerStepThrough>
  188.    Public Shared Sub AddUserAccount(ByVal user As UserPrincipal,
  189.                                     Optional ByVal groupSid As WellKnownSidType = WellKnownSidType.BuiltinUsersSid)
  190.  
  191.        Using context As New PrincipalContext(ContextType.Machine)
  192.  
  193.            Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.Sid, New SecurityIdentifier(groupSid, Nothing).Value)
  194.  
  195.                group.Members.Add(user)
  196.                group.Save()
  197.  
  198.            End Using ' group
  199.  
  200.        End Using ' context
  201.  
  202.    End Sub
« Última modificación: 19 Junio 2015, 12:52 pm por Eleкtro » En línea



Páginas: 1 ... 32 33 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