Friday, April 11, 2008

.NET Journal::Converting AD integer values into bitmapped enumerations

I have often found it useful to store information in bitmap enumerations e.g. [Flags] while programming in c#. Many of my projects have included storing persistent data in Active Directory or ADAM (Active Directory Application Mode) which requires conversion when getting data out of storage.

Here's a quick tidbit about the easiest and most abstractable way to approach such a task. In our example, we are storing an enumeration call "InheritanceModel ", defined as:

[Flags]
public enum InheritanceModel
{
Undefined = 0x0,
None =0x1,
Standard = 0x2,
Invertable = 0x4,
Overrideable = 0x8,
Blockable = 0x10
}

The [Flags] attribute is what allows us to manipulate the values using boolean logic (AND, OR, NOT, etc.). It is not particularly efficient to store such information as a converted string, so we store it as an integer. Our AD/ADAM ldap attribute is defined as an integer, we'll call it "InheritanceModel".

We can get and convert the integer value as follows:

InheritanceModel _InheritanceModel = InheritanceModel.Undefined;
DirectoryEntry _de = new DirectoryEntry(
LDAP://localhost:50000/CN=Folder,CN=....);

if (_de.Properties.Contains("InheritanceModel"))
{
foreach (int iValue in System.Enum.GetValues(typeof(InheritanceModel)))
{
// this shows how we can use the System.Enum functions to see the string value
string sInheritanceModel = System.Enum.GetName(typeof (InheritanceModel), iValue).ToString();
if ((iValue & (int)_de.Properties[("InheritanceModel"].Value) > 0)
{
_InheritanceModel = (InheritanceModel)System.Enum.ToObject(typeof (InheritanceModel), iValue);
}
}
}