Search code examples
.netexchangewebserviceshttp-cachingews-managed-api

Caching user photos in Exchange Web Services


Per MSDN Docs on Contact Photos the following is too Vague I'd appreciate it if someone familiar with the subject can provide more insight as to how to do caching properly.

Here is my code so far...

https://msdn.microsoft.com/en-us/library/office/jj190905(v=exchg.150).aspx#bk_EWSMA

Caching user photos

Exchange returns the data with a content type of image/jpeg, along with a collection of header values. The ETag header is similar to a change key. The value is a string that represents the last time the photo was updated. The ETag remains the same for the user photo until the photo is changed. You can send this ETag value to the server in the HTTPS GET request in an If-None-Match header. If the photo hasn’t changed since the last request, the server will respond with an HTTP 304 response that indicates as such. This means that you can use the user photo that you previously requested and saved rather than processing a new one.

    Dim oPictureRequest As HttpWebRequest
    Dim strHttpPhotoEndPoint As String = pExchangeContact.Service.Url.ToString & "/s/GetUserPhoto?email=" & pExchangeContact.Service.ImpersonatedUserId.Id & "&size=HR240x240"
    Dim strPictureFilePath As String = config.PrivateContactPicturesPath & "/" & pEmployeeId.ToString & "/" & pCRMContact.ContactId.ToString & ".jpg"
    Dim oCachePolicy As New HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate)

    If pExchangeContact.HasPicture Then
        oPictureRequest = DirectCast(WebRequest.Create(strHttpPhotoEndPoint), HttpWebRequest)
        oPictureRequest.CachePolicy = oCachePolicy
        Using oPictureResponse As HttpWebResponse = DirectCast(oPictureRequest.GetResponse(), HttpWebResponse)
            If oPictureResponse.StatusCode = HttpStatusCode.OK Then
                Dim oPicture As Bitmap = New Bitmap(oPictureResponse.GetResponseStream())
                oPicture.Save(strPictureFilePath)
            End If
        End Using

    End If

Solution

  • It looks like you are already using the EWS Managed API if you get the latest version from github https://github.com/OfficeDev/ews-managed-api then you can use the SOAP operation and the Managed API has code to handle the headers eg

            String ETag = "";
            GetUserPhotoResults grPhoto = service.GetUserPhoto("user@domain.com", "HR240x240", ETag);
            if (grPhoto.Status == GetUserPhotoStatus.PhotoReturned) 
            {
                ETag = grPhoto.EntityTag; 
            }
            grPhoto = service.GetUserPhoto("user@domain.com", "HR240x240", ETag);
            switch (grPhoto.Status) 
            {
                case GetUserPhotoStatus.PhotoReturned: ETag = grPhoto.EntityTag;
                    break;
                case GetUserPhotoStatus.PhotoUnchanged:
                    Console.WriteLine("Photo Unchanged");
                    break;
            }