spotlight
     
     
WWWCoder.com Resource Directory

Methods for Active Directory Management
12/16/2003 4:44:31 PM

Here we provide several methods for managing your Active Directory database via ASP.Net code. We'll cover querying user information using System.DirectoryServices, changing user accounts, and group management.

In this function we'll run a query against Active Directory to obtain properties for the current account logged onto our application. First we'll specify an array of the properties we want to retrieve from AD, then pass it to our GetADsObject method (later in this article), and set authentication to AD in order to run and retrieve information from our query.


 Private Const _FILTER As String = "(&(ObjectClass={0})(sAMAccountName={1}))"
Private Const _FOREST = 5                       'Default for a Forest objectClass
Private Const _DOMAINCHILD = 13                 'Default for a Domain objectClass
Private Const _UNIVERSAL_SECURITY = -2147483640
Private Const _GLOBAL_SECURITY = -2147483646

Dim sLoadProps As String() = {"givenName", "sn", "StreetAddress", "l", _
    "PostalCode", "co", "telephonenumber", "mail"}
Dim loginUser As String = "MyUser"
Dim userInfo As DirectoryEntry = GetADsObject("person", loginUser, sLoadProps, False)
If Not userInfo Is Nothing Then
  'set authentication info for using ADs, feel free to create
  'a function for authenticating to AD.
  userInfo.AuthenticationType = AuthenticationTypes.Delegation
  userInfo.Username = "username"
  userInfo.Password = "password"
  With userInfo
    'Get properties
    Dim fName As String = CheckForNothing(.Properties("GivenName").Value)
    Dim lName As String = CheckForNothing(.Properties("sn").Value)
    Dim sStreet As String = CheckForNothing(.Properties("StreetAddress").Value)
    Dim sCity As String = CheckForNothing(.Properties("l").Value)
    Dim sPostalCode As String = CheckForNothing(.Properties("PostalCode").Value)
    Dim sCountry As String = CheckForNothing(.Properties("co").Value)
    Dim sTelephone As String = CheckForNothing(.Properties("telephonenumber").Value)
    Dim sUserName As String = LoginID
    Dim sMail As String = CheckForNothing(.Properties("mail").Value)
    'Update ADs properties
    .Properties("GivenName").Value = FirstName
    .Properties("sn").Value = LastName
    .Properties("StreetAddress").Value = Street
    .Properties("l").Value = City
    .Properties("PostalCode").Value = PostalCode
    .Properties("co").Value = countryName
    .Properties("c").Value = countryCode
    .Properties("telephonenumber").Value = Telephone
    .Properties("mail").Value = Email
    'Save changes
    .CommitChanges()                       
  End With                
End If
::
::
::
::
::
'function to make sure we check for null.
Private Function CheckForNothing(ByVal value As Object) As String
  If value Is Nothing Then
    Return ""
  Else
    Return value.ToString
  End If
End Function

Obtaining Group Membership for a User

In the next block of code we'll pass our user information and obtain the group membership for the user account:

Dim sLoadProps As String() = {"memberOf"}
'Get Directory Entry object 
Dim userInfo As DirectoryEntry = GetADsObject("person", loginUser, sLoadProps, False)
If Not userInfo Is Nothing Then
  'set authentication info for using ADs, feel free to create
  'a function for authenticating to AD.
  userInfo.AuthenticationType = AuthenticationTypes.Delegation
  userInfo.Username = "username"
  userInfo.Password = "password"
  Dim iCount As Integer = userInfo.Properties("MemberOf").Count
  If iCount > 0 Then
    'Retrive group membership from Windows ADs and add to arraylist
    For i = 0 To iCount - 1
      Dim gADs As String = userInfo.Properties("MemberOf").Item(i)
      Dim myGroup As String = Left(gADs, (InStr(gADs, ",") - 1))
      arrGroup.Add(myGroup.Replace("CN=", ""))
    Next                        
  End If
End If

Creating New Groups in AD

In the next method we'll create a new group within Active Directory:

