views:

85

answers:

3

Hi,

I am reading this article on how to work with AD via C#. Half way through the article, the below code is presented.

The user account properties are checkboxes. Does anyone have any idea what the below line of code will return for a checked checkbox? What if more than 1 checkbox is checked? I'd have thought a bool being returned would be more intuitive?

//Add this to the create account method

int val = (int)newUser.Properties["userAccountControl"].Value; 
 //newUser is DirectoryEntry object

Why do we do the logical or below? How does it work between an int and the second value (is that a byte?)

 newUser.Properties["userAccountControl"].Value = val | 0x80000; 
//ADS_UF_TRUSTED_FOR_DELEGATION

I know that sounds very naive...

Thanks

A: 

userAccountControl is a flag field, that's why they put it into an int.

See http://support.microsoft.com/kb/305144 for more information.

Moose
A: 

Based on the information that you are giving, I would guess that they are using a flags type system to indicate selected items. Each option has a specific value, and they are added up so you can get back which are selected.

This would be proved by the logical or that is used to see if a specific value is included.

Mitchel Sellers
+1  A: 

The userAccountControl property contains a two byte value in which each single bit has a significant meaning. If the bit is on, then some option is used - if it's not on, then the option is not present.

This is more compact and more space optimized than having a gazillion of booleans. Also, many "older" Win16 and Win32 API just simply work this way.

The bitwise "AND" operator is used to check for the presence of such a single bit:

if (newUser.Properties["userAccountControl"].Value & 0x400 == 0x400)

in this case, the 0x400 bit is set.

In order to actually set a bit, you use the bitwise "OR" operator:

newUser.Properties["userAccountControl"].Value = val | 0x800

This sets the "0x800" bit.

It's basic bit-wise boolean logic, really. A bit messy, indeed - but .NET has some help to make things a bit easier (check out the BitArray data type, for instance)

marc_s