In my Exchange 2010 environment, we’re using the thumbnailPhoto attribute in active directory, so that users photos appear in Outlook 2010. We also have a custom intranet page that features a company directory which pulls details such as phone numbers from AD. I wanted to also add in the image stored in thumbnailPhoto for each user, so started to create a way of extracting the image that could be used in a web page.

I ended up with a C# ASP page, called userPhoto.aspx with the following contents:

<%@ Page Language="C#" %>
<%@ OutputCache Duration="6000" VaryByParam="u" %>
<%@ Import Namespace="System.DirectoryServices" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    private void Page_Load(object sender, EventArgs e)
    {
        String myUser = Request.QueryString["u"];

        if (myUser == null)
            Response.Redirect("app_graphics/user.jpg");

        Response.ContentType = "image/jpeg";
        Response.Clear();
        Response.BufferOutput = true;

        DirectoryEntry de = new DirectoryEntry();
        de.Path = "LDAP://OU=Users,DC=domain,DC=local";

        DirectorySearcher search = new DirectorySearcher();
        search.SearchRoot = de;
        search.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + myUser + "))";
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertiesToLoad.Add("thumbnailPhoto");

        SearchResult user;
        user = search.FindOne();

        String userName;
        if (user == null)
            Response.Redirect("app_graphics/user.jpg");
        else
            userName = (String)user.Properties["sAMAccountName"][0];

        try
        {
            byte[] bb = (byte[])user.Properties["thumbnailPhoto"][0];
            Response.BinaryWrite(bb);
            Response.Flush();
        }
        catch
        {
            Response.Redirect("app_graphics/user.jpg");
        }

    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>userImage</title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

You can then use the file by passing a parameter of u on a HTTP GET request, containing the users sAMAccountName.

For example, <img src=’userPhoto.aspx?u=gkendal’/>. Also, don’t forget to set the OU of where your user objects are in AD on line 21, and to add a placeholder image for those users that dont have anything stored in thier thumbnailPhoto attribute!

Leave a Reply