Categories: Windows Phone, Code, WP7, Silverlight Posted by Shawn Oster on 2/15/2012 2:16 AM | Comments

I’m using the excellent REST library RestSharp for all my REST and OAuth calls.  I’m also using the amazing data caching framework AgFx written by Shawn Burke which handles caching your web requests, something that goes from a nice to have to critical when writing high performance Windows Phone apps.

Out of the box AgFx handles all your requests so it can do it’s caching thing, getting in the front of each request to determine if it should give you a cached version instead of hitting the web, if it should invalidate the cache, if it should give you a cached version and then make a live request, etc.  This is how you want it but sometimes you want more control over how those live requests are made.  In my case I’m using OAuth and requesting protected resources that require OAuth access tokens and RestSharp has some very nice methods for both authenticating and making those pesky protected calls.  The question is how to slip RestSharp into the middle of the AgFx mechanism?

AgFx Out of the Box

Your basic AgFx call looks like this:

ZipCodeVm viewModel = DataManager.Current.Load<ZipCodeVm>(txtZipCode.Text);

Which eventually executes code like this (which you the developer has written):

public LoadRequest GetLoadRequest(ZipCodeLoadContext loadContext, Type objectType)
{
    // build the URI, return a WebLoadRequest.
    string uri = String.Format(ZipCodeUriFormat, loadContext.ZipCode);
    return new WebLoadRequest(loadContext, new Uri(uri));
}

AgFx will call GetLoadRequest() to get a LoadRequest which it’ll use when it needs to fetch live data.  This example is using the default WebLoadRequest which uses HttpWebRequest under the covers to fetch the data but as long as you return an object that descends from LoadRequest you can use whatever requesting mechanism you like.

RestSharpLoadRequest

That’s where RestSharp comes in.  Instead of hand-crafting HTTP requests including hand-crafting headers and building POST payloads I’m going to let RestSharp do the heavy lifting by creating a custom RestSharpLoadRequest.  It’s based heavily on the WebLoadRequest in AgFX, right down to the comments and took all of 15 minutes to code up.  It’s not that exciting of a class but you can download it and view it on github as a gist:

An AgFx LoadRequest that uses RestSharp to make the actual request, supports passing in OAuth tokens

Download it and drop it into your application as is (well, I’d probably change the namespace to something more appropriate).  Sorry about it being a tar.gz file, maybe I’ll ping Phil Haack now that he works there to offer up .zips for gists as well.

WOW, sorry folks, I didn’t realize I’d created the Gist as private, if you tried to view it before you should have better luck now.

RestSharpLoadRequest in Action

I’m going straight to a meaty example where I create a few parameters to throw on the URL and pass in all my OAuth token goodness:

public LoadRequest GetLoadRequest(ShelfLoadContext loadContext, Type objectType)
{
    var resource = BuildResource(
        "review/list.xml",
        new Dictionary()
        {
            {"v", "2"},    
            {"id", loadContext.UserId},
            {"page", loadContext.Page.ToString()},                        
            {"shelf", loadContext.Shelf}
        });

    return new RestSharpLoadRequest(
        loadContext,
        resource,
        Client.Current.ConsumerKey,
        Client.Current.ConsumerSecret,
        Client.Current.AccessToken,
        Client.Current.AccessTokenSecret);
}

Don’t worry about the BuildResource call, that’s simply building up your REST API end-point (aka “resource”).  The only difference from the standard usage of AgFx is instead of a WebLoadRequest I’m using RestSharpLoadRequest.

And there you have it, now you can lean on RestSharp inside of the AgFx framework.  Also If you’re using Hammock as your REST library as choice it should take all of 15 minutes to whip up a HammockLoadRequest following the same basic principles.

UPDATE (02.14.2010): The way I was handing parameters above was just plain weird, the RestRequest object that I’m using inside of RestSharpLoadRequest already has robust AddParameter() logic so I exposed it.  The above code now looks like this:

public override LoadRequest GetLoadRequest(ShelfLoadContext loadContext, Type objectType)
{
    var request = new RestSharpLoadRequest(
        loadContext,
        GoodReadsClient.Current.BuildResource("review/list.xml"),
        GoodReadsClient.Current.ConsumerKey,
        GoodReadsClient.Current.ConsumerSecret,
        GoodReadsClient.Current.AccessToken,
        GoodReadsClient.Current.AccessTokenSecret);

    request.AddParameter("key", GoodReadsClient.Current.ConsumerKey);
    request.AddParameter("shelf", loadContext.Shelf);
    request.AddParameter("v", "2");
    request.AddParameter("id", loadContext.UserId);
    request.AddParameter("page", loadContext.Page.ToString());                

    return request;
}

