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

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

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

UserAccountUtil.vb, una class para realizar tareas comunes relacioandas con las cuentas de usuario (LOCALES) de Windows.

Diagrama de Class:


Código fuente:
Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 20-June-2015
' ***********************************************************************
' <copyright file="UserAccountUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Public Members Summary "

#Region " Properties "

' UserAccountUtil.CurrentUser As UserPrincipal
' UserAccountUtil.CurrentUserIsAdmin As Boolean

#End Region

#Region " Functions "

' UserAccountUtil.Create(String, String, String, String, Boolean, Boolean) As UserPrincipal
' UserAccountUtil.FindProfilePath(SecurityIdentifier) As String
' UserAccountUtil.FindProfilePath(String) As String
' UserAccountUtil.FindSid(String) As SecurityIdentifier
' UserAccountUtil.FindUser(SecurityIdentifier) As UserPrincipal
' UserAccountUtil.FindUser(String) As UserPrincipal
' UserAccountUtil.FindUsername(SecurityIdentifier) As String
' UserAccountUtil.GetAllUsers() As List(Of UserPrincipal)
' UserAccountUtil.IsAdmin(String) As Boolean
' UserAccountUtil.IsMemberOfGroup(String, String) As Boolean
' UserAccountUtil.IsMemberOfGroup(String, WellKnownSidType) As Boolean

#End Region

#Region " Methods "

' UserAccountUtil.Add(String, String, String, String, Boolean, Boolean, WellKnownSidType)
' UserAccountUtil.Add(UserPrincipal, WellKnownSidType)
' UserAccountUtil.Delete(String)

#End Region

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports System.Collections.Generic
Imports System.DirectoryServices.AccountManagement
Imports System.Linq
Imports System.Security.Principal

#End Region

