Basics of Reading Attribute Values
As we discussed in Chapters 3 and 4, SDS provides two mechanisms for reading attribute data. The DirectoryEntry class allows us to read data for a particular object in the directory via the PropertyCollection and PropertyValueCollection classes. The DirectorySearcher class allows similar functionality through the ResultPropertyCollection and ResultPropertyValueCollection classes on the SearchResult class.
The design of these two sets of classes is remarkably similar, so knowledge about one pair generally applies to the second. There are some subtle but important differences, however.
The Basic Design
Both PropertyCollection (from DirectoryEntry) and ResultPropertyCollection (from SearchResult) are typical .NET dictionary-type collection classes with a string key and the value as a PropertyValueCollection or ResultPropertyValueCollection, respectively. Each key corresponds to an attribute held by the parent object. There are no really important differences between these two property collection classes, so we can think of them the same way in practice.
The actual attribute values are stored in the PropertyValueCollection and ResultPropertyValueCollection classes. These classes are typical .NET array-style collections that use an integer value for indexing. The values are typed as System.Object because the directory may contain many different types of data (byte[], System.Int64, System.String, etc.) and System.Object is the only common base class. Like all array-style collections in .NET, we may enumerate the value collections using either a foreach construct or a for loop that indexes values numerically.
Because the directory may contain multivalued attributes, the class library designers opted always to represent attribute values with a collection class. Attributes with a single value are simply represented by a collection class with one value and null values use an empty collection. This provides a consistent programming model.
While this leads to a common model, it also tends to be a source of confusion for first-time SDS developers, who expect to be able to differentiate easily between a single-valued attribute and a multivalued attribute. We will mention some tips in this chapter and point out that it becomes easier to identify these kinds of things with experience.
Key Differences between the Value Collections
There are a number of important differences between the two types of value collections.
- ResultPropertyValueCollection is read-only, and PropertyValueCollection allows editing.
- PropertyValueCollection has a helper property called Value, and ResultPropertyValueCollection does not.
- They use two different mechanisms for converting ADSI data types to .NET data types.
The last point is subtle, but it is the most important one to understand in order to avoid confusion later on. We will be covering this point in detail later in this chapter.