Share photos on Twitter from Windows Phone app

One of the things you might need Twitter authentication in your app for is to be able to share photos. In my last article, I described the way to get the user authenticated (PIN based authentication), and this article will show one of the methods for sharing photos on Twitter from Windows Phone app. Note that there are of course other solutions, this is just my way of handling it in my apps.

First of all, a personal note: I created a website for my app Photo Light.

If you haven’t, try downloading Photo Light – it integrates Twitter sharing so you can share the photos you edit on Twitter ;)

In case you were wondering what the last article was, here it is:

The result of this was an authentication object (called TwitterAccess) serialized to isolated storage

public class TwitterAccess  
        public string AccessToken { get; set; }
        public string AccessTokenSecret { get; set; }
        public string UserId { get; set; }
        public string ScreenName { get; set; }

Once you’ve acquired those details, you can share a photo on Twitter, or do anything else that the user allowed you to do on his or her Twitter.

Create a page for sharing a photo. In the end, it may look similar to this one:

It has a space for you to enter a message, which has a MaxLength property of 114, a character counter and the photo you’d like to share on Twitter. The button in the app bar starts photo sharing.

You will be sharing a photo with some text (Twitter message).

Deserialize the authentication information:

var file = SerializeHelper.LoadSetting<Common.TwitterAccess>("TwitterAccess");

Add the following libs to the class:

using Hammock;  
using Hammock.Authentication.OAuth;  
using TweetSharp;

Create a new TwitterService object:

TwitterService service = new TwitterService(Common.TwitterSettings.ConsumerKey, Common.TwitterSettings.ConsumerKeySecret);

Then, assuming you have a WriteableBitmap representation of your photo called LoadedPhoto. Write it to a memory stream:

MemoryStream ms = new MemoryStream();  
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 100);

Then create OAuthCredentials object

var credentials = new OAuthCredentials  
    Type = OAuthType.ProtectedResource,
    SignatureMethod = OAuthSignatureMethod.HmacSha1,
    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
    ConsumerKey = Common.TwitterSettings.ConsumerKey,
    ConsumerSecret = Common.TwitterSettings.ConsumerKeySecret,
    Token = file.AccessToken,
    TokenSecret = file.AccessTokenSecret,
    Version = "1.0"

ConsumerKey and ConsumerKeySettings are defined in a static class. See the last article for details. Now, create RestClient and RestRequest objects:

var restClient = new RestClient  
    Authority = ""

var restRequest = new RestRequest  
    Credentials = credentials,
    Path = "/1/statuses/update_with_media.xml",
    Method = Hammock.Web.WebMethod.Post

Define the REST callback method:

var callback = new RestCallback((restRt, restResponse, userState) =>  
    if (restResponse.StatusCode == HttpStatusCode.Unauthorized)
        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
          // ERROR OCCURRED, user not authenticated, try to authenticate him
    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
        // photo shared, tell the user that all went fine

Now, a very important part is that you set the memory stream position to 0, otherwise the photo will not be attached:

ms.Position = 0;

Add the text field (the message that will be shared along with the photo, string – should be around 110 to 114, if it’s larger than that you won’t be able to upload and the REST callback method will have an error), and a file:

restRequest.AddField("status", message);  
restRequest.AddFile("media[]", "ScreenShot.png", ms, "image/jpeg");

The name is not important, put whatever you like. I chose ScreenShot.png. Type is image/jpeg. Stream is the stream we defined earlier – the memory stream ms.

Call the BeginRequest method, with parameter restRequest and the callback method.

restClient.BeginRequest(restRequest, callback);

Of course, make sure that the status message is really not longer than 110 characters.

And that’s it, your photo is on Twitter!

Example of an uploaded photo is here:

About Igor Ralic

Software engineer at Microsoft. Running for Office. Passionate about making an impact with great apps & services. Stays close to coffee and away from coriander. Opinions expressed here are my own.