How does one read in and start processing an AD User Attribute when it’s value is NOT SET? When it is set to some legal value it is very easy to read and extract the value and this is well documented. But when it is NOT SET, then there is no clue as to how to read without it blowing up in your face.
I was working on a custom application application development and had the need to read in user’s AD attributes. For those that are new to this, an Active Directory (AD) user can have several attributes. Examples would be userName, Account Expiry Date, Smart Card Required for Log on, etc.,.
In this case I had to read in the values of a custom attribute that was added to the AD Schema.
Typically one would read in the string value using the following notation.
Now this will work as long as the actual value stored is a non null. When you use ADSIEDIT.MSC tool to see the property values, if they are null you would see them as <Not Set>. If you try to use the same code as above to read in a user property’s value when it is not set then it would give a null reference exception. This caused me some (countless hours) grief and nowhere could I found it documented, on how to read in the value when it is unset like this. The trick is to read in the value into an object and then check for the object’s null’ness. If it is not set, then you don’t try to read and cast it. Else go ahead and read it and start processing.
Object o = user.Properties["customSecurityFlag"].Value;
if (o == null)
customString = "Unknown flag value";
int customFlagValue = (int)user.Properties["customSecurityFlag"].Value;
// case statements for integers
// so on
Hopefully someone will find this useful or have a better solution.