Beresford
Beresford

Reputation: 187

Writing thumbnailPhoto property to Active Directory

I'm creating an application (.Net 3.5) to allow users to update their own photos and telephone numbers in Active Directory.

I'm using the UserPrincipal class, which I've extended using this example

    // Create the "thumbnailPhoto" property.    
    [DirectoryProperty("thumbnailPhoto")]
    public byte[] thumbnailPhoto
    {
        get
        {
            if (ExtensionGet("thumbnailPhoto").Length != 1)
                return null;

            return (byte[])ExtensionGet("thumbnailPhoto")[0];
        }
        set
        {
            ExtensionSet("thumbnailPhoto", value);
        }
    }

I get the byte array and write it to a pictureBox with

pictureBoxthumbnail.Image = Image.FromStream(new MemoryStream(userPrincipal.thumbnailPhoto));

This shows the picture, on the form, so far so good. When I try to write the image to Active Directory, I convert the pictureBox to a byte array with

userPrincipal.thumbnailPhoto = ImageManipulation.imageToByteArray(pictureBoxthumbnail.Image);

public static byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}

And try and save the data, but I get the following exception.

System.DirectoryServices.AccountManagement.PrincipalOperationException was unhandled

Message=Unspecified error

Source=System.DirectoryServices.AccountManagement

ErrorCode=-2147467259

I suspect my pictureBox to byte array is wrong. Is anyone able to help?

Thank you.

Upvotes: 2

Views: 4219

Answers (1)

Beresford
Beresford

Reputation: 187

I managed to get this working today using the function below. Hopefully this helps someone else.

    private void UpdatePhoto()
    {
        var principalContext = new PrincipalContext(ContextType.Domain);
        var userPrincipal = UserPrincipalEx.FindByIdentity(principalContext, System.Environment.UserName);

        DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("LDAP://{0}:389/{1}", principalContext.ConnectedServer, userPrincipal.DistinguishedName));
        directoryEntry.Properties["thumbnailPhoto"].Value = ImageManipulation.imageToByteArray(pictureBoxthumbnail.Image);
        directoryEntry.CommitChanges();
    }

Upvotes: 5

Related Questions