Dim groupName As String = "MyGroup"
Dim Description As String = "MyGroup Description"
Dim root As Object = GetObject("GC://rootDSE")
Dim strNameContext As String = root.Get("DefaultNamingContext")
Dim ADsContainer As New DirectoryEntry("LDAP://CN=users," + strNameContext)
'set authentication info for using ADs, feel free to create
'a function for authenticating to AD.
ADsContainer.AuthenticationType = AuthenticationTypes.Delegation
ADsContainer.Username = "username"
ADsContainer.Password = "password"
Dim newGroup As DirectoryEntry = ADsContainer.Children.Add("CN=" + groupName, "group")
With newGroup
  .Properties("saMAccountname").Value = groupName
  .Properties("groupType").Value = _UNIVERSAL_SECURITY
  .Properties("Description").Value = Description
  .CommitChanges()
End With
            

Updating an AD Group

In this next method we'll update properties for a group. We can rename the group, or change description.

Dim groupName As String = "MyGroup"
Dim sLoadProps As String() = {"name", "Description"}
'Get group object in ADs
Dim grp As DirectoryEntry = GetADsObject("group", groupName, sLoadProps, True)
If Not grp Is Nothing Then
  'set authentication info for using ADs, feel free to create
  'a function for authenticating to AD.
  grp.AuthenticationType = AuthenticationTypes.Delegation
  grp.Username = "username"
  grp.Password = "password"
  With grp
    If LCase(groupName) <> LCase(newGroupName) Then
      .Rename("CN=" + newGroupName)
    End If
    .Properties("Description").Value = Description
    'Save change
    .CommitChanges()
  End With
End If            

Deleting an AD Group

Now we'll delete the newly created group from AD.

Dim groupName As String = "MyGroup"
Dim sLoadProps As String() = {"name", "Description"}
'Get group object in ADs
Dim grp As DirectoryEntry = GetADsObject("group", groupName, sLoadProps, True)
If Not grp Is Nothing Then
  'set authentication info for using ADs, feel free to create
  'a function for authenticating to AD.
  grp.AuthenticationType = AuthenticationTypes.Delegation
  grp.Username = "username"
  grp.Password = "password"
  grp.DeleteTree()
  grp.CommitChanges()
End If           

Adding a User to a Group

We've gone over users and groups, now lets add a user to a group.

'Get object in ADs
Dim usr As DirectoryEntry = GetADsObject("person", loginUser, sUserProps, False)
Dim grp As DirectoryEntry = GetADsObject("group", groupName, sLoadProps, True)
If Not grp Is Nothing And Not usr Is Nothing Then
  'set authentication info for using ADs, feel free to create
  'a function for authenticating to AD.
  usr.AuthenticationType = AuthenticationTypes.Delegation
  usr.Username = "username"
  usr.Password = "password"
  grp.AuthenticationType = AuthenticationTypes.Delegation
  grp.Username = "username"
  grp.Password = "password"
  If Not IsMember(usr, grp) Then
    Dim strDisName As String = usr.Properties("distinguishedName").Value
    grp.Properties("Member").Add(strDisName)
    grp.CommitChanges()
  End If
End If

Removing a User from an AD Group

Now remove the user from the group that the account was added to.

