Wednesday, October 24, 2012

Byte arrays instead of strings when retrieving custom attributes from Active Directory.

Few days ago when I was working with Active Directory I noticed a strange thing. I was quering AD for user with a custom string attribute. The results were being varied on different dev boxes. On one of them I was getting attribute's value as a string but on another - as a byte array.

When I set application pool Identity with the same AD account user identity on both dev boxes I get the same behavior. So I thought that one of AD accounts doesn't have enough access rights to get AD schema.

The goal was to retrieve a Guid from this attribute so I decided to implement a method which can handle all major cases. Here what I got:

public static Guid GuidFromADAttribute(object attribute)
{
    if (attribute is byte[])
    {
        var bytes = (byte[])attribute;
        switch (bytes.Length)
        {
            case 16:
                return new Guid(bytes);
            case 36:
                var stringRepresentation = Encoding.Default.GetString(bytes);
                Guid result;
                return Guid.TryParse(stringRepresentation, out result) ? result : default(Guid);
        }
    }
    else if (attribute is string)
    {
        Guid result;
        return Guid.TryParse((string) attribute, out result) ? result : default(Guid);
    }

    return default(Guid);
}

I kept the opportunity to retrieve "normal" Guid from AD. By "normal" I mean 16 bytes long. Another option here is to pass byte array representation of guid string (it must be 36 bytes long in order to be parsed). The final option is to pass a string representation of guid.

The bad thing is that I didn't find the cause of such a strange AD behavior. Here is the list of similar posts:

Friday, October 19, 2012

Add link between contact and organization entities in Mediachase ecommerce framework

Yesterday I was trying to assign a contact to organization in my code. It seemed really natural to had such a requirement but unfortunatelly I didn't find any examples.

In Mediachase.Commerce.Customers.CustomerContext class there is a method called InnerGetAllCustomerContactsInOrganization. It lists all Contact entities filtered by OwnerId field. So we can set link between this two entities in a following way:
myContact.OwnerId = myOrganization.PrimaryKeyId;
Hope this helps.