Autor
|
Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) (Leído 534,420 veces)
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
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: Dim svcName As String = "themes" Dim svcDisplayName As String = ServiceUtils.GetDisplayName(svcName) Dim svcStatus As ServiceControllerStatus = ServiceUtils.GetStatus(svcName) Dim svcStartMode As ServiceUtils.SvcStartMode = ServiceUtils.GetStartMode(svcName) ServiceUtils.SetStartMode(svcName, ServiceUtils.SvcStartMode.Automatic) ServiceUtils.SetStatus(svcName, ServiceUtils.SvcStatus.Stop, wait:=True, throwOnStatusMissmatch:=True)
Source code: ' *********************************************************************** ' Author : Elektro ' Modified : 14-April-2015 ' *********************************************************************** ' <copyright file="ServiceUtils.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " 'Dim svcName As String = "themes" 'Dim svcDisplayName As String = ServiceUtils.GetDisplayName(svcName) 'Dim svcStatus As ServiceControllerStatus = ServiceUtils.GetStatus(svcName) 'Dim svcStartMode As ServiceUtils.SvcStartMode = ServiceUtils.GetStartMode(svcName) 'ServiceUtils.SetStartMode(svcName, ServiceUtils.SvcStartMode.Automatic) 'ServiceUtils.SetStatus(svcName, ServiceUtils.SvcStatus.Stop, wait:=True, throwOnStatusMissmatch:=True) #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports Microsoft.Win32 Imports System.ServiceProcess #End Region ''' <summary> ''' Contains related Windows service tools. ''' </summary> Public NotInheritable Class ServiceUtils #Region " Enumerations " ''' <summary> ''' Indicates the status of a service. ''' </summary> Public Enum SvcStatus ''' <summary> ''' The service is running. ''' </summary> Start ''' <summary> ''' The service is stopped. ''' </summary> [Stop] End Enum ''' <summary> ''' Indicates the start mode of a service. ''' </summary> Public Enum SvcStartMode As Integer ''' <summary> ''' Indicates that the service has not a start mode defined. ''' Since a service should have a start mode defined, this means an error occured retrieving the start mode. ''' </summary> Undefinied = 0 ''' <summary> ''' Indicates that the service is to be started (or was started) by the operating system, at system start-up. ''' The service is started after other auto-start services are started plus a short delay. ''' </summary> AutomaticDelayed = 1 ''' <summary> ''' Indicates that the service is to be started (or was started) by the operating system, at system start-up. ''' If an automatically started service depends on a manually started service, ''' the manually started service is also started automatically at system startup. ''' </summary> Automatic = 2 'ServiceStartMode.Automatic ''' <summary> ''' Indicates that the service is started only manually, ''' by a user (using the Service Control Manager) or by an application. ''' </summary> Manual = 3 'ServiceStartMode.Manual ''' <summary> ''' Indicates that the service is disabled, so that it cannot be started by a user or application. ''' </summary> Disabled = 4 ' ServiceStartMode.Disabled End Enum #End Region #Region " Public Methods " ''' <summary> ''' Retrieves all the services on the local computer, except for the device driver services. ''' </summary> ''' <returns>IEnumerable(Of ServiceController).</returns> Public Shared Function GetServices() As IEnumerable(Of ServiceController) Return ServiceController.GetServices.AsEnumerable End Function ''' <summary> ''' Gets the name of a service. ''' </summary> ''' <param name="svcDisplayName">The service's display name.</param> ''' <returns>The service name.</returns> ''' <exception cref="ArgumentException">Any service found with the specified display name.;svcDisplayName</exception> Public Shared Function GetName(ByVal svcDisplayName As String) As String Dim svc As ServiceController = (From service As ServiceController In ServiceController.GetServices() Where service.DisplayName.Equals(svcDisplayName, StringComparison.OrdinalIgnoreCase) ).FirstOrDefault If svc Is Nothing Then Throw New ArgumentException("Any service found with the specified display name.", "svcDisplayName") Else Using svc Return svc.ServiceName End Using End If End Function ''' <summary> ''' Gets the display name of a service. ''' </summary> ''' <param name="svcName">The service name.</param> ''' <returns>The service's display name.</returns> ''' <exception cref="ArgumentException">Any service found with the specified name.;svcName</exception> Public Shared Function GetDisplayName(ByVal svcName As String) As String Dim svc As ServiceController = (From service As ServiceController In ServiceController.GetServices() Where service.ServiceName.Equals(svcName, StringComparison.OrdinalIgnoreCase) ).FirstOrDefault If svc Is Nothing Then Throw New ArgumentException("Any service found with the specified name.", "svcName") Else Using svc Return svc.DisplayName End Using End If End Function ''' <summary> ''' Gets the status of a service. ''' </summary> ''' <param name="svcName">The service name.</param> ''' <returns>The service status.</returns> ''' <exception cref="ArgumentException">Any service found with the specified name.;svcName</exception> Public Shared Function GetStatus(ByVal svcName As String) As ServiceControllerStatus Dim svc As ServiceController = (From service As ServiceController In ServiceController.GetServices() Where service.ServiceName.Equals(svcName, StringComparison.OrdinalIgnoreCase) ).FirstOrDefault If svc Is Nothing Then Throw New ArgumentException("Any service found with the specified name.", "svcName") Else Using svc Return svc.Status End Using End If End Function ''' <summary> ''' Gets the start mode of a service. ''' </summary> ''' <param name="svcName">The service name.</param> ''' <returns>The service's start mode.</returns> ''' <exception cref="ArgumentException">Any service found with the specified name.</exception> ''' <exception cref="Exception">Registry value "Start" not found for service.</exception> ''' <exception cref="Exception">Registry value "DelayedAutoStart" not found for service.</exception> Public Shared Function GetStartMode(ByVal svcName As String) As SvcStartMode Dim reg As RegistryKey = Nothing Dim startModeValue As Integer = 0 Dim delayedAutoStartValue As Integer = 0 Try reg = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\" & svcName, writable:=False) If reg Is Nothing Then Throw New ArgumentException("Any service found with the specified name.", paramName:="svcName") Else startModeValue = Convert.ToInt32(reg.GetValue("Start", defaultValue:=-1)) delayedAutoStartValue = Convert.ToInt32(reg.GetValue("DelayedAutoStart", defaultValue:=0)) If startModeValue = -1 Then Throw New Exception(String.Format("Registry value ""Start"" not found for service '{0}'.", svcName)) Return SvcStartMode.Undefinied Else Return DirectCast([Enum].Parse(GetType(SvcStartMode), (startModeValue - delayedAutoStartValue).ToString), SvcStartMode) End If End If Catch ex As Exception Throw Finally If reg IsNot Nothing Then reg.Dispose() End If End Try End Function ''' <summary> ''' Gets the start mode of a service. ''' </summary> ''' <param name="svc">The service.</param> ''' <returns>The service's start mode.</returns> Public Shared Function GetStartMode(ByVal svc As ServiceController) As SvcStartMode Return GetStartMode(svc.ServiceName) End Function ''' <summary> ''' Sets the start mode of a service. ''' </summary> ''' <param name="svcName">The service name.</param> ''' <param name="startMode">The start mode.</param> ''' <exception cref="ArgumentException">Any service found with the specified name.</exception> ''' <exception cref="ArgumentException">Unexpected value.</exception> Public Shared Sub SetStartMode(ByVal svcName As String, ByVal startMode As SvcStartMode) Dim reg As RegistryKey = Nothing Try reg = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\" & svcName, writable:=True) If reg Is Nothing Then Throw New ArgumentException("Any service found with the specified name.", paramName:="svcName") Else Select Case startMode Case SvcStartMode.AutomaticDelayed reg.SetValue("DelayedAutoStart", 1, RegistryValueKind.DWord) reg.SetValue("Start", SvcStartMode.Automatic, RegistryValueKind.DWord) Case SvcStartMode.Automatic, SvcStartMode.Manual, SvcStartMode.Disabled reg.SetValue("DelayedAutoStart", 0, RegistryValueKind.DWord) reg.SetValue("Start", startMode, RegistryValueKind.DWord) Case Else Throw New ArgumentException("Unexpected value.", paramName:="startMode") End Select End If Catch ex As Exception Throw Finally If reg IsNot Nothing Then reg.Dispose() End If End Try End Sub ''' <summary> ''' Sets the start mode of a service. ''' </summary> ''' <param name="svc">The service.</param> ''' <param name="startMode">The start mode.</param> Public Shared Sub SetStartMode(ByVal svc As ServiceController, ByVal startMode As SvcStartMode) SetStartMode(svc.ServiceName, startMode) End Sub ''' <summary> ''' Sets the status of a service. ''' </summary> ''' <param name="svcName">The service name.</param> ''' <param name="status">The desired service status.</param> ''' <param name="wait">if set to <c>true</c> waits for the status change completition.</param> ''' <param name="throwOnStatusMissmatch"> ''' If set to <c>true</c> throws an error when attempting to start a service that is started, ''' or attempting to stop a service that is stopped. ''' </param> ''' <exception cref="ArgumentException">Any service found with the specified name.;svcName</exception> ''' <exception cref="ArgumentException">Cannot start service because it is disabled.</exception> ''' <exception cref="ArgumentException">Cannot start service because a dependant service is disabled.</exception> ''' <exception cref="ArgumentException">The service is already running or pendng to run it.</exception> ''' <exception cref="ArgumentException">The service is already stopped or pendng to stop it.</exception> ''' <exception cref="ArgumentException">Unexpected enumeration value.</exception> ''' <exception cref="Exception"></exception> Public Shared Sub SetStatus(ByVal svcName As String, ByVal status As SvcStatus, Optional wait As Boolean = False, Optional ByVal throwOnStatusMissmatch As Boolean = False) Dim svc As ServiceController = Nothing Try svc = (From service As ServiceController In ServiceController.GetServices() Where service.ServiceName.Equals(svcName, StringComparison.OrdinalIgnoreCase) ).FirstOrDefault If svc Is Nothing Then Throw New ArgumentException("Any service found with the specified name.", "svcName") ElseIf GetStartMode(svc) = SvcStartMode.Disabled Then Throw New Exception(String.Format("Cannot start or stop service '{0}' because it is disabled.", svcName)) Else Select Case status Case SvcStatus.Start Select Case svc.Status Case ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending, ServiceControllerStatus.Paused, ServiceControllerStatus.PausePending For Each dependantSvc As ServiceController In svc.ServicesDependedOn If GetStartMode(dependantSvc) = SvcStartMode.Disabled Then Throw New Exception(String.Format("Cannot start service '{0}' because a dependant service '{1}' is disabled.", svcName, dependantSvc.ServiceName)) Exit Select End If Next dependantSvc svc.Start() If wait Then svc.WaitForStatus(ServiceControllerStatus.Running) End If Case ServiceControllerStatus.Running, ServiceControllerStatus.StartPending, ServiceControllerStatus.ContinuePending If throwOnStatusMissmatch Then Throw New Exception(String.Format("The service '{0}' is already running or pendng to run it.", svcName)) End If End Select Case SvcStatus.Stop Select Case svc.Status Case ServiceControllerStatus.Running, ServiceControllerStatus.StartPending, ServiceControllerStatus.ContinuePending svc.Stop() If wait Then svc.WaitForStatus(ServiceControllerStatus.Stopped) End If Case ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending, ServiceControllerStatus.Paused, ServiceControllerStatus.PausePending If throwOnStatusMissmatch Then Throw New Exception(String.Format("The service '{0}' is already stopped or pendng to stop it.", svcName)) End If End Select Case Else Throw New ArgumentException("Unexpected enumeration value.", paramName:="status") End Select End If Catch ex As Exception Throw Finally If svc IsNot Nothing Then svc.Close() End If End Try End Sub #End Region End Class
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
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 ) ' *********************************************************************** ' Author : Elektro ' Modified : 09-April-2015 ' *********************************************************************** ' <copyright file="PathUtil.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Option Statements " Option Explicit On Option Strict On Option Infer Off #End Region #Region " Path Util " Namespace Tools ''' <summary> ''' Contains related PATH and PATHEXT registry tools. ''' </summary> Public NotInheritable Class PathUtil #Region " Properties " ''' <summary> ''' Gets the registry path of the Environment subkey for the current user. ''' </summary> ''' <value>The registry path of the Environment subkey for the current user.</value> Public Shared ReadOnly Property EnvironmentPathCurrentUser As String Get Return "HKEY_CURRENT_USER\Environment" End Get End Property ''' <summary> ''' Gets the registry path of the Environment subkey for all users. ''' </summary> ''' <value>The registry path of the Environment subkey for all users.</value> Public Shared ReadOnly Property EnvironmentPathAllUsers As String Get Return "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" End Get End Property ''' <summary> ''' Gets the default data of the PATH registry value of a 32-Bit Windows. ''' </summary> ''' <value>The default data of the PATH registry value of a 32-Bit Windows.</value> Public Shared ReadOnly Property DefaultPathDataWin32 As String Get Return "C:\Windows;C:\Windows\System32;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0" End Get End Property ''' <summary> ''' Gets the default data of the PATH registry value of a 64-Bit Windows. ''' </summary> ''' <value>The default data of the PATH registry value of a 64-Bit Windows.</value> Public Shared ReadOnly Property DefaultPathDataWin64 As String Get Return "C:\Windows;C:\Windows\System32;C:\Windows\System32\Wbem;C:\Windows\SysWOW64;C:\Windows\System32\WindowsPowerShell\v1.0" End Get End Property ''' <summary> ''' Gets the default data of the PATHEXt registry value. ''' </summary> ''' <value>The default data of the PATHEXt registry value.</value> Public Shared ReadOnly Property DefaultPathExtData As String Get Return ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE" End Get End Property ''' <summary> ''' Gets the registry export string format. ''' </summary> ''' <value>The registry export string format.</value> Private Shared ReadOnly Property ExportStringFormat As String Get Return "Windows Registry Editor Version 5.00{0}{0}" & "[HKEY_CURRENT_USER\Environment]{0}" & """PATH""=""{1}""{0}" & """PATHEXT""=""{2}""{0}{0}" & "[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]{0}" & """PATH""=""{3}""{0}" & """PATHEXT""=""{4}""" End Get End Property #End Region #Region " Enumerations " ''' <summary> ''' Specifies the registry user mode. ''' </summary> Public Enum UserMode ''' <summary> ''' The current user (HKCU). ''' </summary> Current = 0 ''' <summary> ''' All users (HKLM). ''' </summary> AllUsers = 1 End Enum #End Region #Region " Constructors " ''' <summary> ''' Prevents a default instance of the <see cref="PathUtil"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Public Methods " ''' <summary> ''' Gets the default data of the PATH value for the registry of the specified user (as String). ''' </summary> ''' <returns>The default data of the PATH value for the registry of the specified user.</returns> Public Shared Function GetDefaultPathDataString() As String If Not Environment.Is64BitOperatingSystem Then Return DefaultPathDataWin32 Else Return DefaultPathDataWin64 End If End Function ''' <summary> ''' Gets the default data of the PATH value for the registry of the specified user (as Enumerable). ''' </summary> ''' <returns>The default data of the PATH value for the registry of the specified user.</returns> Public Shared Function GetDefaultPathDataList() As IEnumerable(Of String) If Not Environment.Is64BitOperatingSystem Then Return DefaultPathDataWin32.Split({";"c}, StringSplitOptions.RemoveEmptyEntries) Else Return DefaultPathDataWin64.Split({";"c}, StringSplitOptions.RemoveEmptyEntries) End If End Function ''' <summary> ''' Gets the data of the PATH value on the registry of the specified user (as String). ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <returns>The data of the PATH value on the registry of the specified user.</returns> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Function GetPathDataString(ByVal userMode As UserMode) As String Select Case userMode Case PathUtil.UserMode.Current Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH") Case PathUtil.UserMode.AllUsers Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH") Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select End Function ''' <summary> ''' Gets the data of the PATH value on the registry of the specified user (as Enumerable). ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <returns>The data of the PATH value on the registry of the specified user.</returns> Public Shared Function GetPathDataList(ByVal userMode As UserMode) As IEnumerable(Of String) Return GetPathDataString(userMode).Split({";"c}, StringSplitOptions.RemoveEmptyEntries) End Function ''' <summary> ''' Gets the data of the PATHEXT value on the registry of the specified user (as String). ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <returns>The data of the PATHEXT value on the registry of the specified user.</returns> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Function GetPathExtDataString(ByVal userMode As UserMode) As String Select Case userMode Case PathUtil.UserMode.Current Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT") Case PathUtil.UserMode.AllUsers Return RegEdit.GetValueData(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT") Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select End Function ''' <summary> ''' Gets data of the data of the PATHEXT value on the registry of the specified user (as Enumerable). ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <returns>The data of the PATHEXT value on the registry of the specified user.</returns> Public Shared Function GetPathExtDataList(ByVal userMode As UserMode) As IEnumerable(Of String) Return GetPathExtDataString(userMode).Split({";"c}, StringSplitOptions.RemoveEmptyEntries) End Function ''' <summary> ''' Determines whether the PATH value exists on the registry of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <returns><c>true</c> if PATH value exists, <c>false</c> otherwise.</returns> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Function PathExists(ByVal userMode As UserMode) As Boolean Select Case userMode Case PathUtil.UserMode.Current Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH") Case PathUtil.UserMode.AllUsers Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH") Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select End Function ''' <summary> ''' Determines whether the PATHEXT value exists on the registry of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <returns><c>true</c> if PATHEXT value exists, <c>false</c> otherwise.</returns> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Function PathExtExists(ByVal userMode As UserMode) As Boolean Select Case userMode Case PathUtil.UserMode.Current Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT") Case PathUtil.UserMode.AllUsers Return RegEdit.ExistValue(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT") Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select End Function ''' <summary> ''' Exports the PATH and PATHEXT values to a target registry file. ''' </summary> ''' <param name="filepath">The filepath.</param> ''' <exception cref="Exception"></exception> Public Shared Sub Export(ByVal filepath As String) Try IO. File. WriteAllText(filepath, String.Format(ExportStringFormat, Environment.NewLine, GetPathDataString(UserMode.Current), GetPathExtDataString(UserMode.Current), GetPathDataString(UserMode.AllUsers), GetPathExtDataString(UserMode.AllUsers)), encoding:=System.Text.Encoding.Unicode) Catch ex As Exception Throw End Try End Sub ''' <summary> ''' Creates a PATH value on the registry of the specified user and optionally fills the value with the specified data. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Sub CreatePath(ByVal userMode As UserMode, Optional data As String = "") Try Select Case userMode Case PathUtil.UserMode.Current RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH", valueData:=data) Case PathUtil.UserMode.AllUsers RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH", valueData:=data) Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select Catch ex As Exception Throw End Try End Sub ''' <summary> ''' Creates a PATHEXT value on the registry of the specified user and optionally fills the value with the specified data.. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Sub CreatePathExt(ByVal userMode As UserMode, Optional data As String = "") Try Select Case userMode Case PathUtil.UserMode.Current RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT", valueData:=data) Case PathUtil.UserMode.AllUsers RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT", valueData:=data) Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select Catch ex As Exception Throw End Try End Sub ''' <summary> ''' Adds a directory into the PATH registry value of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <param name="directory">The directory path.</param> ''' <exception cref="ArgumentException">Directory contains invalid character(s).;directory</exception> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Sub AddDirectory(ByVal userMode As UserMode, ByVal directory As String) If directory.Any(Function(c As Char) IO.Path.GetInvalidPathChars.Contains(c)) Then Throw New ArgumentException(message:="Directory contains invalid character(s).", paramName:="directory") Else Select Case userMode Case PathUtil.UserMode.Current RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATH", valueData:=String.Join(";"c, GetPathDataList(userMode).Concat({directory}).Distinct).Trim(";"c)) Case PathUtil.UserMode.AllUsers RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATH", valueData:=String.Join(";"c, GetPathDataList(userMode).Concat({directory}).Distinct).Trim(";"c)) Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select End If End Sub ''' <summary> ''' Adds a file extension into the PATHEXT registry value of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <param name="extension">The file extension.</param> ''' <exception cref="ArgumentException">Unexpected enumeration value.;userMode</exception> Public Shared Sub AddExtension(ByVal userMode As UserMode, ByVal extension As String) If Not extension.StartsWith("."c) Then ' Fix extension. extension.Insert(0, "."c) End If Select Case userMode Case PathUtil.UserMode.Current RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathCurrentUser, valueName:="PATHEXT", valueData:=String.Join(";"c, GetPathExtDataList(userMode).Concat({extension})).Trim(";"c)) Case PathUtil.UserMode.AllUsers RegEdit.CreateValue(Of String)(fullKeyPath:=EnvironmentPathAllUsers, valueName:="PATHEXT", valueData:=String.Join(";"c, GetPathExtDataList(userMode).Concat({extension})).Trim(";"c)) Case Else Throw New ArgumentException(message:="Unexpected enumeration value.", paramName:="userMode") End Select End Sub ''' <summary> ''' Deletes a directory from the PATH registry value of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <param name="directory">The directory path.</param> Public Shared Sub DeleteDirectory(ByVal userMode As UserMode, ByVal directory As String) Dim dirs As IEnumerable(Of String) = From dir As String In GetPathDataList(userMode) Where Not dir.ToLower.Equals(directory, StringComparison.OrdinalIgnoreCase) CreatePath(userMode, data:=String.Join(";"c, dirs)) End Sub ''' <summary> ''' Deletes a directory from the PATH registry value of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <param name="index">The directory index, 0 = First.</param> ''' <exception cref="IndexOutOfRangeException">Directory index is out of range.</exception> Public Shared Sub DeleteDirectory(ByVal userMode As UserMode, ByVal index As Integer) Dim dirs As List(Of String) = GetPathDataList(userMode).ToList If (dirs.Count > index) Then dirs.RemoveAt(index) Else Throw New IndexOutOfRangeException(Message:="Directory index is out of range.") End If CreatePath(userMode, data:=String.Join(";"c, dirs)) End Sub ''' <summary> ''' Deletes a file extension from the PATHEXT registry value of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <param name="extension">The file extension.</param> Public Shared Sub DeleteExtension(ByVal userMode As UserMode, ByVal extension As String) If Not extension.StartsWith("."c) Then ' Fix extension. extension.Insert(0, "."c) End If Dim exts As IEnumerable(Of String) = From ext As String In GetPathExtDataList(userMode) Where Not ext.ToLower.Equals(extension, StringComparison.OrdinalIgnoreCase) CreatePath(userMode, data:=String.Join(";"c, exts)) End Sub ''' <summary> ''' Deletes a file extension from the PATHEXT registry value of the specified user. ''' </summary> ''' <param name="userMode">The user mode.</param> ''' <param name="index">The file extension index, 0 = First.</param> ''' <exception cref="IndexOutOfRangeException">File extension index is out of range.</exception> Public Shared Sub DeleteExtension(ByVal userMode As UserMode, ByVal index As Integer) Dim exts As List(Of String) = GetPathExtDataList(userMode).ToList If (exts.Count > index) Then exts.RemoveAt(index) Else Throw New IndexOutOfRangeException(Message:="File extension index is out of range.") End If CreatePathExt(userMode, data:=String.Join(";"c, exts)) End Sub ''' <summary> ''' Determines whether the PATH registry value of the specified user contains a directory. ''' </summary> ''' <param name="usermode">The usermode.</param> ''' <param name="directory">The directory path.</param> ''' <returns><c>true</c> if contains the specified directory; <c>false</c> otherwise.</returns> Public Shared Function ContainsDirectory(ByVal usermode As UserMode, ByVal directory As String) As Boolean Return GetPathDataList(usermode).Any(Function(dir As String) dir.Equals(directory, StringComparison.OrdinalIgnoreCase)) End Function ''' <summary> ''' Determines whether the PATHEXT registry value of the specified user contains a directory. ''' </summary> ''' <param name="usermode">The usermode.</param> ''' <param name="extension">The file extension.</param> ''' <returns><c>true</c> if contains the specified file extension; <c>false</c> otherwise.</returns> Public Shared Function ContainsExtension(ByVal usermode As UserMode, ByVal extension As String) As Boolean If Not extension.StartsWith("."c) Then ' Fix extension. extension.Insert(0, "."c) End If Return GetPathExtDataList(usermode).Any(Function(ext As String) ext.Equals(extension, StringComparison.OrdinalIgnoreCase)) End Function #End Region End Class End Namespace #End Region
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
Una Class para administrar un archivo de recursos de .Net ( file.resx ) ' *********************************************************************** ' Author : Elektro ' Modified : 16-March-2015 ' *********************************************************************** ' <copyright file="ResXManager.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Usage Examples " 'Imports System.IO 'Imports System.Text 'Public Class Form1 ' Private Sub Test() Handles MyBase.Shown ' Dim resX As New ResXManager(Path.Combine(Application.StartupPath, "MyResources.resx")) ' With resX ' ' Create or replace the ResX file. ' .Create(replace:=True) ' ' Add a string resource. ' .AddResource(Of String)("String Resource", "Hello World!", "String Comment") ' ' Add a bitmap resource. ' .AddResource(Of Bitmap)("Bitmap Resource", SystemIcons.Information.ToBitmap, "Bitmap Comment") ' ' Add a binary resource. ' .AddResource(Of Byte())("Binary Resource", File.ReadAllBytes("C:\file.mp3"), "Binary Comment") ' End With ' ' ******************************************************************************************************* ' ' Get the string resource. ' Dim stringResource As ResXManager.Resource(Of String) = ' resX.FindResource(Of String)("String Resource", StringComparison.OrdinalIgnoreCase) ' ' Get the bitmap resource. ' Dim bitmapResource As ResXManager.Resource(Of Bitmap) = ' resX.FindResource(Of Bitmap)("Bitmap Resource", StringComparison.OrdinalIgnoreCase) ' ' Get the binary resource. ' Dim binaryResource As ResXManager.Resource(Of Byte()) = ' resX.FindResource(Of Byte())("Binary Resource", StringComparison.OrdinalIgnoreCase) ' ' ******************************************************************************************************* ' ' Get the string data. ' Dim stringData As String = stringResource.Data ' ' Get the bitmap data. ' Dim bitmapData As Bitmap = bitmapResource.Data ' ' Get the binary data. ' Dim binaryData As Byte() = binaryResource.Data ' ' ******************************************************************************************************* ' ' Get all the resources at once. ' Dim resources As IEnumerable(Of ResXManager.Resource) = resX.Resources ' ' Get all the resources of specific Type at once. ' Dim stringResources As IEnumerable(Of ResXManager.Resource(Of String)) = resX.FindResources(Of String)() ' ' ******************************************************************************************************* ' ' Get all the resource datas at once from Resource collection. ' Dim resourceDatas As IEnumerable(Of Object) = ' From res As ResXManager.Resource In resX.Resources ' Select res.Data ' ' Get all the resource datas of specific Type at once from Resource collection. ' Dim stringResourceDatas As IEnumerable(Of String) = ' From res As ResXManager.Resource In resX.Resources ' Where res.Type Is GetType(String) ' Select DirectCast(res.Data, String) ' ' ******************************************************************************************************* ' ' Treat the string data as you like. ' MessageBox.Show(stringData, String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information) ' ' Treat the bitmap data as you like. ' Me.Icon = Icon.FromHandle(bitmapData.GetHicon) ' ' Treat the binary data as you like. ' File.WriteAllBytes("C:\new file.mp3", binaryData) ' ' ******************************************************************************************************* ' ' Iterate all the resources. ' For Each res As ResXManager.Resource In resX.Resources ' Dim sb As New StringBuilder ' sb.AppendLine(String.Format("Name...: {0}", res.Name)) ' sb.AppendLine(String.Format("Comment: {0}", res.Comment)) ' sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString)) ' sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString)) ' MsgBox(sb.ToString) ' Next ' ' Iterate all the resources of specific Type. ' For Each res As ResXManager.Resource(Of String) In resX.FindResources(Of String)() ' Dim sb As New StringBuilder ' sb.AppendLine(String.Format("Name...: {0}", res.Name)) ' sb.AppendLine(String.Format("Comment: {0}", res.Comment)) ' sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString)) ' sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString)) ' MsgBox(sb.ToString) ' Next ' ' ******************************************************************************************************* ' ' Remove a resource. ' resX.RemoveResource("Binary Resource") ' ' GC.Collect() ' End Sub 'End Class #End Region #Region " Imports " Imports System.ComponentModel Imports System.ComponentModel.Design Imports System.IO Imports System.Resources #End Region ''' <summary> ''' Manages a .Net managed resource file. ''' </summary> Public NotInheritable Class ResXManager #Region " Properties " ''' <summary> ''' Gets the .Net managed resource file path. ''' </summary> ''' <value>The .Net managed resource filepath.</value> Public ReadOnly Property FilePath As String Get Return Me.filePath1 End Get End Property ''' <summary> ''' The .Net managed resource file path. ''' </summary> Private ReadOnly filePath1 As String ''' <summary> ''' Gets the resources contained in the .Net managed resource file. ''' </summary> ''' <value>The resources.</value> Public ReadOnly Property Resources As IEnumerable(Of Resource) Get Return GetResources() End Get End Property #End Region #Region " Types " #Region " Resource " ''' <summary> ''' Defines a resource of a .Net managed resource file. ''' </summary> <Serializable> Public NotInheritable Class Resource #Region " Properties " ''' <summary> ''' Gets the resource name. ''' </summary> ''' <value>The resource name.</value> Public ReadOnly Property Name As String Get Return Me.name1 End Get End Property Private ReadOnly name1 As String ''' <summary> ''' Gets the resource data. ''' </summary> ''' <value>The resource data.</value> Public ReadOnly Property Data As Object Get Return Me.data1 End Get End Property Private ReadOnly data1 As Object ''' <summary> ''' Gets the resource type. ''' </summary> ''' <value>The resource type.</value> Public ReadOnly Property Type As Type Get Return Data.GetType End Get End Property ''' <summary> ''' Gets the resource comment. ''' </summary> ''' <value>The resource comment.</value> Public ReadOnly Property Comment As String Get Return comment1 End Get End Property Private ReadOnly comment1 As String ''' <summary> ''' Represents a <see cref="Resource"/> instance that is <c>Nothing</c>. ''' </summary> ''' <value><c>Nothing</c></value> <EditorBrowsable(EditorBrowsableState.Advanced)> Public Shared ReadOnly Property Empty As Resource Get Return Nothing End Get End Property #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="Resource"/> class. ''' </summary> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> Public Sub New(ByVal name As String, ByVal data As Object, ByVal comment As String) Me.name1 = name Me.data1 = data Me.comment1 = comment End Sub ''' <summary> ''' Prevents a default instance of the <see cref="Resource"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Hidden Methods " ''' <summary> ''' Determines whether the specified System.Object instances are considered equal. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function Equals(ByVal obj As Object) As Boolean Return MyBase.Equals(obj) End Function ''' <summary> ''' Serves as a hash function for a particular type. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function GetHashCode() As Integer Return MyBase.GetHashCode End Function ''' <summary> ''' Gets the System.Type of the current instance. ''' </summary> ''' <returns>The exact runtime type of the current instance.</returns> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function [GetType]() As Type Return MyBase.GetType End Function ''' <summary> ''' Returns a String that represents the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function ToString() As String Return MyBase.ToString End Function #End Region End Class #End Region #Region " Resource(Of T) " ''' <summary> ''' Defines a resource of a .Net managed resource file. ''' </summary> <Serializable> Public NotInheritable Class Resource(Of T) #Region " Properties " ''' <summary> ''' Gets the resource name. ''' </summary> ''' <value>The resource name.</value> Public ReadOnly Property Name As String Get Return Me.name1 End Get End Property Private ReadOnly name1 As String ''' <summary> ''' Gets the resource data. ''' </summary> ''' <value>The resource data.</value> Public ReadOnly Property Data As T Get Return Me.data1 End Get End Property Private ReadOnly data1 As T ''' <summary> ''' Gets the resource type. ''' </summary> ''' <value>The resource type.</value> Public ReadOnly Property Type As Type Get Return GetType(T) End Get End Property ''' <summary> ''' Gets the resource comment. ''' </summary> ''' <value>The resource comment.</value> Public ReadOnly Property Comment As String Get Return comment1 End Get End Property Private ReadOnly comment1 As String #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="Resource(Of T)"/> class. ''' </summary> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> Public Sub New(ByVal name As String, ByVal data As T, ByVal comment As String) Me.name1 = name Me.data1 = data Me.comment1 = comment End Sub ''' <summary> ''' Prevents a default instance of the <see cref="Resource(Of T)"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Hidden Methods " ''' <summary> ''' Determines whether the specified System.Object instances are considered equal. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function Equals(ByVal obj As Object) As Boolean Return MyBase.Equals(obj) End Function ''' <summary> ''' Serves as a hash function for a particular type. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function GetHashCode() As Integer Return MyBase.GetHashCode End Function ''' <summary> ''' Gets the System.Type of the current instance. ''' </summary> ''' <returns>The exact runtime type of the current instance.</returns> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function [GetType]() As Type Return MyBase.GetType End Function ''' <summary> ''' Returns a String that represents the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function ToString() As String Return MyBase.ToString End Function #End Region End Class #End Region #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="ResXManager"/> class. ''' </summary> ''' <param name="resxFilePath">The .Net managed resource filepath.</param> Public Sub New(ByVal resxFilePath As String) Me.filePath1 = resxFilePath End Sub ''' <summary> ''' Prevents a default instance of the <see cref="ResXManager"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Public Methods " ''' <summary> ''' Creates the .Net managed resource file. ''' </summary> ''' <param name="replace">if set to <c>true</c>, replaces any existent file.</param> ''' <exception cref="System.Exception"></exception> Public Sub Create(Optional ByVal replace As Boolean = False) If Not replace AndAlso File. Exists(Me. filePath1) Then Throw New Exception(String.Format("Resource file already exists: {0}", Me.filePath1)) Exit Sub End If Dim resXWritter As ResXResourceWriter = Nothing Try resXWritter = New ResXResourceWriter(Me.filePath1) Using resXWritter resXWritter.Generate() End Using Catch ex As Exception Throw Finally If resXWritter IsNot Nothing Then resXWritter.Close() End If End Try End Sub ''' <summary> ''' Adds a resource into the .Net managed resource file. ''' </summary> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception> Public Sub AddResource(ByVal name As String, ByVal data As Object, Optional ByVal comment As String = Nothing) Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment) End Sub ''' <summary> ''' Adds a specified resource of the specified type into the .Net managed resource file. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception> Public Sub AddResource(Of T)(ByVal name As String, ByVal data As T, Optional ByVal comment As String = Nothing) Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment) End Sub ''' <summary> ''' Replaces a resource by the specified name inside the .Net managed resource file. ''' </summary> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception> Public Sub ReplaceResource(ByVal name As String, ByVal data As Object, Optional ByVal comment As String = Nothing) Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment) End Sub ''' <summary> ''' Replaces a resource by the specified name of the specified type inside the .Net managed resource file. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception> Public Sub ReplaceResource(Of T)(ByVal name As String, ByVal data As T, Optional ByVal comment As String = Nothing) Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment) End Sub ''' <summary> ''' Finds a resource by the specified name of specified type inside the .Net managed resource file. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="name">The resource name.</param> ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param> ''' <returns>The resource.</returns> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception> ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception> Public Function FindResource(Of T)(ByVal name As String, Optional ByVal stringComparison As StringComparison = StringComparison.OrdinalIgnoreCase) As Resource(Of T) If Not File. Exists(Me. filePath1) Then Throw New FileNotFoundException("Resource file not found.", Me.filePath1) Exit Function End If ' Read the ResX file. Dim resX As ResXResourceReader = Nothing Dim res As Resource(Of T) = Nothing Try resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True} Using resX For Each entry As DictionaryEntry In resX If entry.Key.ToString.Equals(name, stringComparison) Then Dim node As ResXDataNode = CType(entry.Value, ResXDataNode) res = New Resource(Of T)(name:=node.Name, data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T), comment:=node.Comment) Exit For End If Next entry End Using ' resX Return res Catch ex As Exception Throw Finally If resX IsNot Nothing Then resX.Close() End If End Try End Function ''' <summary> ''' Finds a resource by the specified name inside the .Net managed resource file. ''' </summary> ''' <param name="name">The resource name.</param> ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param> ''' <returns>The resource.</returns> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception> ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception> Public Function FindResource(ByVal name As String, Optional ByVal stringComparison As StringComparison = StringComparison.OrdinalIgnoreCase) As Resource If Not File. Exists(Me. filePath1) Then Throw New FileNotFoundException("Resource file not found.", Me.filePath1) Exit Function End If ' Read the ResX file. Dim resX As ResXResourceReader = Nothing Dim res As Resource = Nothing Try resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True} Using resX For Each entry As DictionaryEntry In resX If entry.Key.ToString.Equals(name, stringComparison) Then Dim node As ResXDataNode = CType(entry.Value, ResXDataNode) res = New Resource(name:=node.Name, data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)), comment:=node.Comment) Exit For End If Next entry End Using ' resX Return res Catch ex As Exception Throw Finally If resX IsNot Nothing Then resX.Close() End If End Try End Function ''' <summary> ''' Finds the resources of the specified type inside the .Net managed resource file. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <returns>The resource.</returns> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception> ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception> Public Iterator Function FindResources(Of T)() As IEnumerable(Of Resource(Of T)) If Not File. Exists(Me. filePath1) Then Throw New FileNotFoundException("Resource file not found.", Me.filePath1) Exit Function End If ' Read the ResX file. Dim resX As ResXResourceReader = Nothing Try resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True} Using resX For Each entry As DictionaryEntry In resX Dim node As ResXDataNode = CType(entry.Value, ResXDataNode) If node.GetValue(DirectCast(Nothing, ITypeResolutionService)).GetType Is GetType(T) Then Yield New Resource(Of T)(name:=node.Name, data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T), comment:=node.Comment) End If Next entry End Using ' resX Catch ex As Exception Throw Finally If resX IsNot Nothing Then resX.Close() End If End Try End Function ''' <summary> ''' Removes a resource by the specified name from the .Net managed resource file. ''' </summary> ''' <param name="name">The resource name.</param> ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">Any resource found matching the specified name.;name</exception> Public Sub RemoveResource(ByVal name As String, Optional ByVal stringComparison As StringComparison = StringComparison.OrdinalIgnoreCase) If Not File. Exists(Me. filePath1) Then Throw New FileNotFoundException("Resource file not found.", Me.filePath1) Exit Sub End If If Me.FindResource(name, stringComparison) Is Nothing Then Throw New ArgumentException("Any resource found matching the specified name.", "name") Exit Sub End If Dim resources As New List(Of ResXDataNode) Dim resX As ResXResourceReader = Nothing Dim resXWritter As ResXResourceWriter = Nothing Try resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True} Using resX For Each entry As DictionaryEntry In resX If Not entry.Key.ToString.Equals(name, stringComparison) Then Dim node As ResXDataNode = CType(entry.Value, ResXDataNode) resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment}) End If Next entry End Using ' Add the resource in the ResX file. ' Note: This will replace the current ResX file. resXWritter = New ResXResourceWriter(Me.filePath1) Using resXWritter ' Add the retrieved resources into the ResX file. If resources IsNot Nothing Then For Each resourceItem As ResXDataNode In resources resXWritter.AddResource(resourceItem) Next resourceItem End If resXWritter.Generate() End Using ' resXWritter Catch ex As Exception Throw Finally If resX IsNot Nothing Then resX.Close() End If If resXWritter IsNot Nothing Then resXWritter.Close() End If resources.Clear() End Try End Sub #End Region #Region " Private Methods " ''' <summary> ''' Adds or replaces a resource into the .Net managed resource file. ''' </summary> ''' <param name="replace">if set to <c>true</c>, the resource will be replaced.</param> ''' <param name="name">The resource name.</param> ''' <param name="data">The resource data.</param> ''' <param name="comment">The resource comment.</param> ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception> ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception> Private Sub AddResource(ByVal replace As Boolean, ByVal name As String, ByVal data As Object, ByVal comment As String) If Not File. Exists(Me. filePath1) Then Throw New FileNotFoundException("Resource file not found.", Me.filePath1) Exit Sub End If Dim resources As New List(Of ResXDataNode) Dim resX As ResXResourceReader = Nothing Dim resXWritter As ResXResourceWriter = Nothing Try resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True} Using resX For Each entry As DictionaryEntry In resX If Not replace AndAlso entry.Key.ToString.Equals(name, StringComparison.OrdinalIgnoreCase) Then Throw New ArgumentException("A resource with the same name already exists in the table.", "name") Else Dim node As ResXDataNode = CType(entry.Value, ResXDataNode) resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment}) End If Next entry End Using ' Add the resource in the ResX file. ' Note: This will replace the current ResX file. resXWritter = New ResXResourceWriter(Me.filePath1) Using resXWritter ' Add the retrieved resources into the ResX file. If resources IsNot Nothing Then For Each resourceItem As ResXDataNode In resources resXWritter.AddResource(resourceItem) Next resourceItem End If ' Add the specified resource into the ResX file. resXWritter.AddResource(New ResXDataNode(name, data) With {.Name = name, .Comment = comment}) resXWritter.Generate() End Using ' resXWritter Catch ex As Exception Throw Finally If resX IsNot Nothing Then resX.Close() End If If resXWritter IsNot Nothing Then resXWritter.Close() End If resources.Clear() End Try End Sub ''' <summary> ''' Gets all the resources contained in the .Net managed resource file. ''' </summary> ''' <returns>IEnumerable(Of Resource).</returns> Private Iterator Function GetResources() As IEnumerable(Of Resource) ' Read the ResX file. Using resX As New Resources.ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True} For Each entry As DictionaryEntry In resX Dim node As ResXDataNode = CType(entry.Value, ResXDataNode) Yield New Resource(name:=node.Name, data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)), comment:=node.Comment) Next entry End Using ' resX End Function #End Region #Region " Hidden Methods " ''' <summary> ''' Determines whether the specified System.Object instances are considered equal. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function Equals(ByVal obj As Object) As Boolean Return MyBase.Equals(obj) End Function ''' <summary> ''' Serves as a hash function for a particular type. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function GetHashCode() As Integer Return MyBase.GetHashCode End Function ''' <summary> ''' Gets the System.Type of the current instance. ''' </summary> ''' <returns>The exact runtime type of the current instance.</returns> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function [GetType]() As Type Return MyBase.GetType End Function ''' <summary> ''' Returns a String that represents the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Function ToString() As String Return MyBase.ToString End Function #End Region End Class
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
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: Imports PostSharp.Aspects Public Class MyClass <RangeAttribute(0S, SByte.MaxValue)> Dim sByteValue As SByte <RangeAttribute(0S, Byte.MaxValue)> Dim ByteValue As Byte <RangeAttribute(0S, Short.MaxValue)> Dim Int16Value As Short <RangeAttribute(0US, UShort.MaxValue)> Dim UInt16Value As UShort <RangeAttribute(0I, Integer.MaxValue)> Dim Int32Value As Integer <RangeAttribute(0UI, UInteger.MaxValue)> Dim UInt32Value As UInteger <RangeAttribute(0L, Long.MaxValue)> Dim Int64Value As Long <RangeAttribute(0UL, ULong.MaxValue)> Dim UInt64Value As ULong <RangeAttribute(0.0F, Single.MaxValue)> Dim SglValue As Single <RangeAttribute(0.0R, Double.MaxValue)> Dim DblValue As Double End Class
Código fuente: ' *********************************************************************** ' Author : Elektro ' Modified : 07-June-2015 ' *********************************************************************** ' <copyright file="RangeAttribute.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " 'Imports PostSharp.Aspects ' 'Public Class Myclass ' ' <RangeAttribute(0S, SByte.MaxValue)> ' Dim sByteValue As SByte ' ' <RangeAttribute(0S, Byte.MaxValue)> ' Dim ByteValue As Byte ' ' <RangeAttribute(0S, Short.MaxValue)> ' Dim Int16Value As Short ' ' <RangeAttribute(0US, UShort.MaxValue)> ' Dim UInt16Value As UShort ' ' <RangeAttribute(0I, Integer.MaxValue)> ' Dim Int32Value As Integer ' ' <RangeAttribute(0UI, UInteger.MaxValue)> ' Dim UInt32Value As UInteger ' ' <RangeAttribute(0L, Long.MaxValue)> ' Dim Int64Value As Long ' ' <RangeAttribute(0UL, ULong.MaxValue)> ' Dim UInt64Value As ULong ' ' <RangeAttribute(0.0F, Single.MaxValue)> ' Dim SglValue As Single ' ' <RangeAttribute(0.0R, Double.MaxValue)> ' Dim DblValue As Double ' 'End Class #End Region #Region " Imports " Imports PostSharp.Aspects #End Region #Region " Range Attribute " ''' <summary> ''' Aspect that when applied to a property, defines its minimum and maximum value. ''' </summary> <Serializable> Public Class RangeAttribute : Inherits LocationInterceptionAspect #Region " Properties " ''' <summary> ''' Gets or sets the minimum value. ''' </summary> Private Property Min As Object ''' <summary> ''' Gets or sets the maximum value. ''' </summary> Private Property Max As Object #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="SByte"/> datatype. ''' </summary> ''' <param name="minInt8">The minimum <see cref="SByte"/> value.</param> ''' <param name="maxInt8">The maximum <see cref="SByte"/> value.</param> Public Sub New(ByVal minInt8 As SByte, ByVal maxInt8 As SByte) Me.Min = minInt8 Me.Max = maxInt8 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Byte"/> datatype. ''' </summary> ''' <param name="minUInt8">The minimum <see cref="Byte"/> value.</param> ''' <param name="maxUInt8">The maximum <see cref="Byte"/> value.</param> Public Sub New(ByVal minUInt8 As Byte, ByVal maxUInt8 As Byte) Me.Min = minUInt8 Me.Max = maxUInt8 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Short"/> datatype. ''' </summary> ''' <param name="minInt16">The minimum <see cref="Short"/> value.</param> ''' <param name="maxInt16">The maximum <see cref="Short"/> value.</param> Public Sub New(ByVal minInt16 As Short, ByVal maxInt16 As Short) Me.Min = minInt16 Me.Max = maxInt16 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="UShort"/> datatype. ''' </summary> ''' <param name="minUInt16">The minimum <see cref="UShort"/> value.</param> ''' <param name="maxUInt16">The maximum <see cref="UShort"/> value.</param> Public Sub New(ByVal minUInt16 As UShort, ByVal maxUInt16 As UShort) Me.Min = minUInt16 Me.Max = maxUInt16 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Integer"/> datatype. ''' </summary> ''' <param name="minInt32">The minimum <see cref="Integer"/> value.</param> ''' <param name="maxInt32">The maximum <see cref="Integer"/> value.</param> Public Sub New(ByVal minInt32 As Integer, ByVal maxInt32 As Integer) Me.Min = minInt32 Me.Max = maxInt32 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="UInteger"/> datatype. ''' </summary> ''' <param name="minUInt32">The minimum <see cref="UInteger"/> value.</param> ''' <param name="maxUInt32">The maximum <see cref="UInteger"/> value.</param> Public Sub New(ByVal minUInt32 As UInteger, ByVal maxUInt32 As UInteger) Me.Min = minUInt32 Me.Max = maxUInt32 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Long"/> datatype. ''' </summary> ''' <param name="minInt64">The minimum <see cref="Long"/> value.</param> ''' <param name="maxInt64">The maximum <see cref="Long"/> value.</param> Public Sub New(ByVal minInt64 As Long, ByVal maxInt64 As Long) Me.Min = minInt64 Me.Max = maxInt64 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="ULong"/> datatype. ''' </summary> ''' <param name="minUInt64">The minimum <see cref="ULong"/> value.</param> ''' <param name="maxUInt64">The maximum <see cref="ULong"/> value.</param> Public Sub New(ByVal minUInt64 As ULong, ByVal maxUInt64 As ULong) Me.Min = minUInt64 Me.Max = maxUInt64 End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Single"/> datatype. ''' </summary> ''' <param name="minSingle">The minimum <see cref="Single"/> value.</param> ''' <param name="maxSingle">The maximum <see cref="Single"/> value.</param> Public Sub New(ByVal minSingle As Single, ByVal maxSingle As Single) Me.Min = minSingle Me.Max = maxSingle End Sub ''' <summary> ''' Initializes a new instance of the <see cref="RangeAttribute"/> class for <see cref="Double"/> datatype. ''' </summary> ''' <param name="minDouble">The minimum <see cref="Double"/> value.</param> ''' <param name="maxDouble">The maximum <see cref="Double"/> value.</param> Public Sub New(ByVal minDouble As Double, ByVal maxDouble As Double) Me.Min = minDouble Me.Max = maxDouble End Sub ''' <summary> ''' Prevents a default instance of the <see cref="RangeAttribute"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Methods " ''' <summary> ''' Method invoked <i>instead</i> of the <c>Set</c> semantic of the field or property to which the current aspect is applied, ''' i.e. when the value of this field or property is changed. ''' </summary> ''' <param name="args">Advice arguments.</param> Public Overrides Sub OnSetValue(ByVal args As LocationInterceptionArgs) Dim value As Object = args.Value Select Case True Case TypeOf value Is SByte If DirectCast(value, SByte) < CSByte(Me.Min) Then value = Me.Min ElseIf DirectCast(value, SByte) > CSByte(Me.Max) Then value = Me.Max End If args.SetNewValue(CSByte(value)) Case TypeOf value Is Byte If DirectCast(value, Byte) < CByte(Me.Min) Then value = Me.Min ElseIf DirectCast(value, Byte) > CByte(Me.Max) Then value = Me.Max End If args.SetNewValue(CByte(value)) Case TypeOf value Is Short If DirectCast(value, Short) < CShort(Me.Min) Then value = Me.Min ElseIf DirectCast(value, Short) > CShort(Me.Max) Then value = Me.Max End If args.SetNewValue(CShort(value)) Case TypeOf value Is UShort If DirectCast(value, UShort) < CUShort(Me.Min) Then value = Me.Min ElseIf DirectCast(value, UShort) > CUShort(Me.Max) Then value = Me.Max End If args.SetNewValue(CUShort(value)) Case TypeOf value Is Integer If DirectCast(value, Integer) < CInt(Me.Min) Then value = Me.Min ElseIf DirectCast(value, Integer) > CInt(Me.Max) Then value = Me.Max End If args.SetNewValue(CInt(value)) Case TypeOf value Is UInteger If DirectCast(value, UInteger) < CUInt(Me.Min) Then value = Me.Min ElseIf DirectCast(value, UInteger) > CUInt(Me.Max) Then value = Me.Max End If args.SetNewValue(CUInt(value)) Case TypeOf value Is Long If DirectCast(value, Long) < CLng(Me.Min) Then value = Me.Min ElseIf DirectCast(value, Long) > CLng(Me.Max) Then value = Me.Max End If args.SetNewValue(CLng(value)) Case TypeOf value Is ULong If DirectCast(value, ULong) < CULng(Me.Min) Then value = Me.Min ElseIf DirectCast(value, ULong) > CULng(Me.Max) Then value = Me.Max End If args.SetNewValue(CULng(value)) Case TypeOf value Is Single If DirectCast(value, Single) < CSng(Me.Min) Then value = Me.Min ElseIf DirectCast(value, Single) > CSng(Me.Max) Then value = Me.Max End If args.SetNewValue(CSng(value)) Case TypeOf value Is Double If DirectCast(value, Double) < CDbl(Me.Min) Then value = Me.Min ElseIf DirectCast(value, Double) > CDbl(Me.Max) Then value = Me.Max End If args.SetNewValue(CDbl(value)) End Select End Sub #End Region End Class #End Region
|
|
« Última modificación: 7 Junio 2015, 10:46 am por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
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: Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider Dim resultVB As CompilerResults = CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider, targetAssembly:=CodeDomUtil.TargetAssembly.Dll, targetFile:="C:\VB Assembly.dll", resources:={"C:\MyResources.resx"}, referencedAssemblies:={"System.dll"}, mainClassName:="MainNamespace.MainClass", sourceCode:=<a> Imports System Namespace MainNamespace Public NotInheritable MainClass End Class End Namespace </a>.Value) Dim warnings As IEnumerable(Of CompilerError) = From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)() Where ce.IsWarning Dim errors As IEnumerable(Of CompilerError) = From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)() Where Not ce.IsWarning For Each war As CompilerError In warnings Debug. WriteLine(String. Format("{0}| Warning: {1}", war. ErrorNumber, war. ErrorText)) Next war For Each err As CompilerError In errors Debug. WriteLine(String. Format("{0}| Error: {1}", err. ErrorNumber, err. ErrorText)) End Using
Código fuente: ''' <summary> ''' Specifies a <see cref="CompilerParameters"></see> target assembly. ''' </summary> Public Enum TargetAssembly As Integer ''' <summary> ''' A Command line interface executable. ''' </summary> Cli = 0 ''' <summary> ''' A Graphical user interface executable. ''' </summary> Gui = 1 ''' <summary> ''' A Dynamic-link library. ''' </summary> Dll = 2 End Enum ''' <remarks> ''' ***************************************************************** ''' Title : Compile Assembly (from reaource). ''' Author: Elektro ''' Date : 14-June-2015 ''' Usage : ''' ''' Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider ''' ''' Dim resultVB As CompilerResults = ''' CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider, ''' targetAssembly:=CodeDomUtil.TargetAssembly.Dll, ''' targetFile:="C:\VB Assembly.dll", ''' resources:={"C:\MyResources.resx"}, ''' referencedAssemblies:={"System.dll"}, ''' mainClassName:="MainNamespace.MainClass", ''' sourceCode:=<a> ''' Imports System ''' ''' Namespace MainNamespace ''' ''' Public NotInheritable MainClass ''' ''' End Class ''' ''' End Namespace ''' </a>.Value) ''' ''' Dim warnings As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)() ''' Where ce.IsWarning ''' ''' Dim errors As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)() ''' Where Not ce.IsWarning ''' ''' For Each war As CompilerError In warnings ''' Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText)) ''' Next war ''' ''' For Each err As CompilerError In errors ''' Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText)) ''' Next err ''' ''' End Using ''' ----------------------------------------------------------------- ''' Using csCodeProvider As New Microsoft.CSharp.CSharpCodeProvider ''' ''' Dim resultCS As CompilerResults = ''' CodeDomUtil.CompileAssembly(codeProvider:=csCodeProvider, ''' targetAssembly:=CodeDomUtil.TargetAssembly.Dll, ''' targetFile:="C:\C# Assembly.dll", ''' resources:={"C:\MyResources.resx"}, ''' referencedAssemblies:={"System.dll"}, ''' mainClassName:="MainNamespace.MainClass", ''' sourceCode:=<a> ''' using System; ''' ''' namespace MainNamespace ''' { ''' class MainClass ''' { ''' ''' } ''' } ''' </a>.Value) ''' ''' Dim warnings As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)() ''' Where ce.IsWarning ''' ''' Dim errors As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)() ''' Where Not ce.IsWarning ''' ''' For Each war As CompilerError In warnings ''' Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText)) ''' Next war ''' ''' For Each err As CompilerError In errors ''' Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText)) ''' Next err ''' ''' End Using ''' ***************************************************************** ''' </remarks> ''' <summary> ''' Compiles a .Net assembly as executable or link library. ''' </summary> ''' <param name="codeProvider">The code provider.</param> ''' <param name="targetAssembly">The kind of assembly to generate.</param> ''' <param name="targetFile">The target file to create.</param> ''' <param name="resources">The embedded resources (if any).</param> ''' <param name="referencedAssemblies">The referenced assemblies (if any).</param> ''' <param name="mainClassName">The code to compile (if any).</param> ''' <param name="sourceCode">The sourcecode to compile (if any).</param> ''' <exception cref="Exception">The current CodeDomProvider does not support resource embedding.</exception> ''' <exception cref="NotImplementedException">Default sourcecode is not implemented for the specified CodeDomProvider. Please, set a sourcecode yourself.</exception> ''' <returns>The results of the compiler operation.</returns> Public Shared Function CompileAssembly(ByVal codeProvider As CodeDomProvider, ByVal targetAssembly As TargetAssembly, ByVal targetFile As String, Optional ByVal resources As IEnumerable(Of String) = Nothing, Optional ByVal referencedAssemblies As IEnumerable(Of String) = Nothing, Optional ByVal mainClassName As String = "MainNamespace.MainClass", Optional ByVal sourceCode As String = Nothing) As CompilerResults ' Set a default assembly reference. If referencedAssemblies Is Nothing Then referencedAssemblies = {"System.dll"} End If Dim cp As New CompilerParameters With cp ' Set compiler arguments. Select Case targetAssembly Case CodeDomUtil.TargetAssembly.Gui .CompilerOptions = "/optimize /target:winexe" Case Else .CompilerOptions = "/optimize" End Select ' Generate an exe or a dll. .GenerateExecutable = (targetAssembly <> CodeDomUtil.TargetAssembly.Dll) ' Save the assembly as a physical file. .GenerateInMemory = False ' Generate debug information (pdb). .IncludeDebugInformation = False ' Set the assembly file name to generate. .OutputAssembly = targetFile ' Add an assembly reference. .ReferencedAssemblies.AddRange(referencedAssemblies.ToArray) ' Set a temporary files collection. ' The TempFileCollection stores the temporary files generated during a build in the current directory. .TempFiles = New TempFileCollection(tempdir:=IO.Path.GetTempPath(), keepFiles:=True) ' Set whether to treat all warnings as errors. .TreatWarningsAsErrors = False ' Set the level at which the compiler should start displaying warnings. ' 0 - Turns off emission of all warning messages. ' 1 - Displays severe warning messages. ' 2 - Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members. ' 3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false. ' 4 - Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line. .WarningLevel = 3 ' Set the embedded resource file of the assembly. If codeProvider.Supports(GeneratorSupport.Resources) AndAlso (resources IsNot Nothing) Then .EmbeddedResources.AddRange(resources.ToArray) ElseIf (Not codeProvider.Supports(GeneratorSupport.Resources)) AndAlso (resources IsNot Nothing) Then Throw New Exception(message:="The current CodeDomProvider does not support resource embedding.") End If ' Specify the class that contains the main method of the executable. If codeProvider.Supports(GeneratorSupport.EntryPointMethod) Then .MainClass = mainClassName If (TypeOf codeProvider Is Microsoft.VisualBasic.VBCodeProvider) AndAlso (String.IsNullOrEmpty(sourceCode)) AndAlso .GenerateExecutable Then sourceCode = <a> Imports System Namespace MainNamespace Module MainClass Sub Main() End Sub End Module End Namespace </a>.Value ElseIf (TypeOf codeProvider Is Microsoft.VisualBasic.VBCodeProvider) AndAlso (String.IsNullOrEmpty(sourceCode)) AndAlso Not .GenerateExecutable Then sourceCode = <a> Imports System Namespace MainNamespace Public NotInheritable MainClass End Class End Namespace </a>.Value ElseIf (TypeOf codeProvider Is Microsoft.CSharp.CSharpCodeProvider) AndAlso (String.IsNullOrEmpty(sourceCode)) AndAlso .GenerateExecutable Then sourceCode = <a> using System; namespace MainNamespace { class MainClass { static void Main(string[] args) { } } } </a>.Value ElseIf (TypeOf codeProvider Is Microsoft.CSharp.CSharpCodeProvider) AndAlso (String.IsNullOrEmpty(sourceCode)) AndAlso Not .GenerateExecutable Then sourceCode = <a> using System; namespace MainNamespace { class MainClass { } } </a>.Value ElseIf String.IsNullOrEmpty(sourceCode) Then Throw New NotImplementedException(message:="Default sourcecode is not implemented for the specified CodeDomProvider. Please, specify a sourcecode.") End If End If End With Return codeProvider.CompileAssemblyFromSource(cp, sourceCode) End Function ''' <remarks> ''' ***************************************************************** ''' Title : Compile Assembly (from file). ''' Author: Elektro ''' Date : 14-June-2015 ''' Usage : ''' ''' Using vbCodeProvider As New Microsoft.VisualBasic.VBCodeProvider ''' ''' Dim resultVB As CompilerResults = ''' CodeDomUtil.CompileAssembly(codeProvider:=vbCodeProvider, ''' targetAssembly:=CodeDomUtil.TargetAssembly.Dll, ''' sourceFile:="C:\SourceCode.vb", ''' targetFile:="C:\VB Assembly.dll", ''' resources:={"C:\MyResources.resx"}, ''' referencedAssemblies:={"System.dll"}, ''' mainClassName:="MainNamespace.MainClass") ''' ''' Dim warnings As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)() ''' Where ce.IsWarning ''' ''' Dim errors As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultVB.Errors.Cast(Of CompilerError)() ''' Where Not ce.IsWarning ''' ''' For Each war As CompilerError In warnings ''' Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText)) ''' Next war ''' ''' For Each err As CompilerError In errors ''' Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText)) ''' Next err ''' ''' End Using ''' ----------------------------------------------------------------- ''' Using csCodeProvider As New Microsoft.CSharp.CSharpCodeProvider ''' ''' Dim resultCS As CompilerResults = ''' CodeDomUtil.CompileAssembly(codeProvider:=csCodeProvider, ''' targetAssembly:=CodeDomUtil.TargetAssembly.Dll, ''' sourceFile:="C:\SourceCode.cs", ''' targetFile:="C:\CS Assembly.dll", ''' resources:={"C:\MyResources.resx"}, ''' referencedAssemblies:={"System.dll"}, ''' mainClassName:="MainNamespace.MainClass") ''' ''' Dim warnings As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)() ''' Where ce.IsWarning ''' ''' Dim errors As IEnumerable(Of CompilerError) = ''' From ce As CompilerError In resultCS.Errors.Cast(Of CompilerError)() ''' Where Not ce.IsWarning ''' ''' For Each war As CompilerError In warnings ''' Debug.WriteLine(String.Format("{0}| Warning: {1}", war.ErrorNumber, war.ErrorText)) ''' Next war ''' ''' For Each err As CompilerError In errors ''' Debug.WriteLine(String.Format("{0}| Error: {1}", err.ErrorNumber, err.ErrorText)) ''' Next err ''' ''' End Using ''' ***************************************************************** ''' </remarks> ''' <summary> ''' Compiles a .Net assembly as executable or link library. ''' </summary> ''' <param name="codeProvider">The code provider.</param> ''' <param name="targetAssembly">The kind of assembly to generate.</param> ''' <param name="sourceFile">The source file to compile.</param> ''' <param name="targetFile">The target file to create.</param> ''' <param name="resources">The embedded resources (if any).</param> ''' <param name="referencedAssemblies">The referenced assemblies (if any).</param> ''' <param name="mainClassName">The code to compile (if any).</param> ''' <exception cref="Exception">The current CodeDomProvider does not support resource embedding.</exception> ''' <returns>The results of the compiler operation.</returns> Public Shared Function CompileAssembly(ByVal codeProvider As CodeDomProvider, ByVal targetAssembly As TargetAssembly, ByVal sourceFile As String, ByVal targetFile As String, Optional ByVal resources As IEnumerable(Of String) = Nothing, Optional ByVal referencedAssemblies As IEnumerable(Of String) = Nothing, Optional ByVal mainClassName As String = "MainNamespace.MainClass") As CompilerResults ' Set a default assembly reference. If referencedAssemblies Is Nothing Then referencedAssemblies = {"System.dll"} End If Dim cp As New CompilerParameters With cp ' Set compiler arguments. Select Case targetAssembly Case CodeDomUtil.TargetAssembly.Gui .CompilerOptions = "/optimize /target:winexe" Case Else .CompilerOptions = "/optimize" End Select ' Generate an exe or a dll. .GenerateExecutable = (targetAssembly <> CodeDomUtil.TargetAssembly.Dll) ' Save the assembly as a physical file. .GenerateInMemory = False ' Generate debug information (pdb). .IncludeDebugInformation = False ' Set the assembly file name to generate. .OutputAssembly = targetFile ' Add an assembly reference. .ReferencedAssemblies.AddRange(referencedAssemblies.ToArray) ' Set a temporary files collection. ' The TempFileCollection stores the temporary files generated during a build in the current directory. .TempFiles = New TempFileCollection(tempdir:=IO.Path.GetTempPath(), keepFiles:=True) ' Set whether to treat all warnings as errors. .TreatWarningsAsErrors = False ' Set the level at which the compiler should start displaying warnings. ' 0 - Turns off emission of all warning messages. ' 1 - Displays severe warning messages. ' 2 - Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members. ' 3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false. ' 4 - Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line. .WarningLevel = 3 ' Set the embedded resource file of the assembly. If codeProvider.Supports(GeneratorSupport.Resources) AndAlso (resources IsNot Nothing) Then .EmbeddedResources.AddRange(resources.ToArray) ElseIf (Not codeProvider.Supports(GeneratorSupport.Resources)) AndAlso (resources IsNot Nothing) Then Throw New Exception(message:="The current CodeDomProvider does not support resource embedding.") End If ' Specify the class that contains the main method of the executable. If codeProvider.Supports(GeneratorSupport.EntryPointMethod) Then .MainClass = mainClassName End If End With Return codeProvider.CompileAssemblyFromFile(cp, {sourceFile}) End Function End Class
|
|
« Última modificación: 15 Junio 2015, 20:04 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
¿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: Me.DataGridView1.MoveSelectedRows(DataGridViewMoveRowDirection.Up)
Me.DataGridView1.MoveSelectedRows(DataGridViewMoveRowDirection.Up, {0, 2})
Código fuente: ' *********************************************************************** ' Author : Elektro ' Modified : 16-June-2015 ' *********************************************************************** ' <copyright file="DataGridViewExtensions.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Runtime.CompilerServices Imports System.Windows.Forms #End Region ''' <summary> ''' Contains two methods for moving DataRows up/down. ''' You could easily tweak the code to work for say a ListBox. ''' </summary> ''' <remarks></remarks> Public Module DataGridViewExtensions #Region " Enumerations " ''' <summary> ''' Specifies a direction to move the rows. ''' </summary> Public Enum DataGridViewMoveRowDirection As Integer ''' <summary> ''' Move row up. ''' </summary> Up = 0 ''' <summary> ''' Move row down. ''' </summary> Down = 1 End Enum #End Region #Region " Public Methods " ''' <summary> ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>. ''' </summary> ''' <param name="sender">The <see cref="DataGridView"/>.</param> ''' <param name="direction">The row-move direction.</param> <DebuggerStepThrough()> <Extension()> Public Sub MoveSelectedRows(ByVal sender As DataGridView, ByVal direction As DataGridViewMoveRowDirection) DoRowsMove(sender, direction) End Sub ''' <summary> ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>. ''' </summary> ''' <param name="sender">The <see cref="DataGridView"/>.</param> ''' <param name="direction">The row-move direction.</param> ''' <param name="preserveCellsIndex">A sequence of cell indexes to preserve its cell values when moving the row(s).</param> <DebuggerStepThrough()> <Extension()> Public Sub MoveSelectedRows(ByVal sender As DataGridView, ByVal direction As DataGridViewMoveRowDirection, ByVal preserveCellsIndex As IEnumerable(Of Integer)) DoRowsMove(sender, direction, preserveCellsIndex) End Sub #End Region #Region " Private Methods " ''' <summary> ''' Moves up or down the selected row(s) of the specified <see cref="DataGridView"/>. ''' </summary> ''' <param name="dgv">The <see cref="DataGridView"/>.</param> ''' <param name="direction">The row-move direction.</param> ''' <param name="preserveCellsIndex">Optionally, a sequence of cell indexes to preserve its cell values when moving the row(s).</param> <DebuggerStepThrough()> Private Sub DoRowsMove(ByVal dgv As DataGridView, ByVal direction As DataGridViewMoveRowDirection, Optional ByVal preserveCellsIndex As IEnumerable(Of Integer) = Nothing) ' Keeps tracks of a cell value to preserve, to swap them when moving rows. Dim oldCellValue As Object Dim newCellValue As Object ' Short row collection reference. Dim rows As DataGridViewRowCollection = dgv.Rows ' Keeps track of the current row. Dim curRow As DataGridViewRow ' The maximum row index. Dim lastRowIndex As Integer = If(dgv.AllowUserToAddRows, rows.Count - 2, rows.Count - 1) ' List of hash codes of the selected rows. Dim selectedRows As New List(Of Integer) ' Get the hash codes of the selected rows For i As Integer = 0 To (rows.Count - 1) If (rows(i).IsNewRow = False) AndAlso (rows(i).Selected) Then selectedRows.Add(rows(i).GetHashCode) rows(i).Selected = False End If Next i ' Move the selected rows up or down. Select Case direction Case DataGridViewMoveRowDirection.Up For i As Integer = 0 To lastRowIndex If Not rows(i).IsNewRow Then If (selectedRows.Contains(rows(i).GetHashCode)) AndAlso (i - 1 >= 0) AndAlso (Not selectedRows.Contains(rows(i - 1).GetHashCode)) Then curRow = rows(i) rows.Remove(curRow) rows.Insert(i - 1, curRow) If preserveCellsIndex IsNot Nothing Then For Each cellIndex As Integer In preserveCellsIndex oldCellValue = curRow.Cells(cellIndex).Value newCellValue = rows(i).Cells(cellIndex).Value rows(i).Cells(cellIndex).Value = oldCellValue curRow.Cells(cellIndex).Value = newCellValue Next cellIndex End If End If End If Next i Case DataGridViewMoveRowDirection.Down For i As Integer = lastRowIndex To 0 Step -1 If Not rows(i).IsNewRow Then If (selectedRows.Contains(rows(i).GetHashCode)) AndAlso (i + 1 <= lastRowIndex) AndAlso (Not selectedRows.Contains(rows(i + 1).GetHashCode)) Then curRow = rows(i) rows.Remove(curRow) rows.Insert(i + 1, curRow) If preserveCellsIndex IsNot Nothing Then For Each cellIndex As Integer In preserveCellsIndex oldCellValue = curRow.Cells(cellIndex).Value newCellValue = rows(i).Cells(cellIndex).Value rows(i).Cells(cellIndex).Value = oldCellValue curRow.Cells(cellIndex).Value = newCellValue Next cellIndex End If End If End If Next i End Select ' Restore selected rows. For i As Integer = 0 To (rows.Count - 1) If Not rows(i).IsNewRow Then rows(i).Selected = selectedRows.Contains(rows(i).GetHashCode) End If Next i End Sub #End Region End Module
Saludos!
|
|
« Última modificación: 16 Junio 2015, 14:07 pm por Eleкtro »
|
En línea
|
|
|
|
nolasco281
Desconectado
Mensajes: 319
|
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
Mensajes: 9.885
|
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
Mensajes: 9.885
|
Una Class para manipular archivos de texto. Diagrama de clase: Ejemplo de uso: Using txtFile As New TextfileStream("C:\File.txt", Encoding.Default) txtFile.Lock() txtFile.Lines.Add("Test") txtFile.Lines(0) = "Hello World!" txtFile.Save() Dim lineIndex As Integer Dim lineCount As Integer = txtFile.Lines.Count Dim textFormat As String = Environment.NewLine & String.Join(ControlChars.NewLine, From line As String In txtFile.Lines Select String.Format("{0}: {1}", Interlocked.Increment(lineIndex).ToString(New String("0"c, lineCount.ToString.Length)), line)) Console.WriteLine(String.Format("FilePath: {0}", txtFile.Filepath)) Console.WriteLine(String.Format("Encoding: {0}", txtFile.Encoding.WebName)) Console.WriteLine(String.Format("Lines : {0}", textFormat)) End Using
Código fuente: ' *********************************************************************** ' Author : Elektro ' Modified : 18-June-2015 ' *********************************************************************** ' <copyright file="TextfileStream.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " 'Using txtFile As New TextfileStream("C:\File.txt") ' ' txtFile.Lock() ' ' txtFile.Lines.Add("Test") ' txtFile.Lines(0) = "Hello World!" ' txtFile.Save() ' ' Dim lineIndex As Integer ' Dim lineCount As Integer = txtFile.Lines.Count ' Dim textFormat As String = ' Environment.NewLine & ' String.Join(ControlChars.NewLine, ' From line As String In txtFile.Lines ' Select String.Format("{0}: {1}", ' Interlocked.Increment(lineIndex).ToString(New String("0"c, lineCount.ToString.Length)), line)) ' ' Console.WriteLine(String.Format("FilePath: {0}", txtFile.Filepath)) ' Console.WriteLine(String.Format("Encoding: {0}", txtFile.Encoding.WebName)) ' Console.WriteLine(String.Format("Lines : {0}", textFormat)) ' 'End Using #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports Microsoft.Win32.SafeHandles Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.IO Imports System.Linq Imports System.Text #End Region #Region " Textfile " ''' <summary> ''' Reads and manages the contents of a textfile. ''' It encapsulates a <see cref="System.IO.FileStream"/> to access the textfile. ''' </summary> Public NotInheritable Class TextfileStream : Implements IDisposable #Region " Properties " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the textfile path. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The textfile path. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public ReadOnly Property Filepath As String Get Return Me.filepathB End Get End Property ''' <summary> ''' (Backing field) ''' The textfile path. ''' </summary> Private ReadOnly filepathB As String ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the textfile <see cref="Encoding"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The textfile <see cref="Encoding"/>. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public ReadOnly Property Encoding As Encoding Get Return Me.encodingB End Get End Property ''' <summary> ''' (Backing field) ''' The textfile <see cref="Encoding"/>. ''' </summary> Private ReadOnly encodingB As Encoding = Encoding.Default ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets or sets the textfile lines. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The textfile lines. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public Property Lines As TexfileLines Get Return Me.linesB End Get Set(ByVal value As TexfileLines) Me.linesB = value End Set End Property ''' <summary> ''' (Backing field) ''' The textfile lines. ''' </summary> Private linesB As TexfileLines ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the <see cref="System.IO.FileStream"/> instance that exposes a <see cref="System.IO.Stream"/> around the textfile. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The <see cref="System.IO.FileStream"/> instance. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Private ReadOnly Property fs As FileStream Get Return Me.fsB End Get End Property ''' <summary> ''' (Backing Field) ''' The <see cref="System.IO.FileStream"/> instance that exposes a <see cref="System.IO.Stream"/> around the textfile. ''' </summary> Private ReadOnly fsB As FileStream ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a <see cref="Microsoft.Win32.SafeHandles.SafeFileHandle"/> object that represents the operating system file handle of the textfile. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' A <see cref="Microsoft.Win32.SafeHandles.SafeFileHandle"/> object that represents the operating system file handle of the textfile. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public ReadOnly Property FileHandle As SafeFileHandle Get Return Me.fs.SafeFileHandle End Get End Property ''' <summary> ''' (Backing Field) ''' A <see cref="Microsoft.Win32.SafeHandles.SafeFileHandle"/> object that represents the operating system file handle of the textfile. ''' </summary> Private ReadOnly fileHandleB As SafeFileHandle #End Region #Region " Sub-Classes " ''' <summary> ''' Defines a <see cref="System.Collections.Generic.List(Of String)"/> that contains the text-lines of a textfile. ''' </summary> Partial Public NotInheritable Class TexfileLines : Inherits List(Of String) #Region " Properties " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the number of blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The number of blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public ReadOnly Property CountBlank As Integer Get Return (From line As String In Me Where String.IsNullOrEmpty(line) OrElse String.IsNullOrWhiteSpace(line)).Count End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets the number of non-blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <value> ''' The number of non-blank elements actually contained in the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </value> ''' ---------------------------------------------------------------------------------------------------- Public ReadOnly Property CountNonBlank As Integer Get Return (From line As String In Me Where Not String.IsNullOrEmpty(line) AndAlso Not String.IsNullOrWhiteSpace(line)).Count End Get End Property #End Region #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Initializes a new instance of the <see cref="TexfileLines"/> class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Sub New() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Initializes a new instance of the <see cref="TexfileLines"/> class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="lines"> ''' The text-lines. ''' </param> ''' ---------------------------------------------------------------------------------------------------- Public Sub New(ByVal lines As IEnumerable(Of String)) Me.AddRange(lines) End Sub #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Randomizes the elements of the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' An <see cref="IEnumerable(Of String)"/> that contains the randomized elements. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Function Randomize() As IEnumerable(Of String) Dim rand As New Random Return From line As String In Me Order By rand.Next End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes the elements at the specified indexes of the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="indexes"> ''' The zero-based indexes of the elements to remove. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="IndexOutOfRangeException"> ''' </exception> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Overloads Sub RemoveAt(ByVal indexes As IEnumerable(Of Integer)) Dim lineCount As Integer = Me.Count Select Case indexes.Max Case Is < 0, Is > lineCount Throw New IndexOutOfRangeException() Case Else Dim tmpRef As IEnumerable(Of String) = Me.Select(Function(line As String, index As Integer) Return New With { Key .line = line, Key .index = index + 1 } End Function). Where(Function(con) Not indexes.Contains(con.index)). Select(Function(con) con.line) Me.Clear() Me.AddRange(tmpRef) tmpRef = Nothing End Select End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' 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)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="trimChars"> ''' An array of Unicode characters to remove. ''' If <paramref name="trimChars"></paramref> is <c>Nothing</c> or an empty array, Unicode white-space characters are removed instead. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' 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. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Function Trim(Optional ByVal trimChars As Char() = Nothing) As IEnumerable(Of String) Return From line As String In Me Select line.Trim(trimChars) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes all leading occurrences of a set of characters from all the elements of the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="trimChars"> ''' An array of Unicode characters to remove. ''' If <paramref name="trimChars"></paramref> is <c>Nothing</c> or an empty array, Unicode white-space characters are removed instead. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The <see cref="IEnumerable(Of String)"/> that remains after all occurrences of the specified characters are removed from the start of the elements. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Function TrimStart(Optional ByVal trimChars As Char() = Nothing) As IEnumerable(Of String) Return From line As String In Me Select line.TrimStart(trimChars) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Removes all trailing occurrences of a set of characters from all the elements of the <see cref="System.Collections.Generic.List(Of T)"/>. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="trimChars"> ''' An array of Unicode characters to remove. ''' If <paramref name="trimChars"></paramref> is <c>Nothing</c> or an empty array, Unicode white-space characters are removed instead. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The <see cref="IEnumerable(Of String)"/> that remains after all occurrences of the specified characters are removed from the end of the elements. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Function TrimEnd(Optional ByVal trimChars As Char() = Nothing) As IEnumerable(Of String) Return From line As String In Me Select line.TrimEnd(trimChars) End Function #End Region End Class #End Region #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="TextfileStream"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Sub New() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Initializes a new instance of the <see cref="TextfileStream"/> class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="filepath"> ''' The textfile path. ''' If the path doesn't exists, the file will be created. ''' </param> ''' ''' <param name="encoding"> ''' The file encoding used to read the textfile. ''' If <paramref name="encoding"></paramref> value is <c>Nothing</c>, an attempt to detect the encoding will be realized, ''' if the attempt to detect the file encoding fails, <see cref="Encoding.Default"/> will be used. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="FileNotFoundException"> ''' File not found. ''' </exception> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Sub New(ByVal filepath As String, Optional ByVal encoding As Encoding = Nothing) If Not File. Exists(filepath ) Then Throw New FileNotFoundException(message:="File not found.", fileName:=filepath) Else Me.filepathB = filepath Me.encodingB = encoding If Me.encodingB Is Nothing Then Me.encodingB = Me.GetEncoding End If Me. linesB = New TexfileLines (File. ReadAllLines(Me. filepathB, Me. encodingB)) Me.fsB = New FileStream(filepath, FileMode.OpenOrCreate) End If End Sub #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents other processes from reading or writing to the textfile. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Sub Lock() Me.fsB.Lock(0, Me.fsB.Length) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Allows access by other processes to read or write to a textfile that was previously locked. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Sub Unlock() Me.fsB.Unlock(0, Me.fsB.Length) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Sub Close() Me.fsB.Close() End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Save the lines of the current textfile, in the current textfile. ''' Note that the <see cref="Save"></see> method should be called to apply any realized changes in the lines of the textfile ''' before disposing this <see cref="TextfileStream"></see> instance. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="encoding"> ''' The file encoding used to write the textfile. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Sub Save(Optional ByVal encoding As Encoding = Nothing) If encoding Is Nothing Then encoding = Me.encodingB End If Dim bytes As Byte() = encoding.GetBytes(Me.ToString) Me.fs.SetLength(bytes.Length) Me.fs.Write(bytes, 0, bytes.Length) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Save the lines of the current textfile, in the target textfile. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="filepath"> ''' The target filepath where to save the text. ''' </param> ''' ''' <param name="encoding"> ''' The file encoding used to write the textfile. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Sub Save(ByVal filepath As String, Optional ByVal encoding As Encoding = Nothing) If encoding Is Nothing Then encoding = Me.encodingB End If Using fs As New FileStream(filepath, FileMode.OpenOrCreate) Dim bytes As Byte() = encoding.GetBytes(Me.ToString) fs.SetLength(bytes.Length) fs.Write(bytes, 0, bytes.Length) End Using End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Returns a <see cref="String"/> that represents this instance. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' A <see cref="String"/> that represents this instance. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Overrides Function ToString() As String Return String.Join(ControlChars.NewLine, Me.linesB) End Function #End Region #Region " Private Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines the <see cref="Encoding"/> of the current textfile. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' If the encoding can be detected, the return value is the detected <see cref="Encoding"/>, ''' if the encoding can't be detected, the return value is <see cref="Encoding.Default"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Private Function GetEncoding() As Encoding Dim encoding As Encoding = Nothing Dim bytes As Byte() = File. ReadAllBytes(Me. filepathB) For Each encodingInfo As EncodingInfo In encoding.GetEncodings() Dim currentEncoding As Encoding = encodingInfo.GetEncoding() Dim preamble As Byte() = currentEncoding.GetPreamble() Dim match As Boolean = True If (preamble.Length > 0) AndAlso (preamble.Length <= bytes.Length) Then For i As Integer = 0 To (preamble.Length - 1) If preamble(i) <> bytes(i) Then match = False Exit For End If Next i Else match = False End If If match Then encoding = currentEncoding Exit For End If Next encodingInfo If encoding Is Nothing Then Return encoding.Default Else Return encoding End If End Function #End Region #Region " IDisposable " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' To detect redundant calls when disposing. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private isDisposed As Boolean = False ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevent calls to methods after disposing. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="System.ObjectDisposedException"></exception> ''' ---------------------------------------------------------------------------------------------------- Private Sub DisposedCheck() If Me.isDisposed Then Throw New ObjectDisposedException(Me.GetType.FullName) End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Releases all the resources used by this <see cref="TextfileStream"></see> instance. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Sub Dispose() Implements IDisposable.Dispose Me.Dispose(isDisposing:=True) GC.SuppressFinalize(obj:=Me) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Releases unmanaged and - optionally - managed resources. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="isDisposing"> ''' <c>True</c> to release both managed and unmanaged resources; ''' <c>False</c> to release only unmanaged resources. ''' </param> ''' ---------------------------------------------------------------------------------------------------- Protected Sub Dispose(ByVal isDisposing As Boolean) If Not Me.isDisposed Then If isDisposing Then If Me.fsB IsNot Nothing Then Me.fsB.Close() Me.linesB.Clear() End If End If End If Me.isDisposed = True End Sub #End Region End Class #End Region
|
|
« Última modificación: 19 Junio 2015, 10:40 am por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.885
|
Un pequeño código para crear nuevas cuentas de usuario en el equipo. Ejemplo de uso: CreateUserAccount(username:="Elektro", password:="", displayName:="Elektro account.", description:="This is a test user-account.", canChangePwd:=True, pwdExpires:=False, groupSid:=WellKnownSidType.BuiltinAdministratorsSid)
Código fuente: ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Create user-account. ''' Author: Elektro ''' Date : 19-June-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> ''' CreateUserAccount(username:="Elektro", ''' password:="", ''' displayName:="Elektro Account.", ''' description:="This is a test user-account.", ''' canChangePwd:=True, ''' pwdExpires:=False, ''' groupSid:=WellKnownSidType.BuiltinAdministratorsSid) ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Creates a new user account in the current machine. ''' This function does not adds the user to the machine. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="username"> ''' The user name. ''' </param> ''' ''' <param name="password"> ''' The user password. ''' If this value is empty, account is set to don't require a password. ''' </param> ''' ''' <param name="displayName"> ''' The display name of the user account. ''' </param> ''' ''' <param name="description"> ''' The description of the user account. ''' </param> ''' ''' <param name="canChangePwd"> ''' A value that indicates whether the user can change its password. ''' </param> ''' ''' <param name="pwdExpires"> ''' A value that indicates whether the password should expire. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' An <see cref="UserPrincipal"/> object that contains the user data. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function CreateUserAccount(ByVal username As String, ByVal password As String, ByVal displayName As String, ByVal description As String, ByVal canChangePwd As Boolean, ByVal pwdExpires As Boolean) As UserPrincipal Using context As New PrincipalContext(ContextType.Machine) Dim user As New UserPrincipal(context) With user .Name = username .SetPassword(password) .PasswordNotRequired = String.IsNullOrEmpty(password) .DisplayName = displayName .Description = description .UserCannotChangePassword = canChangePwd .PasswordNeverExpires = pwdExpires .Enabled = True .Save() End With Return user End Using End Function ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Add user-account. ''' Author: Elektro ''' Date : 19-June-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> ''' AddUserAccount(username:="Elektro", ''' password:="", ''' displayName:="Elektro Account.", ''' description:="This is a test user-account.", ''' canChangePwd:=True, ''' pwdExpires:=False, ''' groupSid:=WellKnownSidType.BuiltinAdministratorsSid) ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Adds a new user account in the current machine. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="username"> ''' The user name. ''' </param> ''' ''' <param name="password"> ''' The user password. ''' If this value is empty, account is set to don't require a password. ''' </param> ''' ''' <param name="displayName"> ''' The display name of the user account. ''' </param> ''' ''' <param name="description"> ''' The description of the user account. ''' </param> ''' ''' <param name="canChangePwd"> ''' A value that indicates whether the user can change its password. ''' </param> ''' ''' <param name="pwdExpires"> ''' A value that indicates whether the password should expire. ''' </param> ''' ''' <param name="groupSid"> ''' A <see cref="WellKnownSidType"/> security identifier (SID) that determines the account group where to add the user. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub AddUserAccount(ByVal username As String, ByVal password As String, ByVal displayName As String, ByVal description As String, ByVal canChangePwd As Boolean, ByVal pwdExpires As Boolean, Optional ByVal groupSid As WellKnownSidType = WellKnownSidType.BuiltinUsersSid) Using context As New PrincipalContext(ContextType.Machine) Using user As UserPrincipal = CreateUserAccount(username, password, displayName, description, canChangePwd, pwdExpires) Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.Sid, New SecurityIdentifier(groupSid, Nothing).Value) group.Members.Add(user) group.Save() End Using ' group End Using ' user End Using ' context End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Title : Add user-account. ''' Author: Elektro ''' Date : 19-June-2015 ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> ''' AddUserAccount(user:=myUserPrincipal, groupSid:=WellKnownSidType.BuiltinAdministratorsSid) ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Adds a new user account in the current machine. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="user"> ''' An <see cref="UserPrincipal"/> object that contains the user data. ''' </param> ''' ''' <param name="groupSid"> ''' A <see cref="WellKnownSidType"/> security identifier (SID) that determines the account group where to add the user. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub AddUserAccount(ByVal user As UserPrincipal, Optional ByVal groupSid As WellKnownSidType = WellKnownSidType.BuiltinUsersSid) Using context As New PrincipalContext(ContextType.Machine) Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.Sid, New SecurityIdentifier(groupSid, Nothing).Value) group.Members.Add(user) group.Save() End Using ' group End Using ' context End Sub
|
|
« Última modificación: 19 Junio 2015, 12:52 pm por Eleкtro »
|
En línea
|
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Librería de Snippets en C/C++
« 1 2 3 4 »
Programación C/C++
|
z3nth10n
|
31
|
26,118
|
2 Agosto 2013, 17:13 pm
por 0xDani
|
|
|
[APORTE] [VBS] Snippets para manipular reglas de bloqueo del firewall de Windows
Scripting
|
Eleкtro
|
1
|
4,122
|
3 Febrero 2014, 20:19 pm
por Eleкtro
|
|
|
Librería de Snippets para Delphi
« 1 2 »
Programación General
|
crack81
|
15
|
21,370
|
25 Marzo 2016, 18:39 pm
por crack81
|
|
|
Una organización en Github para subir, proyectos, snippets y otros?
Sugerencias y dudas sobre el Foro
|
z3nth10n
|
0
|
3,114
|
21 Febrero 2017, 10:47 am
por z3nth10n
|
|
|
índice de la Librería de Snippets para VB.NET !!
.NET (C#, VB.NET, ASP)
|
Eleкtro
|
7
|
6,598
|
4 Julio 2018, 21:35 pm
por Eleкtro
|
|