Not only does it leverage existing code it follows the pattern most RestSharp/Hammock users are used to, namely you create the request and then you add on parameters.

Categories: Windows Phone, Silverlight, WP7, Mango Posted by Shawn Oster on 7/22/2011 11:16 PM | Comments

In a little app I’m working on to exercise some new Mango features I needed to create the message “bubble” and oddly enough didn’t stumble across any samples I could easily use even though a large number of apps have recreated this style, most likely because it’s so easy to do.

image

Here was my first take and it’s very hard-coded to the above look but it should be trivial to change it around.  Also there are dozen ways you could make this more reusable, either as a template for a ContentControl or as a new control.  If anyone has any suggestions for improvements or a better resource I’d love to see it!

XAML

<!-- bubble -->
<Grid Grid.Column="1"
		Margin="12,6,12,0">
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto" />
		<RowDefinition Height="Auto" />
	</Grid.RowDefinitions>
	<Path Data="M 16,12 16,0 0,12"
			Fill="{StaticResource PhoneAccentBrush}"
			HorizontalAlignment="Right"
			Margin="0,0,12,0"
			UseLayoutRounding="False"
			VerticalAlignment="Top" />
								
	<!-- Your actual content here -->
	<StackPanel Grid.Row="1"
				Background="{StaticResource PhoneAccentBrush}">
		<TextBlock Text="{Binding Mood}"
					Style="{StaticResource PhoneTextNormalStyle}"
					FontWeight="Bold"
					TextWrapping="Wrap"
					Margin="6,12,6,6"
					HorizontalAlignment="Left"
					VerticalAlignment="Top" />

		<TextBlock Text="{Binding LastUpdated, StringFormat='g'}"
					HorizontalAlignment="Right"
					VerticalAlignment="Top"
					Margin="6,0,6,6"
					Style="{StaticResource PhoneTextSubtleStyle}"
					FontFamily="Segoe WP SemiLight" />
	</StackPanel>
</Grid>

Note for the sharp-eyed I’m using a feature that is new for Mango that exists in Silverlight 4 which is default string formatting in bindings.

Categories: WP7, Mango, Silverlight, Windows Phone Posted by Shawn Oster on 7/20/2011 9:59 PM | Comments

In Mango we added the ability to interact with the shell’s native progress indicator along the top of the page.  This is a great way to maintain UI consistency with the phone as well as get a smooth progress animation because the system is handling the animation vs. the Silverlight runtime.  Here I’m recreating the ‘save to phone’ menu item you can see in the pictures hub by adding a “Saving picture…” progress indicator:

image

There are some great articles on using the new ProgressIndicator out there and I won’t do yet another intro blog post but I did want to share a little extension method I wrote to grab it from the page and avoid some of the annoying initialization code that you end up writing over and over again.

Some of my favorite ProgressIndicator articles so far for those looking to explore this in more depth are:

And here is my little extension method I’ve found useful on a few pages:

public static class Extensions
{
    public static ProgressIndicator GetProgressIndicator(this PhoneApplicationPage page)
    {
        var progressIndicator = SystemTray.ProgressIndicator;
        if (progressIndicator == null)
        {
            progressIndicator = new ProgressIndicator();
            SystemTray.SetProgressIndicator(page, progressIndicator);
        }
        return progressIndicator;
    }
}

I'm playing with using some of the various code snippet websites out there and this is embedded from Smipple. I'd love to see more Windows Phone snippets pop up on these sites.

UPDATE: Scratch the idea of embedding Smipple snippets via embed code, it looks awesome but seems to tweak my formatting, going back to good old syntax highlighted.

Categories: Windows Phone, Silverlight, WP7 Posted by Shawn Oster on 4/20/2011 12:25 AM | Comments

My talk from MIX11 has made its way online and for those that couldn’t attend (or those that were still recovering from the great attendee party and discovered that 9am is way too early to attempt to move) a video of my session is online over only channel9 available for streaming or downloading.

Channel9: What’s New for Windows Phone Development with Silverlight?

Also for your direct viewing pleasure here it is embedded.

For anyone that watches it and has questions, or people in the audience that didn’t get a chance to ask one feel free to drop me a line in the comments and I’ll do the best I can to find you the answers.

Also because not everyone had time to fill out their speaker evals if there is a type of content or way you’d like to see this content delivered in the future I’d love to hear your feedback in general.  More or less code? More technical details, would you prefer to see flashy demos that rock but require a lot of code or more simple demos that clearly show the feature?

MIX is for you so anything we can do to help improve content is greatly appreciated.