.comment-link {margin-left:.6em;}
Books & Articles I wrote.

Wednesday, February 08, 2006

 

Please dispose your directory connections

I have seen many people open a directory connection but not dispose it afterwards.

Please make sure you dispose of your directory connections - the easiest way is to use the using keywork as follows:

using (DirectoryEntry groupEntry = new DirectoryEntry("LDAP://"
+ LdapMachineName
+ ":"
+ LdapPort
+ LdapPartition
+ LdapReadersGroup,
LdapUserName,
LdapUserPassword,
AuthenticationTypes.Secure))
{
...
}

If you do not dispose them then the underlying COM connection remains open (ADSI takes care of the connection to the directory by itself, so don't worry about that) and you end up with a memory leak because the finalizer of the DirectoryEntry never calls unbind.

 read 0 comments | 
 

Adding to Groups in ADAM

In ADAM there are a few ways you can add a user to a group. The simplest is just to get an instance of the DirectoryEntry for that group and add the user to the "member" property as follows:

//get a group instance
DirectoryEntry groupEntry = new DirectoryEntry("LDAP://"
+ LdapMachineName
+ ":"
+ LdapPort
+ LdapPartition
+ LdapReadersGroup,
LdapUserName,
LdapUserPassword,
AuthenticationTypes.Secure);


//find the user we are talking of
DirectoryEntry duser = root.Children.Find("CN=steven", "user");

//add the user to the member property of our group
groupEntry.Properties["member"].Add(duser.Properties["distinguishedName"].Value);

//commit the changes
groupEntry.CommitChanges();


However, if you wish to do a straight commital, you can use Invoke as follows:

groupEntry.Invoke("Add", new object[] {"LDAP://"
+ LdapMachineName
+ ":"
+ LdapPort
+ "/" + duser.Properties["distinguishedName"].Value.ToString()});


What this does however is to call the IADs Add method via interop. So you can get the same effect as follows:

((ActiveDS.IADsGroup)groupEntry.NativeObject).Add("LDAP://"
+ LdapMachineName
+ ":"
+ LdapPort
+ "/" + duser2.Properties["distinguishedName"].Value.ToString());


It's more likely you will use CommitChanges(), but the other techniques can be useful if you wish to quickly update a membership.

 read 0 comments | 

This page is powered by Blogger. Isn't yours?

Weblog Commenting and Trackback by HaloScan.com