Dim loginUser As String = Right(loginID, Len(loginID) - InStr(loginID, "\"))
Dim sUserProps As String() = {"name", "distinguishedName"}
Dim groupName As String = RoleName
Dim sLoadProps As String() = {"member"}
'Get user & group object in ADs
Dim usr As DirectoryEntry = GetADsObject("person", loginUser, sUserProps, False)
Dim grp As DirectoryEntry = GetADsObject("group", groupName, sLoadProps, True)
If Not grp Is Nothing And Not usr Is Nothing Then
  'set authentication info for using ADs, feel free to create
  'a function for authenticating to AD.
  usr.AuthenticationType = AuthenticationTypes.Delegation
  usr.Username = "username"
  usr.Password = "password"
  grp.AuthenticationType = AuthenticationTypes.Delegation
  grp.Username = "username"
  grp.Password = "password"
  If IsMember(usr, grp) Then
    Dim strDisName As String = usr.Properties("distinguishedName").Value
    grp.Properties("member").Remove(strDisName)
    grp.CommitChanges()
  End If
End If

GetADsObject Function

The following function accepts the type of object (ADsType) you wish to query in AD, the name of the object, for example the user account, an array of properties, and a Boolean value for specifying whether or not to query an LDAP path or the Global Catalog for your AD.

Private Function GetADsObject(ByVal ADsType As String, ByVal ADsName As String, _
      ByVal LoadProps As String(), ByVal LDAP As Boolean) As DirectoryEntry
  Dim ADsFilter As String = String.Format(_FILTER, ADsType, ADsName)
  Dim ADsRoot = GetObject("GC://rootDSE")
  Dim strRootForest As String
  'Get RootDomain for your AD forest.
  If LDAP Then
    strRootForest = "LDAP://" & ADsRoot.get("rootDomainNamingContext")
  Else
    strRootForest = "GC://" & ADsRoot.get("rootDomainNamingContext")
  End If
  Dim root As New DirectoryEntry(strRootForest)
  root.AuthenticationType = AuthenticationTypes.Delegation
  root.Username = "username"
  root.Password = "password"
  Dim searcher As New System.DirectoryServices.DirectorySearcher(root)
  searcher.SearchScope = SearchScope.Subtree
  searcher.ReferralChasing = ReferralChasingOption.All
  searcher.PropertiesToLoad.AddRange(LoadProps)
  searcher.Filter = ADsFilter
  Dim search As SearchResult = searcher.FindOne()
  Dim ADsObject As DirectoryEntry = search.GetDirectoryEntry
  Return ADsObject
End Function

By: Patrick Santry, Microsoft MVP (ASP/ASP.NET), developer of this site, author of books on Web technologies, and member of the DotNetNuke core development team. If you're interested in the services provided by Patrick, visit his company Website at Santry.com.

Related Articles
   Related Document Obtaining Active Directory User Information Using System.DirectoryServices


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 8/2/2009 12:02:31 AM by Anonymous
Comments: Can this code be used in a windows service? Thanks.
No ratings available.
Left on 6/4/2009 3:02:10 AM by Anonymous
Comments: where to write the above codes
Left on 3/5/2007 2:38:56 AM by Anonymous
Comments: "Loginid is not declared", what is this supposed to be set to?
No ratings available.
Left on 2/1/2007 4:31:59 AM by Anonymous
Comments:
No ratings available.
Left on 10/4/2006 4:34:07 AM by Anonymous
Comments: i want to get the list of usernames according to the roles(groups)... how do i do that....
Plz mail @ sandeepan.kundu@tv18online.com
Left on 5/23/2006 7:26:29 AM by Anonymous
Comments: DalSoft:
Good example the MSDN documentation is lacking examples
when it comes to the System.DirectoryServices class, this should get developers started.
I would change the GetADsObject to use the managed
DirectoryEntry instead of COM interop GetObject see my example below:


Private Function GetADsObject(ByVal ADsType As String, ByVal ADsName As String, _
            ByVal LoadProps As String(), ByVal LDAP As Boolean) As DirectoryEntry


        Dim ADsFilter As String = String.Format(_FILTER, ADsType, ADsName)
        Dim ADSroot As New DirectoryEntry("GC://rootDSE")
        Dim strRootForest As String

        'Get RootDomain for your AD forest.
        If LDAP Then
            strRootForest = "LDAP://" & ADSroot.Properties("rootDomainNamingContext").Value.ToString()
        Else
            strRootForest = "GC://" & ADSroot.Properties("rootDomainNamingContext").Value.ToString()
        End If
Left on 3/29/2006 1:23:52 AM by Anonymous
Comments: The "add to group" doesn't work if you have 2 trusted domain. And want to add a user from the domain that the group isn't in.
Left on 3/3/2006 3:24:03 AM by Anonymous
Comments: veeeerrrrrrrrrryyyyyyyyyy nice
Left on 9/6/2005 7:45:24 PM by Anonymous
Comments: Sorry, but you can't get the password. It is stored as a encrypted hash and there is no way to get the information. You can authenticate against the password via code, i.e. have someone pass in a value in your code and it return true or false if the user logon is correct. This would enable a Web based logon of an account, but still no way to get at the password.
No ratings available.
Left on 9/6/2005 7:28:26 PM by Anonymous
Comments: Is it possible to retrieve password information, like in a "send password by e-mail" scenario?
No ratings available.
Left on 5/31/2005 4:07:15 PM by Anonymous
Comments: Don't need help with the easy stuff
Left on 5/19/2005 12:49:05 PM by Anonymous
Comments: It'd be great if I could just fart out code. Then I could truly say I code in my sleep.
No ratings available.
Left on 5/19/2005 12:46:51 PM by Anonymous
Comments: Its like you just farted this code out after a hard night of drinking!
Left on 3/18/2005 10:41:16 PM by Anonymous
Comments: How can I get basic user information like official name for user id and who user reports to without using username and password information?
No ratings available.
Left on 1/27/2005 3:11:28 AM by Anonymous
Comments: just remove If IsMember(usr, grp)
No ratings available.
Left on 11/16/2004 1:32:20 PM by Anonymous
Comments: This list is still not complete, will this look at nested groups?
No ratings available.
Left on 10/5/2004 12:19:02 AM by Anonymous
Comments: thanks alot very useful
Left on 9/24/2004 12:42:27 AM by Anonymous
Comments: how to get users using ASP Code
No ratings available.
Left on 8/3/2004 3:05:59 PM by Anonymous
Comments: I am trying to get the groups for all users. The code crashes at "memberOf"
No ratings available.
Left on 6/22/2004 9:30:05 AM by Anonymous
Comments: Where/what is the IsMember method/function?
Left on 5/21/2004 9:37:52 PM by Anonymous
Comments: Thank you.
http://www.cibilliyet.com
Left on 4/30/2004 3:11:15 PM by Anonymous
Comments: Very nice pices of code, but has anyone tried to create a distribution group, ie. what constant should be added to the groupType property ??
Help apreciated - thanks!
No ratings available.
Left on 4/23/2004 5:54:30 AM by Anonymous
Comments: All examples worked except Adding a User to a Group example.  http://adminblogs.com/steve/archive/2004/04/22/318.aspx i posted the solution I came up with.  Thanks you saved me lots of time!
Left on 4/22/2004 9:12:47 PM by Anonymous
Comments: Comments from the following blog: Steve Schofield Weblog, located at: http://weblogs.asp.net/steveschofield/archive/2004/04/22/118605.aspx
No ratings available.
Left on 4/22/2004 9:07:54 PM by Anonymous
Comments: Comments from the following blog: AdminBlogs.com, located at: http://adminblogs.com/steve/archive/0001/01/01/318.aspx
No ratings available.
Left on 4/22/2004 9:07:04 PM by Anonymous
Comments: Comments from the following blog: AdminBlogs.com, located at: http://adminblogs.com/steve/archive/2004/04/22/318.aspx
No ratings available.
Left on 2/6/2004 8:00:02 AM by Anonymous
Comments: dio can
No ratings available.
Left on 1/27/2004 10:56:00 PM by Anonymous
Comments: Saved me some time. Thanks!
No ratings available.
Left on 12/23/2003 9:51:26 PM by Anonymous
Comments: Good!
Left on 12/19/2003 11:25:41 AM by Anonymous
Comments: One problem is that memberOf does not include the users Primary Group. You have to go through some hoops to get that.
     
     

 

 

     
     

 


 


Digg This
 


DotNetNuke Platinum Benefactor

 


 


Digg This
 


DotNetNuke Platinum Benefactor

     
     

Other family network sites: santry.com - katieandkarleigh.com

Powered by 

 

     
Copyright 20010 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970
Privacy Statement | Terms Of Use