ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

GetValue

A bunch of extensions that work with SearchResult to retrieve its data.

Source

public static T GetValue<T>(this SearchResult result, string key)
{
    return result.GetValue(key, default(T));
}

public static T GetValue<T>(this SearchResult result, string key, T defaultValue)
{
    if (!result.Properties.Contains(key))
    {
        return defaultValue;
    }

    var resultPropertyValueCollection = result.Properties[key];
    if (resultPropertyValueCollection.Count == 0)
    {
        return defaultValue;
        
    }

    return (T) resultPropertyValueCollection[0];
}

public static IEnumerable<T> GetEnumerable<T>(this SearchResult result, string key)
{
    if (!result.Properties.Contains(key))
    {
        yield break;
    }

    var values = result.Properties[key];


    foreach (var value in values)
    {
        var valueCollection = value as T[];
        if (valueCollection != null)
        {
            foreach (var innerValue in valueCollection)
            {
                yield return innerValue;
            }
            yield break;
        }
        yield return (T) value;
    }
}

public static SecurityIdentifier GetObjectSid(this SearchResult result)
{
    if (result.Properties["objectSid"].Count > 0)
    {
        var binaryForm = (byte[])result.Properties["objectSid"][0];
        return new SecurityIdentifier(binaryForm, 0);
    }

    return null;
}

public static Guid? GetObjectGuid(this SearchResult result)
{
    if (result.Properties["objectGuid"].Count == 1)
    {
        var b = (byte[])result.Properties["objectGuid"][0];
        return new Guid(b);
    }

    return null;
}

Example

result.GetValue("sAMAccountName", String.Empty)

Author: john Simons

Submitted on: 17 jun 2010

Language: C#

Type: System.DirectoryServices.SearchResult

Views: 6563