I have a page that will allow and administrator to update user account details such as SamAccountName, Surname, etc., what I would like to be able to do is also update the actual account logon name and reanmve the user's container in AD. Is this possible
using .NET?
Here is what I have so far:
Dim CurrentUserName = Request.QueryString("UserName")
Dim UserName As String = tbx_UserName.Text.ToLower
Dim FirstName As String = tbx_FirstName.Text
Dim LastName As String = tbx_LastName.Text
Dim FInitial As String = tbx_FirstName.Text.ToLower
Dim FirstInitial As String = FInitial.Substring(0, 1)
Dim EmailAlias As String = tbx_EmailAddress.Text
If tbx_MiddleName.Text = String.Empty Then
Session("MiddleName") = "."
Else
Session("MiddleName") = tbx_MiddleName.Text
End If
Dim MiddleName As String = Session("MiddleName")
Dim newStringBuilder As New StringBuilder()
newStringBuilder.Append(tbx_UserName.Text)
newStringBuilder.Append("@tustin.k12.ca.us")
Dim Email As New String(newStringBuilder.ToString())
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT")
Using user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, CurrentUserName)
user.SamAccountName = LastName
user.Surname = LastName
user.GivenName = FirstName
user.MiddleName = MiddleName
user.DisplayName = LastName + ", " + FirstName
user.EmailAddress = Email
user.Save()
End Using
End Using
Thanks in advance.
Allan Browning
Vision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
The samaccountname is normally the user's logon name. This is not changed very often. If you do, you want to make sure the user is logged off their system before its done. This page gives samples of how to do many things in AD. Its in C but there are sites
you can paste the code and translate to VB,
http://www.codeproject.com/KB/system/everythingInAD.aspx. You will use CommitChanges() to update changes to user properties. You will use .Rename to rename the user object. Examples of both are in that link.
I can update all the attributes including the CN using the following EXCPET 'mailNickname'. If I update mailNickname I get the following errer:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 268: Using ctx = ChangeName.FindByIdentity(context, IdentityType.Name, UserName)
Line 269:
Line 270: ctx.mailNickname = SamAccountName
Line 271:
Line 272: ctx.Save()
Here is my code that updated everything except mailNickname:
Imports System.Data
Imports System.Text
Imports System.Data.SqlClient
Imports Telerik.Web.UI
Imports System.CodeDom
Imports System.Web
Imports System.Web.Security
Imports System.Web.Security.Roles
Imports System.Web.Security.Membership
Imports System.Security
Imports System.Security.Principal.WindowsIdentity
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Diagnostics
Imports System.Net
Imports System.Object
Imports System.Management
Imports System.Management.Automation
Imports System.Management.Automation.Host
Imports System.Management.Automation.Runspaces
Imports System.ServiceModel.Syndication
Imports System.Collections.ObjectModel
Imports System.Runtime.InteropServices
Imports System.Net.Mail
<DirectoryRdnPrefix("CN")> _
<DirectoryObjectClass("user")> _
Public Class ChangeName
Inherits GroupPrincipal
Public Sub New(ByVal context As PrincipalContext)
MyBase.New(context)
End Sub
Private searchFilter As ADGroupSearchFilter
Public ReadOnly Property AdvancedSearchFilter() As ADGroupSearchFilter
Get
If searchFilter Is Nothing Then
searchFilter = New ADGroupSearchFilter(Me)
End If
Return searchFilter
End Get
End Property
<DirectoryProperty("mailNickname")> Public Property mailNickname() As String
Get
If ExtensionGet("mailNickname").Length <> 1 Then
Return Nothing
End If
Return DirectCast(ExtensionGet("mailNickname")(0), String)
End Get
Set(ByVal value As String)
ExtensionSet("mailNickname", value)
End Set
End Property
Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityValue As String) As ChangeName
Return DirectCast(FindByIdentityWithType(context, GetType(ChangeName), identityValue), ChangeName)
End Function
Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityType As IdentityType, ByVal identityValue As String) As ChangeName
Return DirectCast(FindByIdentityWithType(context, GetType(ChangeName), identityType, identityValue), ChangeName)
End Function
Public Class ADGroupSearchFilter
Inherits AdvancedFilters
Public Sub New(ByVal p As Principal)
MyBase.New(p)
End Sub
End Class
End Class
Partial Class _Default
Inherits System.Web.UI.Page
''' <summary>
''' Function to extract just the login from the provided string (given in the format YOURDOMAIN\Username)
''' </summary>
''' <param name="path">Full AD login of the associate</param>
''' <returns>The login with the "YOURDOMAIN\" stripped</returns>
''' <remarks></remarks>
Public Shared Function ExtractUserName(ByVal path As String) As String
'Split on the "\"
Dim userPath As String() = path.Split(New Char() {"\"c})
'Return the rest (username part)
Return userPath((userPath.Length - 1))
End Function
''' <summary>
''' Helper method that sets properties for AD users.
''' </summary>
''' <param name="de">DirectoryEntry to use</param>
''' <param name="pName">Property name to set</param>
''' <param name="pValue">Value of property to set</param>
Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, ByVal pName As String, ByVal pValue As String)
'First make sure the property value isnt "nothing"
If Not pValue Is Nothing Then
'Check to see if the DirectoryEntry contains this property already
If de.Properties.Contains(pName) Then 'The DE contains this property
'Update the properties value
de.Properties(pName)(0) = pValue
Else 'Property doesnt exist
'Add the property and set it's value
de.Properties(pName).Add(pValue)
End If
End If
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim UserName As String = Request.QueryString("UserName")
Dim connectionString As String = DirectCast(ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString, String)
Dim conn As New SqlConnection(connectionString)
Dim comm As New SqlCommand("SELECT [UserName], [FirstName], [LastName], [aspnetUserID] FROM [vw_AD_ADSI_Extended_Users] WHERE ([UserName] = @UserName)", conn)
comm.Connection.Open()
comm.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = UserName
Dim myDataAdapter As New SqlDataAdapter(comm)
Dim myDataSet As New DataSet
Dim dtData As New DataTable
Dim dtRow As DataRow
myDataAdapter.Fill(myDataSet)
conn.Close()
For Each dtRow In myDataSet.Tables(0).Rows
Dim givenName As String = dtRow.Item("FirstName")
Dim surName As String = dtRow.Item("LastName")
Dim UserId As String = dtRow.Item("aspnetUserID")
'Create a DirectorySearcher Object (used for searching the AD)
Dim search As New DirectorySearcher()
'Set the filter on the searcher object to look for the SAMAccountName, givenName and the sn (Sur Name)
search.Filter = String.Format("(&(SAMAccountName={0})(givenName={1})(sn={2}))", ExtractUserName(UserName), givenName, surName)
'Now load these properties to the search
search.PropertiesToLoad.Add("cn")
search.PropertiesToLoad.Add("SAMAccountName") 'Users login name
search.PropertiesToLoad.Add("givenName") 'Users first name
search.PropertiesToLoad.Add("sn") 'Users last name
search.PropertiesToLoad.Add("DistinguishedName") 'Users last name
'Use the .FindOne() Method to stop as soon as a match is found
Dim result As SearchResult = search.FindOne()
'Now check to see if a result was found
hfd_DN.Value = (result.GetDirectoryEntry().Properties.Item("DistinguishedName").Value)
hfd_UserID.Value = UserId
Next
btn_ChangeName.Visible = False
End Sub
Protected Sub tbx_LastName_TextChanged(sender As Object, e As System.EventArgs) Handles tbx_LastName.TextChanged
If tbx_LastName.Text IsNot Nothing Then
Dim FInitial As String = tbx_FirstName.Text
Dim FirstInitial As String = FInitial.Substring(0, 1)
Dim LastName As String = tbx_LastName.Text
Dim UserNameString As New StringBuilder()
UserNameString.Append(FirstInitial)
UserNameString.Append(LastName)
Dim UserName As New String(UserNameString.ToString())
tbx_UserName.Text = UserName
End If
If Membership.GetUser(tbx_UserName.Text) IsNot Nothing Then
tbx_UserName.BackColor = Drawing.Color.LightPink
Panel1.BackImageUrl = "../../images/icon_exclaim_200.png"
Else
tbx_UserName.BackColor = Drawing.Color.LightGreen
Panel1.BackImageUrl = "../../images/icon_exclaim_200_g.png"
btn_ChangeName.Visible = True
End If
tbx_UserName.Focus()
End Sub
Protected Sub tbx_UserName_TextChanged(sender As Object, e As System.EventArgs) Handles tbx_UserName.TextChanged
If Membership.GetUser(tbx_UserName.Text) IsNot Nothing Then
tbx_UserName.BackColor = Drawing.Color.LightPink
Panel1.BackImageUrl = "../../images/icon_exclaim_200.png"
Else
tbx_UserName.BackColor = Drawing.Color.LightGreen
Panel1.BackImageUrl = "../../images/icon_exclaim_200_g.png"
btn_ChangeName.Visible = True
End If
End Sub
Protected Sub btn_ChangeName_Click(sender As Object, e As System.EventArgs) Handles btn_ChangeName.Click
Dim CurrentUserName = Request.QueryString("UserName")
Dim UserName As String = tbx_UserName.Text.ToLower
Dim FirstName As String = tbx_FirstName.Text
Dim LastName As String = tbx_LastName.Text
Dim FInitial As String = tbx_FirstName.Text.ToLower
Dim FirstInitial As String = FInitial.Substring(0, 1)
Dim LastNameLower As String = tbx_LastName.Text.ToLower
Dim SamAccountName = UserName
If tbx_MiddleName.Text = String.Empty Then
Session("MiddleName") = "."
Else
Session("MiddleName") = tbx_MiddleName.Text
End If
Dim MiddleName As String = Session("MiddleName")
Dim newStringBuilder As New StringBuilder()
newStringBuilder.Append(UserName)
newStringBuilder.Append("@tustin.k12.ca.us")
Dim Email As New String(newStringBuilder.ToString())
Dim ID As String = hfd_UserID.Value
Dim UserID As System.Guid = CType(System.ComponentModel.TypeDescriptor.GetConverter(UserID).ConvertFrom(ID), System.Guid)
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT")
Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, CurrentUserName)
user.SamAccountName = SamAccountName
user.UserPrincipalName = SamAccountName + "@tusd.local"
user.Surname = LastName
user.GivenName = FirstName
user.MiddleName = MiddleName
user.DisplayName = LastName + ", " + FirstName
user.EmailAddress = Email
user.Save()
End Using
End Using
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT")
Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, UserName)
Using ctx = ChangeName.FindByIdentity(context, IdentityType.Name, UserName)
ctx.mailNickname = SamAccountName
ctx.Save()
End Using
End Using
End Using
Dim objectDn As String = hfd_DN.Value
Dim child As New DirectoryEntry("LDAP://" + objectDn)
child.Rename("CN=" + SamAccountName)
Dim sql As String
Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString()
sql = "UPDATE AD_ADSI_Extended SET UserName = @UserName, FirstName = @FirstName, MiddleName = @MiddleName, LastName = @LastName, DisplayName = @DisplayName, EmailAddress = @EmailAddress WHERE UserName = @CurrentUserName"
Dim connection As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sql, connection)
'cmd.Parameters.Add("@IDModifiedUser", SqlDbType.UniqueIdentifier).Value = currentUserId
'cmd.Parameters.Add("@ModifiedDate", SqlDbType.DateTime).Value = DateTime.Now
cmd.Parameters.Add("@CurrentUserName", SqlDbType.NVarChar, 50).Value = CurrentUserName
cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 50).Value = UserName
cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = FirstName
cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar, 50).Value = MiddleName
cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = LastName
cmd.Parameters.Add("@DisplayName", SqlDbType.NVarChar, 50).Value = LastName + ", " + FirstName
cmd.Parameters.Add("@EmailAddress", SqlDbType.NVarChar, 50).Value = UserName + "@tustin.k12.ca.us"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Dim sql1 As String
Dim strConnString1 As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString()
sql1 = "UPDATE aspnet_Membership SET Email = @Email, LoweredEmail = @LoweredEmail WHERE UserId = @UserId"
Dim connection1 As New SqlConnection(strConnString1)
Dim cmd1 As New SqlCommand(sql1, connection1)
cmd1.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = Email
cmd1.Parameters.Add("@LoweredEmail", SqlDbType.NVarChar, 50).Value = Email
cmd1.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = UserID
cmd1.Connection.Open()
cmd1.ExecuteNonQuery()
cmd1.Connection.Close()
Dim sql2 As String
Dim strConnString2 As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString()
sql2 = "UPDATE aspnet_Users SET UserName = @UserName, LoweredUserName = @LoweredUserName WHERE UserId = @UserId"
Dim connection2 As New SqlConnection(strConnString2)
Dim cmd2 As New SqlCommand(sql2, connection2)
cmd2.Parameters.Add("@UserName", SqlDbType.NVarChar, 50).Value = UserName
cmd2.Parameters.Add("@LoweredUserName", SqlDbType.NVarChar, 50).Value = UserName
cmd2.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = UserID
cmd2.Connection.Open()
cmd2.ExecuteNonQuery()
cmd2.Connection.Close()
End Sub
End Class
Allan Browning
Vision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
Thank you for the reply, howver the directory search results are only there to ensure I am updating the correct user. I really do not even need to return anything from the search except the 'DistinguishedName' which I use to rename the 'CN'.
However, just in case, (he says with all humility), I did try adding mailNickname to the search results. Alas this still provides the same error.
On more thing. It's almost as if my AD has a different naming convention for some attributes. For example, in the following code I update the email address. If you look up what that attribute should be it is email, however, I must actually use the attribe
EmailAddress. Weird.
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT")
Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, CurrentUserName)
user.SamAccountName = SamAccountName
user.UserPrincipalName = SamAccountName + "@tusd.local"
user.Surname = LastName
user.GivenName = FirstName
user.MiddleName = MiddleName
user.DisplayName = LastName + ", " + FirstName
user.EmailAddress = Email
user.Save()
End Using
End Using
Allan Browning
Vision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
Found my issue. Programmer Failure. I was using the wrong Identifier for the CTX. It should have been CurrentUserName and not UserName.
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT")
Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, CurrentUserName)
user.SamAccountName = SamAccountName
user.UserPrincipalName = SamAccountName + "@tusd.local"
user.Surname = LastName
user.GivenName = FirstName
user.MiddleName = MiddleName
user.DisplayName = LastName + ", " + FirstName
user.EmailAddress = Email
user.Save()
End Using
End Using
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT")
Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, UserName)
Using ctx = ChangeName.FindByIdentity(context, IdentityType.Name, UserName)
ctx.mailNickname = SamAccountName
ctx.Save()
End Using
End Using
End Using
Thank you everyone.
Allan Browning
Vision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
Marked as answer by abrowning on Dec 13, 2011 04:17 PM
abrowning
Member
39 Points
68 Posts
Change User Name / Account Name
Dec 09, 2011 09:03 PM|LINK
I have a page that will allow and administrator to update user account details such as SamAccountName, Surname, etc., what I would like to be able to do is also update the actual account logon name and reanmve the user's container in AD. Is this possible using .NET?
Here is what I have so far:
Dim CurrentUserName = Request.QueryString("UserName") Dim UserName As String = tbx_UserName.Text.ToLower Dim FirstName As String = tbx_FirstName.Text Dim LastName As String = tbx_LastName.Text Dim FInitial As String = tbx_FirstName.Text.ToLower Dim FirstInitial As String = FInitial.Substring(0, 1) Dim EmailAlias As String = tbx_EmailAddress.Text If tbx_MiddleName.Text = String.Empty Then Session("MiddleName") = "." Else Session("MiddleName") = tbx_MiddleName.Text End If Dim MiddleName As String = Session("MiddleName") Dim newStringBuilder As New StringBuilder() newStringBuilder.Append(tbx_UserName.Text) newStringBuilder.Append("@tustin.k12.ca.us") Dim Email As New String(newStringBuilder.ToString()) Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT") Using user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, CurrentUserName) user.SamAccountName = LastName user.Surname = LastName user.GivenName = FirstName user.MiddleName = MiddleName user.DisplayName = LastName + ", " + FirstName user.EmailAddress = Email user.Save() End Using End UsingThanks in advance.
Vision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
gww
Contributor
2143 Points
458 Posts
Re: Change User Name / Account Name
Dec 10, 2011 12:13 AM|LINK
The samaccountname is normally the user's logon name. This is not changed very often. If you do, you want to make sure the user is logged off their system before its done. This page gives samples of how to do many things in AD. Its in C but there are sites you can paste the code and translate to VB, http://www.codeproject.com/KB/system/everythingInAD.aspx. You will use CommitChanges() to update changes to user properties. You will use .Rename to rename the user object. Examples of both are in that link.
abrowning
Member
39 Points
68 Posts
Re: Change User Name / Account Name
Dec 12, 2011 07:21 PM|LINK
Thank you for the response.
I can update all the attributes including the CN using the following EXCPET 'mailNickname'. If I update mailNickname I get the following errer:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 268: Using ctx = ChangeName.FindByIdentity(context, IdentityType.Name, UserName)
Line 269:
Line 270: ctx.mailNickname = SamAccountName
Line 271:
Line 272: ctx.Save()
Here is my code that updated everything except mailNickname:
Imports System.Data Imports System.Text Imports System.Data.SqlClient Imports Telerik.Web.UI Imports System.CodeDom Imports System.Web Imports System.Web.Security Imports System.Web.Security.Roles Imports System.Web.Security.Membership Imports System.Security Imports System.Security.Principal.WindowsIdentity Imports System.DirectoryServices Imports System.DirectoryServices.AccountManagement Imports System.Diagnostics Imports System.Net Imports System.Object Imports System.Management Imports System.Management.Automation Imports System.Management.Automation.Host Imports System.Management.Automation.Runspaces Imports System.ServiceModel.Syndication Imports System.Collections.ObjectModel Imports System.Runtime.InteropServices Imports System.Net.Mail <DirectoryRdnPrefix("CN")> _ <DirectoryObjectClass("user")> _ Public Class ChangeName Inherits GroupPrincipal Public Sub New(ByVal context As PrincipalContext) MyBase.New(context) End Sub Private searchFilter As ADGroupSearchFilter Public ReadOnly Property AdvancedSearchFilter() As ADGroupSearchFilter Get If searchFilter Is Nothing Then searchFilter = New ADGroupSearchFilter(Me) End If Return searchFilter End Get End Property <DirectoryProperty("mailNickname")> Public Property mailNickname() As String Get If ExtensionGet("mailNickname").Length <> 1 Then Return Nothing End If Return DirectCast(ExtensionGet("mailNickname")(0), String) End Get Set(ByVal value As String) ExtensionSet("mailNickname", value) End Set End Property Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityValue As String) As ChangeName Return DirectCast(FindByIdentityWithType(context, GetType(ChangeName), identityValue), ChangeName) End Function Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityType As IdentityType, ByVal identityValue As String) As ChangeName Return DirectCast(FindByIdentityWithType(context, GetType(ChangeName), identityType, identityValue), ChangeName) End Function Public Class ADGroupSearchFilter Inherits AdvancedFilters Public Sub New(ByVal p As Principal) MyBase.New(p) End Sub End Class End Class Partial Class _Default Inherits System.Web.UI.Page ''' <summary> ''' Function to extract just the login from the provided string (given in the format YOURDOMAIN\Username) ''' </summary> ''' <param name="path">Full AD login of the associate</param> ''' <returns>The login with the "YOURDOMAIN\" stripped</returns> ''' <remarks></remarks> Public Shared Function ExtractUserName(ByVal path As String) As String 'Split on the "\" Dim userPath As String() = path.Split(New Char() {"\"c}) 'Return the rest (username part) Return userPath((userPath.Length - 1)) End Function ''' <summary> ''' Helper method that sets properties for AD users. ''' </summary> ''' <param name="de">DirectoryEntry to use</param> ''' <param name="pName">Property name to set</param> ''' <param name="pValue">Value of property to set</param> Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, ByVal pName As String, ByVal pValue As String) 'First make sure the property value isnt "nothing" If Not pValue Is Nothing Then 'Check to see if the DirectoryEntry contains this property already If de.Properties.Contains(pName) Then 'The DE contains this property 'Update the properties value de.Properties(pName)(0) = pValue Else 'Property doesnt exist 'Add the property and set it's value de.Properties(pName).Add(pValue) End If End If End Sub Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load Dim UserName As String = Request.QueryString("UserName") Dim connectionString As String = DirectCast(ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString, String) Dim conn As New SqlConnection(connectionString) Dim comm As New SqlCommand("SELECT [UserName], [FirstName], [LastName], [aspnetUserID] FROM [vw_AD_ADSI_Extended_Users] WHERE ([UserName] = @UserName)", conn) comm.Connection.Open() comm.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = UserName Dim myDataAdapter As New SqlDataAdapter(comm) Dim myDataSet As New DataSet Dim dtData As New DataTable Dim dtRow As DataRow myDataAdapter.Fill(myDataSet) conn.Close() For Each dtRow In myDataSet.Tables(0).Rows Dim givenName As String = dtRow.Item("FirstName") Dim surName As String = dtRow.Item("LastName") Dim UserId As String = dtRow.Item("aspnetUserID") 'Create a DirectorySearcher Object (used for searching the AD) Dim search As New DirectorySearcher() 'Set the filter on the searcher object to look for the SAMAccountName, givenName and the sn (Sur Name) search.Filter = String.Format("(&(SAMAccountName={0})(givenName={1})(sn={2}))", ExtractUserName(UserName), givenName, surName) 'Now load these properties to the search search.PropertiesToLoad.Add("cn") search.PropertiesToLoad.Add("SAMAccountName") 'Users login name search.PropertiesToLoad.Add("givenName") 'Users first name search.PropertiesToLoad.Add("sn") 'Users last name search.PropertiesToLoad.Add("DistinguishedName") 'Users last name 'Use the .FindOne() Method to stop as soon as a match is found Dim result As SearchResult = search.FindOne() 'Now check to see if a result was found hfd_DN.Value = (result.GetDirectoryEntry().Properties.Item("DistinguishedName").Value) hfd_UserID.Value = UserId Next btn_ChangeName.Visible = False End Sub Protected Sub tbx_LastName_TextChanged(sender As Object, e As System.EventArgs) Handles tbx_LastName.TextChanged If tbx_LastName.Text IsNot Nothing Then Dim FInitial As String = tbx_FirstName.Text Dim FirstInitial As String = FInitial.Substring(0, 1) Dim LastName As String = tbx_LastName.Text Dim UserNameString As New StringBuilder() UserNameString.Append(FirstInitial) UserNameString.Append(LastName) Dim UserName As New String(UserNameString.ToString()) tbx_UserName.Text = UserName End If If Membership.GetUser(tbx_UserName.Text) IsNot Nothing Then tbx_UserName.BackColor = Drawing.Color.LightPink Panel1.BackImageUrl = "../../images/icon_exclaim_200.png" Else tbx_UserName.BackColor = Drawing.Color.LightGreen Panel1.BackImageUrl = "../../images/icon_exclaim_200_g.png" btn_ChangeName.Visible = True End If tbx_UserName.Focus() End Sub Protected Sub tbx_UserName_TextChanged(sender As Object, e As System.EventArgs) Handles tbx_UserName.TextChanged If Membership.GetUser(tbx_UserName.Text) IsNot Nothing Then tbx_UserName.BackColor = Drawing.Color.LightPink Panel1.BackImageUrl = "../../images/icon_exclaim_200.png" Else tbx_UserName.BackColor = Drawing.Color.LightGreen Panel1.BackImageUrl = "../../images/icon_exclaim_200_g.png" btn_ChangeName.Visible = True End If End Sub Protected Sub btn_ChangeName_Click(sender As Object, e As System.EventArgs) Handles btn_ChangeName.Click Dim CurrentUserName = Request.QueryString("UserName") Dim UserName As String = tbx_UserName.Text.ToLower Dim FirstName As String = tbx_FirstName.Text Dim LastName As String = tbx_LastName.Text Dim FInitial As String = tbx_FirstName.Text.ToLower Dim FirstInitial As String = FInitial.Substring(0, 1) Dim LastNameLower As String = tbx_LastName.Text.ToLower Dim SamAccountName = UserName If tbx_MiddleName.Text = String.Empty Then Session("MiddleName") = "." Else Session("MiddleName") = tbx_MiddleName.Text End If Dim MiddleName As String = Session("MiddleName") Dim newStringBuilder As New StringBuilder() newStringBuilder.Append(UserName) newStringBuilder.Append("@tustin.k12.ca.us") Dim Email As New String(newStringBuilder.ToString()) Dim ID As String = hfd_UserID.Value Dim UserID As System.Guid = CType(System.ComponentModel.TypeDescriptor.GetConverter(UserID).ConvertFrom(ID), System.Guid) Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT") Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, CurrentUserName) user.SamAccountName = SamAccountName user.UserPrincipalName = SamAccountName + "@tusd.local" user.Surname = LastName user.GivenName = FirstName user.MiddleName = MiddleName user.DisplayName = LastName + ", " + FirstName user.EmailAddress = Email user.Save() End Using End Using Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT") Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, UserName) Using ctx = ChangeName.FindByIdentity(context, IdentityType.Name, UserName) ctx.mailNickname = SamAccountName ctx.Save() End Using End Using End Using Dim objectDn As String = hfd_DN.Value Dim child As New DirectoryEntry("LDAP://" + objectDn) child.Rename("CN=" + SamAccountName) Dim sql As String Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString() sql = "UPDATE AD_ADSI_Extended SET UserName = @UserName, FirstName = @FirstName, MiddleName = @MiddleName, LastName = @LastName, DisplayName = @DisplayName, EmailAddress = @EmailAddress WHERE UserName = @CurrentUserName" Dim connection As New SqlConnection(strConnString) Dim cmd As New SqlCommand(sql, connection) 'cmd.Parameters.Add("@IDModifiedUser", SqlDbType.UniqueIdentifier).Value = currentUserId 'cmd.Parameters.Add("@ModifiedDate", SqlDbType.DateTime).Value = DateTime.Now cmd.Parameters.Add("@CurrentUserName", SqlDbType.NVarChar, 50).Value = CurrentUserName cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 50).Value = UserName cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = FirstName cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar, 50).Value = MiddleName cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = LastName cmd.Parameters.Add("@DisplayName", SqlDbType.NVarChar, 50).Value = LastName + ", " + FirstName cmd.Parameters.Add("@EmailAddress", SqlDbType.NVarChar, 50).Value = UserName + "@tustin.k12.ca.us" cmd.Connection.Open() cmd.ExecuteNonQuery() cmd.Connection.Close() Dim sql1 As String Dim strConnString1 As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString() sql1 = "UPDATE aspnet_Membership SET Email = @Email, LoweredEmail = @LoweredEmail WHERE UserId = @UserId" Dim connection1 As New SqlConnection(strConnString1) Dim cmd1 As New SqlCommand(sql1, connection1) cmd1.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = Email cmd1.Parameters.Add("@LoweredEmail", SqlDbType.NVarChar, 50).Value = Email cmd1.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = UserID cmd1.Connection.Open() cmd1.ExecuteNonQuery() cmd1.Connection.Close() Dim sql2 As String Dim strConnString2 As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("IT_CentralConnectionString").ConnectionString() sql2 = "UPDATE aspnet_Users SET UserName = @UserName, LoweredUserName = @LoweredUserName WHERE UserId = @UserId" Dim connection2 As New SqlConnection(strConnString2) Dim cmd2 As New SqlCommand(sql2, connection2) cmd2.Parameters.Add("@UserName", SqlDbType.NVarChar, 50).Value = UserName cmd2.Parameters.Add("@LoweredUserName", SqlDbType.NVarChar, 50).Value = UserName cmd2.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = UserID cmd2.Connection.Open() cmd2.ExecuteNonQuery() cmd2.Connection.Close() End Sub End ClassVision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
gww
Contributor
2143 Points
458 Posts
Re: Change User Name / Account Name
Dec 12, 2011 10:30 PM|LINK
Looks like you need to load that property in your search
search.PropertiesToLoad.Add("mailnickname")
abrowning
Member
39 Points
68 Posts
Re: Change User Name / Account Name
Dec 13, 2011 02:50 PM|LINK
Thank you for the reply, howver the directory search results are only there to ensure I am updating the correct user. I really do not even need to return anything from the search except the 'DistinguishedName' which I use to rename the 'CN'.
However, just in case, (he says with all humility), I did try adding mailNickname to the search results. Alas this still provides the same error.
On more thing. It's almost as if my AD has a different naming convention for some attributes. For example, in the following code I update the email address. If you look up what that attribute should be it is email, however, I must actually use the attribe EmailAddress. Weird.
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT") Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, CurrentUserName) user.SamAccountName = SamAccountName user.UserPrincipalName = SamAccountName + "@tusd.local" user.Surname = LastName user.GivenName = FirstName user.MiddleName = MiddleName user.DisplayName = LastName + ", " + FirstName user.EmailAddress = Email user.Save() End Using End UsingVision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.
abrowning
Member
39 Points
68 Posts
Re: Change User Name / Account Name
Dec 13, 2011 04:16 PM|LINK
Found my issue. Programmer Failure. I was using the wrong Identifier for the CTX. It should have been CurrentUserName and not UserName.
Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT") Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, CurrentUserName) user.SamAccountName = SamAccountName user.UserPrincipalName = SamAccountName + "@tusd.local" user.Surname = LastName user.GivenName = FirstName user.MiddleName = MiddleName user.DisplayName = LastName + ", " + FirstName user.EmailAddress = Email user.Save() End Using End Using Using context = New PrincipalContext(ContextType.Domain, "TUSTIN_NT") Using user = UserPrincipal.FindByIdentity(context, IdentityType.Name, UserName) Using ctx = ChangeName.FindByIdentity(context, IdentityType.Name, UserName) ctx.mailNickname = SamAccountName ctx.Save() End Using End Using End UsingThank you everyone.
Vision Quest Integrated Technologies, Inc.
www.VisionQuestIT.com
If you solve your issue, please post the solution.