''' <summary>
''' Contains related Windows user-account utilities.
''' </summary>
Public NotInheritable Class UserAccountUtil

#Region " Properties "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets an <see cref="UserPrincipal"/> object that represents the current user.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <value>
   ''' An <see cref="UserPrincipal"/> object that represents the current user.
   ''' </value>
   ''' ----------------------------------------------------------------------------------------------------
   Public Shared ReadOnly Property CurrentUser As UserPrincipal
       Get
           If UserAccountUtil.currentUserB Is Nothing Then
               UserAccountUtil.currentUserB = UserAccountUtil.FindUser(Environment.UserName)
           End If
           Return UserAccountUtil.currentUserB
       End Get
   End Property
   ''' <summary>
   ''' (Backing Field)
   ''' Gets an <see cref="UserPrincipal"/> object that represents the current user.
   ''' </summary>
   Private Shared currentUserB As UserPrincipal

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Gets a value that indicates whether the current user has Administrator privileges.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <value>
   ''' A value that indicates whether the current user has Administrator privileges.
   ''' </value>
   ''' ----------------------------------------------------------------------------------------------------
   Public Shared ReadOnly Property CurrentUserIsAdmin As Boolean
       Get
           Using group As GroupPrincipal =
               GroupPrincipal.FindByIdentity(CurrentUser.Context,
                                             IdentityType.Sid,
                                             New SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, Nothing).Value)

               Return UserAccountUtil.CurrentUser.IsMemberOf(group)
           End Using
       End Get
   End Property

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Prevents a default instance of the <see cref="UserAccountUtil"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

#End Region

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Get all user-accounts.
   ''' Author: Elektro
   ''' Date  : 20-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim users As List(Of UserPrincipal) = UserAccountUtil.GetAllUsers()
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Find and returns all the user accounts of the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' A <see cref="List(Of UserPrincipal)"/> collection that contains the users.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function GetAllUsers() As List(Of UserPrincipal)

       Dim context As New PrincipalContext(ContextType.Machine)

       Using user As New UserPrincipal(context)

           Using searcher As New PrincipalSearcher(user)

               Return searcher.FindAll.Cast(Of UserPrincipal).ToList

           End Using ' searcher

       End Using ' user

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Find user-account by name.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim user As UserPrincipal = UserAccountUtil.FindUser(username:="Administrator")
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Finds an user account that matches the specified name in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name to find.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' An <see cref="UserPrincipal"/> object that contains the user data.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <exception cref="ArgumentException">
   ''' User not found.;username
   ''' </exception>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function FindUser(ByVal username As String) As UserPrincipal

       Dim context As New PrincipalContext(ContextType.Machine)

       Using user As New UserPrincipal(context)

           Using searcher As New PrincipalSearcher(user)

               Try
                   Return (From p As Principal In searcher.FindAll
                           Where p.Name.Equals(username, StringComparison.OrdinalIgnoreCase)).
                           Cast(Of UserPrincipal).
                           First

               Catch ex As InvalidOperationException
                   Throw New ArgumentException(message:="User not found.", paramName:="username", innerException:=ex)

               End Try

           End Using ' searcher

       End Using ' user

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Find user-account by SID.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim user As UserPrincipal = UserAccountUtil.FindUser(sid:=New SecurityIdentifier("S-1-5-21-1780771175-1208154119-2269826705-500"))
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Finds an user account that matches the specified security identifier (SID) in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="sid">
   ''' A <see cref="SecurityIdentifier"/> (SID) object.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' An <see cref="UserPrincipal"/> object that contains the user data.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function FindUser(ByVal sid As SecurityIdentifier) As UserPrincipal

       Dim context As New PrincipalContext(ContextType.Machine)

       Using user As New UserPrincipal(context)

           Using searcher As New PrincipalSearcher(user)

               Try
                   Return (From p As Principal In searcher.FindAll
                           Where p.Sid.Value.Equals(sid.Value, StringComparison.OrdinalIgnoreCase)).
                           Cast(Of UserPrincipal).
                           First

               Catch ex As InvalidOperationException
                   Throw New ArgumentException(message:="User not found.", paramName:="username", innerException:=ex)

               End Try

           End Using ' searcher

       End Using ' user

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Find user-account name by SID.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim username As String = UserAccountUtil.FindUsername(sid:=New SecurityIdentifier("S-1-5-21-1780771175-1208154119-2269826705-500"))
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Finds the username of the specified security identifier (SID) in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="sid">
   ''' A <see cref="SecurityIdentifier"/> (SID) object.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The username.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function FindUsername(ByVal sid As SecurityIdentifier) As String

       Using user As UserPrincipal = UserAccountUtil.FindUser(sid)

           Return user.Name

       End Using

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Find user-account SID by username.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim sid As SecurityIdentifier = UserAccountUtil.FindSid(username:="Administrator"))
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Finds the security identifier (SID) of the specified username account in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' A <see cref="SecurityIdentifier"/> (SID) object.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function FindSid(ByVal username As String) As SecurityIdentifier

       Return UserAccountUtil.FindUser(username).Sid

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Find user-account's profile path by username.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim profilePath As String = UserAccountUtil.FindProfilePath(username:="Administrator"))
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Finds the profile directory path of the specified username account in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name to find.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The profile directory path.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function FindProfilePath(ByVal userName As String) As String

       Using user As UserPrincipal = UserAccountUtil.FindUser(userName)

           Return CStr(My.Computer.Registry.GetValue(String.Format("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\{0}",
                                                                   user.Sid.Value),
                                                                   "ProfileImagePath", ""))

       End Using

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Find user-account's profile path by SID.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim profilePath As String = UserAccountUtil.FindProfilePath(sid:=New SecurityIdentifier("S-1-5-21-1780771175-1208154119-2269826705-500"))
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Finds the profile directory path of the specified username account in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="sid">
   ''' A <see cref="SecurityIdentifier"/> (SID) object.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' The profile directory path.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function FindProfilePath(ByVal sid As SecurityIdentifier) As String

       Using user As UserPrincipal = UserAccountUtil.FindUser(sid)

           Return CStr(My.Computer.Registry.GetValue(String.Format("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\{0}",
                                                                   user.Sid.Value),
                                                                   "ProfileImagePath", ""))

       End Using

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : User is Admin?.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim userIsAdmin As Boolean = UserAccountUtil.IsAdmin(username:="Administrator")
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Determines whether an user-account of the current machine context is an Administrator.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if the user is an Administrator, otherwise, <c>False</c>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function IsAdmin(ByVal username As String) As Boolean

       Using user As UserPrincipal = UserAccountUtil.FindUser(username)

           Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(user.Context, IdentityType.Sid, New SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, Nothing).Value)

               Return user.IsMemberOf(group)

           End Using ' group

       End Using ' user

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : User is member of group...?.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim userIsGuest As Boolean = UserAccountUtil.IsMemberOfGroup(username:="Administrator", groupSid:=WellKnownSidType.BuiltinGuestsSid)
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Determines whether an user-account of the current machine context is a member of the specified group.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name.
   ''' </param>
   '''
   ''' <param name="groupSid">
   ''' A <see cref="WellKnownSidType"/> security identifier (SID) that determines the account group.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if the user is a member of the specified group, otherwise, <c>False</c>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function IsMemberOfGroup(ByVal username As String,
                                          ByVal groupSid As WellKnownSidType) As Boolean

       Using user As UserPrincipal = UserAccountUtil.FindUser(username)

           Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(user.Context, IdentityType.Sid, New SecurityIdentifier(groupSid, Nothing).Value)

               Return user.IsMemberOf(group)

           End Using ' group

       End Using ' user

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : User is member of group...?.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim userIsGuest As Boolean = UserAccountUtil.IsMemberOfGroup(username:="Administrator", groupname:="Guests")
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Determines whether an user-account of the current machine context is a member of the specified group.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name.
   ''' </param>
   '''
   ''' <param name="groupname">
   ''' The name of thehe group.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <returns>
   ''' <c>True</c> if the user is a member of the specified group, otherwise, <c>False</c>.
   ''' </returns>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Function IsMemberOfGroup(ByVal username As String,
                                          ByVal groupname As String) As Boolean

       Using user As UserPrincipal = UserAccountUtil.FindUser(username)

           Using group As GroupPrincipal = GroupPrincipal.FindByIdentity(user.Context, IdentityType.Name, groupname)

               Return user.IsMemberOf(group)

           End Using ' group

       End Using ' user

   End Function

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Create user-account.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' Dim user as UserPrincipal = UserAccountUtil.Create(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 context.
   ''' This function does NOT adds a new user 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 any 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 Create(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>
   ''' UserAccountUtil.Add(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 context.
   ''' </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 any 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 Add(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 = UserAccountUtil.Create(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>
   ''' UserAccountUtil.Add(user:=myUserPrincipal, groupSid:=WellKnownSidType.BuiltinAdministratorsSid)
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Adds a new user account in the current machine context.
   ''' </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 Add(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

   ''' ----------------------------------------------------------------------------------------------------
   ''' <remarks>
   ''' Title : Delete user-account.
   ''' Author: Elektro
   ''' Date  : 19-June-2015
   ''' </remarks>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example>
   ''' UserAccountUtil.Delete(username:="User name")
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Deletes an user account in the current machine context.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="username">
   ''' The user name of the user-account to delete.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <exception cref="ArgumentException">
   ''' User not found.;username
   ''' </exception>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Sub Delete(ByVal username As String)

       Using curUser As UserPrincipal = UserAccountUtil.FindUser(username)

           curUser.Delete()

       End Using

   End Sub

#End Region

End Class








Eleкtro

#471
Comparto esta class que sirve para registrar una extensión de archivo, o para obtener información de una extensión ya registrada en el sistema.

Si encuentran cualquier bug, hagan el favor de comunicármelo para arreglarlo en futuras versiones.




Diagrama de Class:





Ejemplos de uso:
Código (vbnet) [Seleccionar]
FileAssocUtil.Register(regUser:=FileAssocUtil.RegistryUser.CurrentUser,
                      extensionName:=".elek",
                      keyReferenceName:="ElektroFile",
                      friendlyName:="Elektro File",
                      defaultIcon:="%WinDir%\System32\Shell32.ico",
                      iconIndex:=0,
                      executable:="%WinDir%\notepad.exe",
                      arguments:="""%1""")


Código (vbnet) [Seleccionar]
Dim isRegistered As Boolean = FileAssocUtil.IsRegistered(".elek")

Código (vbnet) [Seleccionar]
Dim feInfo As FileAssocUtil.FileExtensionInfo = FileAssocUtil.GetFileExtensionInfo(".wav")

Dim sb As New StringBuilder
With sb
   .AppendLine(String.Format("FriendlyDocName: {0}", feInfo.FriendlyDocName))
   .AppendLine(String.Format("ContentType: {0}", feInfo.ContentType))
   .AppendLine(String.Format("DefaultIcon: {0}", feInfo.DefaultIcon))
   .AppendLine("-----------------------------------------------------------")
   .AppendLine(String.Format("FriendlyAppName: {0}", feInfo.FriendlyAppName))
   .AppendLine(String.Format("Executable: {0}", feInfo.Executable))
   .AppendLine(String.Format("Command: {0}", feInfo.Command))
   .AppendLine("-----------------------------------------------------------")
   .AppendLine(String.Format("DropTarget: {0}", feInfo.DropTarget))
   .AppendLine(String.Format("InfoTip: {0}", feInfo.InfoTip))
   .AppendLine(String.Format("No Open: {0}", feInfo.NoOpen))
   .AppendLine(String.Format("Shell Extension: {0}", feInfo.ShellExtension))
   .AppendLine(String.Format("Shell New Value: {0}", feInfo.ShellNewValue))
   .AppendLine("-----------------------------------------------------------")
   .AppendLine(String.Format("Supported URI Protocols: {0}", feInfo.SupportedUriProtocols))
   .AppendLine(String.Format("DDE Application: {0}", feInfo.DdeApplication))
   .AppendLine(String.Format("DDE Command: {0}", feInfo.DdeCommand))
   .AppendLine(String.Format("DDE If Exec: {0}", feInfo.DdeIfExec))
   .AppendLine(String.Format("DDE Topic: {0}", feInfo.DdeTopic))
End With

MsgBox(sb.ToString)







Código fuente:
http://pastebin.com/gXbp78Pv
http://pastebin.com/aAscfAev








tincopasan

Elektro:
            no entro nunca a la sección net así que recién hoy veo el trabajo que llevas realizado(no todo porque es mucho para ver en una sola vez y no es que me encante la programación) así que FELICITACIONES!! y no lo tomes como un grito sino como lo que es, admiración. Vi un par de codes de decimales y hexadeciales pero no vi de binarios, claro que no tiene uso, salvo a quienes nos gusta la ingeniería inversa más que la programación en si, pero es un minúsculo granito de arena.
Para pasar enteros a binarios

Código (vbnet) [Seleccionar]
  Public Function DecaBin(numero As Integer) As String
        If numero <= 2 Then 'Caso Base
            DecaBin = (numero \ 2) & (numero Mod 2)
        Else 'Caso Recursivo
            DecaBin = DecaBin(numero \ 2) & numero Mod 2
        End If
    End Function


# ejemplo de uso
   
Textbox = DecaBin(numeromio)

Eleкtro

#473
@tincopasan

Antes de nada, Gracias por tu comentario ...ya hacia tiempo que nadie (más que yo) aportaba algo a este hilo, y que lo aporte alguien que no programa en .net (o eso me das a entender) tiene más mérito si cabe.

Pero debo hacer un pequeño apunte sobre el código (con la intención de que le sirva a alguien para aprender, o al menos eso deseo), mira, para convertir un entero a un string binario simplemente puedes recurrir a la utilización de la función Convert.ToString, a uno de sus overloads que toma cómo parametro la base.

Ejemplo:
Código (vbnet) [Seleccionar]
Clipboard.SetText(Convert.ToString(123456789I, toBase:=2)) ' Resultado: 111010110111100110100010101

Esta opción está muy bien para simplificar el código, pero lo cierto es que tu metodología también es buena en el sentido de que enseña "la base" de cómo hacerlo utilizando la aritmética, a la antigua usanza, sin aprovecharse de estas funciones built-in de .Net que tanto nos facilitan la vida en una linea de código. Así cómo tú has mostrado se aprende mejor a resolver problemas, pero bueno, quería dejar constancia de la alternativa, la Class Convert es muy útil.

Saludos!








tincopasan

Gracias por mostrar la forma simple de hacerlo, efectivamente no soy programador de ningún lenguaje en particular, pero usando la forma básica y conociendo las sentencias más comunes, if, then, for, while, etc. por ejemplo y de forma muy bruta resuelvo problemas en varios lenguajes, porque más allá de la riqueza de cada uno de ellos todos tienen la forma básica de empezar.

tincopasan

Sigo revisando, son muchos! en la parte de criptografía vi un code que hace el cifrado de Cesar, obviamente lo haría más a lo bruto:

Código (vb) [Seleccionar]
Dim Lista() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "ñ", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim Adelante As Integer = 3    ' modificando este valor es cuantos lugares adelantamos para reemplazar
Dim Letra As Char
Dim x As Integer
Dim cifrada As String = ""

Private Sub Cesar(palabra As String)
    For i = 1 To Len(palabra)
        Letra = GetChar(palabra, i)
        For x = 0 To 26
            If Letra = Lista(x) Then
                x = (x + Adelante) Mod 27
                Letra = CChar(Lista(x))
                cifrada = cifrada + Letra
                Exit For
            End If
        Next
    Next
MsgBox(cifrada)
End Sub
'forma de uso
Cesar("elhacker")

Eleкtro

#476
Una refactorización de una Class que ya compartí para apagar, reiniciar, o desloguear un equipo local o en red.

Diagrama de Class:


Ejemplo de uso:
Código (vbnet) [Seleccionar]
   Sub Test()

       ' Restart the current computer in 30 seconds and wait for applications to close.
       ' Specify that the restart operation is planned because a consecuence of an installation.
       Dim success As Boolean =
           SystemRestarter.Restart("127.0.0.1", 30, "System is gonna be restarted quickly, go save all your data now...!",
                                   SystemRestarter.ShutdownMode.Wait,
                                   SystemRestarter.ShutdownReason.MajorOperatingSystem Or
                                   SystemRestarter.ShutdownReason.MinorInstallation,
                                   SystemRestarter.ShutdownPlanning.Planned)

       Console.WriteLine(String.Format("Restart operation initiated successfully?: {0}", CStr(success)))

       ' Abort the current operation.
       If success Then
           Dim isAborted As Boolean = SystemRestarter.Abort()
           Console.WriteLine(String.Format("Restart operation aborted   successfully?: {0}", CStr(isAborted)))
       Else
           Console.WriteLine("There is any restart operation to abort.")
       End If
       Console.ReadKey()

       ' Shutdown the current computer instantlly and force applications to close.
       ' ( When timeout is '0' the operation can't be aborted )
       SystemRestarter.Shutdown(Nothing, 0, Nothing, SystemRestarter.ShutdownMode.ForceSelf)

       ' LogOffs the current user.
       SystemRestarter.LogOff(SystemRestarter.LogOffMode.Wait)

   End Sub


Código fuente:
http://pastebin.com/FyH8U1ip
http://pastebin.com/3n9TbXB0 (corregido)

Fix:
El primer código no funcionaba, ya que al actualizar el código sin querer me equivoqué al escribir esto, lo dupliqué:
Citar
Código (vbnet) [Seleccionar]
Private Shared ReadOnly privilegeNameOfShutdown As String = "SeRemoteShutdownPrivilege"
Private Shared ReadOnly privilegeNameOfRemoteShutdown As String = "SeRemoteShutdownPrivilege"

Ya está corregido, resubido y testeado.








tincopasan

muchas veces he tenido que hacer aplicaciones como facturas y lo que siempre queda bien o piden es que el número se pase a letras, una funcíon vieja que hace eso, estoy seguro que Elektro lo hace más fácil pero igual acá va:
Código (vbnet) [Seleccionar]
Public Function NunAText(ByVal value As Double) As String
        Select Case value
            Case 0 : NunAText = "CERO"
            Case 1 : NunAText = "UN"
            Case 2 : NunAText = "DOS"
            Case 3 : NunAText = "TRES"
            Case 4 : NunAText = "CUATRO"
            Case 5 : NunAText = "CINCO"
            Case 6 : NunAText = "SEIS"
            Case 7 : NunAText = "SIETE"
            Case 8 : NunAText = "OCHO"
            Case 9 : NunAText = "NUEVE"
            Case 10 : NunAText = "DIEZ"
            Case 11 : NunAText = "ONCE"
            Case 12 : NunAText = "DOCE"
            Case 13 : NunAText = "TRECE"
            Case 14 : NunAText = "CATORCE"
            Case 15 : NunAText = "QUINCE"
            Case Is < 20 : NunAText = "DIECI" & NunAText(value - 10)
            Case 20 : NunAText = "VEINTE"
            Case Is < 30 : NunAText = "VEINTI" & NunAText(value - 20)
            Case 30 : NunAText = "TREINTA"
            Case 40 : NunAText = "CUARENTA"
            Case 50 : NunAText = "CINCUENTA"
            Case 60 : NunAText = "SESENTA"
            Case 70 : NunAText = "SETENTA"
            Case 80 : NunAText = "OCHENTA"
            Case 90 : NunAText = "NOVENTA"
            Case Is < 100 : NunAText = NunAText(Int(value \ 10) * 10) & " Y " & NunAText(value Mod 10)
            Case 100 : NunAText = "CIEN"
            Case Is < 200 : NunAText = "CIENTO " & NunAText(value - 100)
            Case 200, 300, 400, 600, 800 : NunAText = NunAText(Int(value \ 100)) & "CIENTOS"
            Case 500 : NunAText = "QUINIENTOS"
            Case 700 : NunAText = "SETECIENTOS"
            Case 900 : NunAText = "NOVECIENTOS"
            Case Is < 1000 : NunAText = NunAText(Int(value \ 100) * 100) & " " & NunAText(value Mod 100)
            Case 1000 : NunAText = "MIL"
            Case Is < 2000 : NunAText = "MIL " & NunAText(value Mod 1000)
            Case Is < 1000000 : NunAText = NunAText(Int(value \ 1000)) & " MIL"
                If value Mod 1000 Then NunAText = NunAText & " " & NunAText(value Mod 1000)
            Case 1000000 : NunAText = "UN MILLON"
            Case Is < 2000000 : NunAText = "UN MILLON " & NunAText(value Mod 1000000)
            Case Is < 1000000000000.0# : NunAText = NunAText(Int(value / 1000000)) & " MILLONES "
                If (value - Int(value / 1000000) * 1000000) Then NunAText = NunAText & " " & NunAText(value - Int(value / 1000000) * 1000000)
                'Case 1000000000000.0# : NunAText = "UN BILLON"
                'Case Is < 2000000000000.0# : NunAText = "UN BILLON " & NunAText(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
                'Case Else : NunAText = NunAText(Int(value / 1000000000000.0#)) & " BILLONES"
                '   If (value - Int(value / 1000000000000.0#) * 1000000000000.0#) Then NunAText = NunAText & " " & NunAText(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
        End Select


    End Function


uso: NumAText(1897432)

crack81

Buenas queria preguntas si en este hilo solo se puede publicar codigo de vb y c# o tambien se puede de otro lenguajes

Ya que me he dado la tarea de traducir parte del codigo aqui ya publicado y otro mio en el lenguaje Delphi  o mejor lo pongo en otro post?
Si C/C++ es el padre de los lenguajes entonces ASM es dios.

Eleкtro

Cita de: crack81 en  5 Julio 2015, 04:28 AM
Buenas queria preguntas si en este hilo solo se puede publicar codigo de vb y c# o tambien se puede de otro lenguajes

Ya que me he dado la tarea de traducir parte del codigo aqui ya publicado y otro mio en el lenguaje Delphi  o mejor lo pongo en otro post?

Este hilo es para publicar códigos de VisualBasic.Net, aunque .Net no es solamente VB.Net y C#, pero Delphi no forma parte de .Net, lo mejor será que crees un post en la sección de programación general.

Saludos!