Binary Data Conversion

The process of converting attributes that contain binary data is very similar to that used for the other standard data types. In this case, both Directory-Entry and DirectorySearcher will convert the attribute data to a single-dimensional array of bytes:

//given our DirectoryEntry entry //and SearchResult result from our previous examples byte[] sid = (byte[]) entry.Properties["objectSid"].Value; sid = (byte[]) result.Properties["objectSid"][0];

What about Boxing of Value Types?

It is true that System.Boolean, System.Int32, System.Int64, and System.DateTime are all .NET value types or structures, yet the SDS collection classes cast them as System.Object. As developers, we should be aware that when value types are cast to and from reference types like System.Object, the .NET Framework does something called boxing and unboxing. A performance penalty is associated with boxing and unboxing, and many developers have been taught to try to avoid it when possible.

Unfortunately, this is one of the situations where we cannot avoid it. Because the LDAP data types are returned as a mix of reference types and value types, there really is no other way for the collection classes to work. Does this make things slower? Probably, but if we consider it in the overall scheme of things, it is not so bad. Nearly all of this data is retrieved via network calls and it goes through many layers before it gets to our code. Try to relax and not worry about it. Try some of the other performance tips we suggest in the book, and if you get desperate, you are probably using the wrong API. Check out SDS.P or consider dropping .NET entirely and look at the Win32 LDAP API instead.

If the attribute contains multiple values, we simply do the same thing in a foreach loop:

foreach (byte[] cert in entry.Properties["userCertificate"]) { //do something useful... }

We can also use the Value property again here with PropertyValueCollection. In the case of multiple values, it will return a jagged array of byte arrays.

Категории