Archive for the ‘Silverlight’ Category
January 25th, 2012
So, you want to use Facebook to sign into something or in some way integrate Facebook with your Windows Phone 7 app. You are in luck because it is almost hilariously easy.
I’ve uploaded this tutorial as a zip file. I tried to github it, but I’m inching up on 1 hour of trying to figure out what the hell I’m doing wrong.
Download this Tutorial Project
I’ve tried to make this a full featured tutorial, so if you just want to get to the code, head down to the “Let the User Login To Facebook” section.
Get Your Facebook Key
Go to http://developers.facebook.com and log in with your Facebook account. Give them the permissions they need and go to the “Apps” tab. Click on “Create new App”
Fill in the App Display Name and the App Namespace and do the verification. Then you’ll get to a page that gives you your App ID and App Secret.

Don’t worry about anything else here… you don’t need to select anything in the “how your app integrates with Facebook” section to do this tutorial. If you’re using Facebook integration to do some basic login and simple posting, you could probably just use the Website option.
Also, click the “Graph API Explorer” on the left and keep that open. We’ll come back to that in a moment.
Add Facebook C# SDK
Download the Facebook C# SDK and extract it. Go to the “sl3-wp” folder and unblock the Facebook.dll file (right-click => Properties=>click “Unblock”)
Open up your project (for the example, I used the Visual Studio 10 “Windows Phone Databound Application” template) and right-click on “References => Add References…”. Click “Browse” and navigate to the Facebook.dll and add it to your project.
Build Facebook Login UI
We’ll do this quick here (no MVVM, no bindings) but in later versions I’ll integrate this into a more formal project.
Open your project in Blend. For this quick-and-dirty tutorial, we’ll just add another page title and another panel for the UI we want to show when the user is logged in and set the Visibility to Collapsed on those. Our visual tree should look like this.

In our loginPanel, we’re going to add a button and a WebBrowser to our panel. Set the button (containing “sign in using facebook” in the content) to the top and the WebBrowser to fill the panel. For a little flare, I’m going to add “ShowFacebookLogin” and “HideFacebookLogin” animations. My login screen now looks like this (the WebBrowser will animate in when we press the button).

When we get our data back, we’re going to tell the user it worked by showing their name and their Facebook avatar. So we’ll add a Grid with an Image and a TextBlock to display the user, along with a friendly “Hello”. (Make sure to name all these things so that we can update them from the code.)
OK… out UI is simple, but ready to roll. Now let’s do something when the user clicks the sign-in button. Go to the “Click” event and add a method like “StartFacebookLogin”.

Let the User Login to Facebook
Add “using Facebook;” to your references at the top of your MainPage.xaml.cs file. Now, add the following properties:
private FacebookClient _asyncFbClient;
private string _appID = "get from your facebook app page";
private string _appSecret = "get from your facebook app page";
Now go to your StartFacebookLogin method and add the following (explained at the end).
private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
string[] extendedPermissions = new[] { "user_about_me", "publish_stream" };
var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
var parameters = new Dictionary<string, object>
{
{"response_type", "token"},
{"display", "touch"}
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigated += new EventHandler<NavigationEventArgs>(CheckForAuth);
webBrowser.Navigate(loginUrl);
}
Remember how I told you to keep the Graph API open? Here is why. It has a big list of all the extendedPermissions that you can tell Facebook you want from the user. Here, we’ve asked for basic user information and the ability to publish to the user’s stream. Ask for only the permissions you need. The user can see the details of your permission request and may reject it if you ask too much.
Next, we create our OAuth client using out AppID and AppSecret and create a Dictionary of parameters communicating to Facebook the details of our request (for example, setting “display”, “touch” tells Facebook that we want the mobile interface.
We write out permission request into our parameters and then get a login url, which we will direct to our webBrowser. Here is what we will should get.

At the point Facebook walks the user through their login and, when they are done, it hands us back the access token we’ll need to get the user info and let the user make posts through our app.
This is why we attached the CheckForAuth event handler to our webBrowser. When we navigate to a new page, we’ll check to see if we got an access token using this code:
private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
if(Settings.Contains("MyFacebookAccessToken"))
Settings["MyFacebookAccessToken"] = result.AccessToken;
else
Settings.Add("MyFacebookAccessToken", result.AccessToken);
Settings.Save();
_asyncFbClient = new FacebookClient(result.AccessToken);
_asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
_asyncFbClient.GetAsync("/me");
}
}
}
If the Uri does contain a Facebook OAuth result and it is a success, we save the access token to our settings and then immediately use it to get the most basic user information.
The problem we have right now is that we have no class to structure the data that comes back. So get that all squared away.
First, right-click on “References” and select “Add Reference…”. Select “System.Runtime.Serialization”.
Next, add a class to your project (I added mine in a folder called “Models”) and name it FacebookUser.cs.

In that class, add the following code
[DataContractAttribute]
public class FacebookUser
{
public FacebookUser() { }
private string _id;
[DataMember(Name = "id")]
public string ID
{
get { return _id; }
set { _id = value; }
}
private string _name;
[DataMember(Name = "name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
}
The sample project has a much larger (although still incomplete) version of this model. But this one will do for our purposes.
We’ll make our “GetCompleted” event handler (remember that?) look like this:
void _asyncFbClient_GetCompleted(object sender, FacebookApiEventArgs e)
{
FacebookUser _fbUser = e.GetResultData<FacebookUser>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
fbName.Text = _fbUser.Name;
BitmapImage bi = new BitmapImage(new Uri("https://graph.facebook.com/" + _fbUser.ID + "/picture"));
fbAvatar.Source = bi;
HideFacebookLogin.Begin();
});
_asyncFbClient.GetCompleted -= _asyncFbClient_GetCompleted;
}
What we’ve done here is shove our data into a FacebookUser model. Then we use BeginInvoke to bring ourselves back to the UI thread and set all the properties we want.
Finally, we start the animation that hides the login data and shows that our Facebook login was a success.
Boom!

January 12th, 2012
This is really fast but it took me a while to figure out. I was getting the following on my recent project when I tried to save something using IsolatedStorageSettings:
“Operation not permitted on IsolatedStorageFileStream.”
And I couldn’t find anything about it other than a very generic “Looks like a threading problem” answers.
Long story short:
I was, in rapid succession, running the same save code twice. What I think happened was that the IsolatedStorageFileStream was still open and trying to save when I tried to get it to save again on another thread.
That’s my guess. I figured I’d toss up this short post on it before I forgot what the problem was.
January 11th, 2012
My initial concern here was to deal with tombstoning when it comes to HTTP requests, because that issue has kicked my butt on more than one account. But the second thing you’ll find here is a simple pattern for HTTP requests and responses in Windows Phone 7.
Most of the .NET code I look at uses WebClient to do HTTP requests. But using WebClient can negatively affect the UI thread in Windows Phone 7, so we have to do something a little more like this:
1: public void MakeSomeHTTPCall()
2: {
3: var request = (HttpWebRequest)WebRequest.Create("http://my.awesomewebsite.com");
4: request.Method = "GET";
5: request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);
6: }
Easy enough, right?
Not so fast!
If the user starts a request and then hits the “power” button on their phone, this will cancel that request. How can we tell when this has happened?
Well, we handle the response to this request in the “GetSomeResponse” method, so let’s take a look at that.
1: private void GetSomeResponse(IAsyncResult MyResultAsync)
2: {
3: HttpWebRequest request = (HttpWebRequest)MyResultAsync.AsyncState;
4: try
5: {
6: HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResultAsync);
7: if (response.StatusCode == HttpStatusCode.OK && response.ContentLength > 0)
8: {
9: using (StreamReader sr = new StreamReader(response.GetResponseStream()))
10: {
11: // This result string below is going to be whatever I get back,
12: // be it JSON or XML or whatever
13: string result = sr.ReadToEnd();
14: }
15: }
16: }
17: catch (WebException e)
18: {
19: if (e.Status == WebExceptionStatus.RequestCanceled)
20: MessageBox.Show("Looks like your request was interrupted by tombstoning");
21: else
22: {
23: using (HttpWebResponse response = (HttpWebResponse)e.Response)
24: {
25: MessageBox.Show("I got an http error of: " + response.StatusCode.ToString());
26: }
27: }
28: }
29: }
OK… let’s walk through this.
First, we get our request from the MyResultAsync.AsyncState (line 3), which we’ use to get our response (line 6). Now we can get a HTTP status code (like “200 – OK” or “404 – Not Found”) from this response, right?
No, we cannot. If the response is something other than OK, it will trigger an error and we will jump to the “catch” with a WebException error (line 17).
If we’re coming back from a tombstone (or Fast Application Switching, which will also cancel the request), the WebException status will be “RequestCanceled”. We test for that case and do something special for it (depending on the app, we may want to automatically re-do the request to ensure that we don’t put the user out of sorts by an errant power button press). Otherwise, we know it’s a normal HTTP status code and we can deal with it that way.
December 20th, 2011
I’m tired of trying to find things about Windows Phone 7 development, so I’m just going to post links that I find helpful so I can find them later.
Here’s Nick Harris with a handy set of static methods for getting the following unique IDs:
- Device Manufacturer ID
- DeviceExtendedProperties.TryGetValue(“DeviceManufacturer”, out someObject);
- example: “HTC”
- Device ID
- DeviceExtendedProperties.TryGetValue(“DeviceUniqueId”, out someObject);
- requires ID_CAP_IDENTITY_DEVICE in the app manifest which will trigger a warning to users when they install the app
- a byte[], converter to a string will looks like
“12345678901234567890123456789012345678901234567890123”
- Anonymous Windows Live ID
- A 32 character subset at offset 2 of the results of
“UserExtendedProperties.TryGetValue(“ANID”, out someObject)
- requires ID_CAP_IDENTITY_USER in the app manifest which will trigger a warning to users when they install the app
- looks like “00FF00FF00FF00FF00FF00FF00FF00FF”
However, if you just need any unique identifier (not necessarily a device ID), you can always set and store a new global unique identifier using:
Guid.NewGuid();
which will return a 128-bit integer that will look something like this:
“e81644f1-46b6-4994-2903-1d1f1440c130″
This will not cause warnings to appear when the app is downloaded because it isn’t a constant identifier to that specific device.
June 28th, 2011
OK… it’s been almost 2 months since I tried to start this series and now I’m going to finish it. A brief warning: this is done with pre-Mango bits so it won’t have all the latest, greatest most exciting things like the back-tile functionality or deep linking. (Here’s a good blog post on all that.) But it remains a good introduction.
Windows Phone 7 Push Notification Project Files (github)
The goal of this post is to provide a sample Push Notification application that is
- easy to test
- good architecture
- provides a sample web app for testing your push code (part of the delay has been because I’ve been trying to be a perfectionist on that web app. I’ve decided I’m never going to get around to making it perfect so this is the best I can do with the time I have)
Too many of the sample apps I’ve seen shove the push notification code in the xaml code-behind, leaving it to us to separate out the bits and translate it into a real project. This project uses MVVMLight binding and an event-driven architecture to get the push stuff working.
So… let’s dig into it.
I created a class called PushNotificationService that held a number of helpful little variables and objects. The most important variable here is
private static string _pushChannelName = "SampleAppNotification";
This name will delineate our push service from other services. If something weird happens and your push service stops working, the first thing you should do is change this string.
Next, we have a method that allows us to control when we get the push notification Uri. As an overview of what we’re doing,
- See if we already have a valid HttpNotificationChannel (the object that will control the push permissions and handle information from the Microsoft Push server)
- If we do have a valid HttpNotificationChannel, make sure we got the channel Uri correctly (the uri we will send out push notifications to). If we did, SUCCESS! Otherwise, go to step 3.
- Set the event handlers so we can handle when we get a new channel Uri back from the Microsoft Push server.
- Ask the Microsoft Push server for a new channel Uri.
- Set the HttpNotificationChannel up to handle the right kind of push notifications.
- Handle the returned uri from the Microsoft Push server & send it to the rest of the app.
Step 1
_notificationChannel = HttpNotificationChannel.Find(_pushChannelName);
Step 2
if (_notificationChannel.ChannelUri != null)
{
// Success! We run the event to send that info back to our ViewModel
RaiseGotPushUri(_notificationChannel.ChannelUri);
}
Step 3
else
{
_notificationChannel = new HttpNotificationChannel(_pushChannelName);
_notificationChannel.ChannelUriUpdated +=
new EventHandler<NotificationChannelUriEventArgs>(_notificationChannel_ChannelUriUpdated);
_notificationChannel.HttpNotificationReceived +=
new EventHandler<HttpNotificationEventArgs>(_notificationChannel_HttpNotificationReceived);
_notificationChannel.ErrorOccurred +=
new EventHandler<NotificationChannelErrorEventArgs>(_notificationChannel_ErrorOccurred);
}
Step 4
_notificationChannel.Open();
Step 5
BindNotifications(_notificationChannel);
Binding Details
In the pre-Mango push notifications, there are 3 kinds of push notifications and we have to announce what kind of notifications we plan on handling.
First, there are toast notifications, which look like this (stolen from Shawn Wildermuth):

Toast notifications consist of
- a title (“Toast Message” in the example above)
- a message (“This is from the server”)
To bind them, we simply type:
_thisChannel.BindToShellToast();
Tile notifications will only show up if the user has pinned the application to the front application tile board on the phone. I like to split Tile notifications into two types because we have to handle them differently in the code.
The first kind of tile notification is what I call “simple” Tile notifications. With simple Tile notifications, we can change a number and title on our app tile. The new title will show up where the title always shows up (at the bottom left) and the number will show up in a black circle at the top right.

Doing this much is simple:
_thisChannel.BindToShellTile();
But then there are Live Tiles, which allow us to send a whole new image to the tile to change it in a more holistic way to represent some push data. (We can still update numbers and titles too.) Live Tiles, however, require that we whitelist all the websites that might want to send an image to our phone. So we need to create a collection of whitelisted domains and add that to our tile binding.
System.Collections.ObjectModel.Collection<Uri> permittedImageHosts = new System.Collections.ObjectModel.Collection<Uri>();
permittedImageHosts.Add(new Uri("http://www.designersilverlight.com"));
_thisChannel.BindToShellTile(permittedImageHosts);
If you’re going to use my handy-dandy WP7 Push Tester, make sure you whitelist the exact domain above.
And that’s it… that’s all we need to do to get everything bound and ready to go! All we need now is to get the Uri from the Microsoft Push server so we know where to send our Push Notifications to.
Step 6
void _notificationChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
RaiseGotPushUri(e.ChannelUri);
}
This will run when we get the updated Uri back and we just send it in our event, which the ViewModel is listening to.
I’ve really streamlined the code in this blog post to deal with just the bare essentials. If you want to look at the project in detail, you can download it here.
Now, all we have to do is start testing it.
You can test it using my WP7 Push Notification web app. I’m also working on another post that walks through creating a push notification system using PHP, but in the meantime you might want to check out this PHP library that I used.
January 28th, 2011
When designing a “You are here” icon for the map in ShopSavvy (download now on iPhone, Android and Windows Phone 7. It’s free and super awesome), I decided to try something a little different. Because ShopSavvy is a theme-compliant application, I thought it might be fun to have the “you are here” icon be representation of the user’s actual phone.
So I created a little XAML icon that is a very rough approximation of the front Windows Phone 7 screen. I used shapes and theme-variant brushes so that the icon changes to represent whatever theme the user has in place on their phone.
Because the the icon is so small (48-by-80 px), I used only basic shapes and one custom path shape to represent the “maps” application. I also did everything on a “Canvas” in order to try to trim off as much layout computation time as possible. You could make it with a Grid and then scale it to your heart’s content. Probably won’t make a huge difference, but I’m paranoid about resources in my phone apps these days.
Here are a couple examples of how the icon could look, depending on the user’s theme choice:


All from the same XAML.
For the ShopSavvy version, I put a tiny little ShopSavvy icon at the top. In the code below, I took it out so the top right-hand will simply be a blank box. Or you would put a tiny version of your own app icon there.
Themed Windows Phone 7 Icon
- <Microsoft_Phone_Controls_Maps:Pushpin>
- <Border BorderBrush="#FF9B9B9B" BorderThickness="1"
- HorizontalAlignment="Center" Height="80"
- VerticalAlignment="Center" Width="48"
- CornerRadius="4" Background="Black">
- <Canvas>
- <Ellipse Fill="#FFE4E4E4" Height="3"
- Stroke="Black" Width="3"
- StrokeThickness="0"
- Canvas.Top="71"
- Canvas.Left="6"/>
- <Ellipse Fill="#FFE4E4E4"
- Height="3" Stroke="Black"
- Width="3" StrokeThickness="0"
- Canvas.Top="71" Canvas.Left="22"/>
- <Ellipse Fill="#FFE4E4E4" Height="3"
- Stroke="Black" Width="3"
- StrokeThickness="0"
- Canvas.Top="71" Canvas.Left="37"/>
- <Rectangle Height="62" Canvas.Left="3"
- StrokeThickness="0" Canvas.Top="5"
- Width="40" RadiusX="1"
- RadiusY="1"
- Fill="{StaticResource PhoneBackgroundBrush}"/>
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0"
- Width="13"
- Canvas.Left="7" Canvas.Top="9" />
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0" Width="13"
- Canvas.Left="21" Canvas.Top="9" />
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0" Width="13"
- Canvas.Left="7" Canvas.Top="23" />
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0" Width="13"
- Canvas.Left="21" Canvas.Top="23" />
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0" Width="27"
- Canvas.Left="7" Canvas.Top="37" />
- <Ellipse Height="3" Fill="{StaticResource PhoneForegroundBrush}"
- Stroke="Black" Width="3"
- StrokeThickness="0"
- Canvas.Top="10" Canvas.Left="37" />
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0"
- Width="13" Canvas.Left="7" Canvas.Top="51" />
- <Rectangle Fill="{StaticResource PhoneAccentBrush}"
- Height="13" StrokeThickness="0"
- Width="13" Canvas.Left="21" Canvas.Top="51" />
- <Ellipse Fill="White" Height="7" Stroke="Black"
- StrokeThickness="0" Width="7"
- Canvas.Top="12" Canvas.Left="10"/>
- <Rectangle Fill="White" Height="5" Stroke="Black"
- StrokeThickness="0" Width="7"
- Canvas.Left="10" Canvas.Top="27"/>
- <Rectangle Fill="White" Height="5" Stroke="Black"
- StrokeThickness="0" Width="5"
- Canvas.Left="28" Canvas.Top="43"/>
- <Rectangle Fill="White" Height="2" Stroke="Black"
- StrokeThickness="0"
- Canvas.Left="21" Canvas.Top="46" Width="5"/>
- <Path Data="M226.1875,316.1875 L230.5,321.5 L232.75,322 L234.25,324 L235.5,325.5 L236.75,327.25 L238.875,328.375 L238.9375,316.125 z"
- Fill="White" Height="12.25"
- Stretch="Fill" Stroke="Black"
- StrokeThickness="0" UseLayoutRounding="False"
- Canvas.Left="21.2"
- Canvas.Top="51.1" Width="12.751"/>
- <Rectangle Fill="White" Stroke="Black"
- StrokeThickness="0" Width="7" Height="5"
- Canvas.Left="9" Canvas.Top="55"/>
- <Ellipse Fill="White" Height="6"
- Stroke="Black" StrokeThickness="0"
- Width="6" Canvas.Top="26" Canvas.Left="24"/>
-
- </Canvas>
- </Border>
- </Microsoft_Phone_Controls_Maps:Pushpin>
Not much. Just something fun that I thought might be fun to share
January 27th, 2011
One of the things that I’ve been fascinated by since last year’s MIX conference is the motion design in place in Windows Phone 7. In a past life I worked as a video producer and I’m always stunned to see how well people respond to beautiful animations… especially in interface design.
You can see this fascination in my multiple blog posts on Windows Phone 7 motion design:
Now I’m trying to take my passion and talk about it at MIX 11. My goal with this talk is to show some excellent examples of practical motion design and show 1) how users really respond to good motion design and how it helps our applications seem more responsive and 2) show how to practically implement this motion design in our applications.
My goal is to help us all see how motion design is not icing on the cake, but an essential part of building beautiful applications. So, if you could, please vote for me and help me speak at MIX 11.
January 17th, 2011
App bars in Windows Phone 7 are actually a pretty cool little bit of functionality. They give the user 1-4 instantly accessible options for dealing with the screen the user is on, their buttons auto-animate in, they offer “always on” funtionality that isn’t going to be hidden by the on-screen keyboard, they give designers and developers instant access to a range of default icons in Windows Phone 7 ecosystem and they offer a much wider range of options when the user taps on the ellipses to open more options.
That’s a lot for such a little thing item. So you may be asking yourself, “What the hell is he talking about? What is an ‘App Bar’?” This:

And like this when the ellipses are tapped

But what gets me is the fact that making these things is so damn easy, thanks to the fact that Blend is the single greatest product ever created for people who want to design user interfaces. And you can quote me on that. My crush on the Microsoft Blend team is well documented.
Anyway.
So let’s go about mak
Making the App Bar
ing this app bar. You may be surprised to know that we can do pretty much everything we need to do without a single line of code. Because Blend is so stinking awesome.
First, select the PhoneApplicationPage in your Object and Timeline tab in Blend.

In the “Common Properties” section, you’ll see an “ApplicationBar” property. Click on the “New” button. You should see the following:

Add App Bar Buttons
Click on the “…” button to the right of “Buttons (Collection)”. Up will pop a “Collection Editor: Buttons” pop-up. Click on the “Add another item” button.

Type “Button” and you should see a “ApplicationBarIconButton” option.

Double-click on it. It will add an App bar button to your app bar. You should have a set of “Common Properties” that you can set. Type in the text you want (in our case, “done”) and click on the IconUri box. You will see a list of default Windows Phone 7 icons. Pick the one that works for you (I picked the check mark).

Do that same thing over again, but pick the close icon and give it the text “close”. Hit “OK” to close the app bar pop-up. Believe it or not, we’re done. Yeah, we need to hook up some Click events so they can actually do something, but the rest of it is all taken care of.
If you need to get back to the App Bar design, you can just click on the ApplicationBar in the “Objects and Timeline” and see the options again.
Add App Bar Menu Items
Adding menu items is similarly easy. Under the “Buttons (Collection)” item we clicked on earlier, there is a “MenuItems (Colleciton)” button. Click on it.

We see the same “Collection Editor and we’ll click “Add another item” again. This time, though, we type “menu” and double click on ApplicationBarMenuItem.

Add the text (“do one thing”) and run the process again to add another item. Click “OK” when you’re done.
Colors & the Application Bar
Designing the App Bar is pretty easy. The icons that we assigned to the buttons actually just act as opacity masks (I assume that’s how it works… it seems to make sense) so that they will change to whatever color is assigned to the foreground of the app bar. Warning: they will default to the theme foreground unless you explicitly set them to be another color. If you’ve decided not to work with the default theming engine, you will need to explicitly set the foreground and the background of the App Bar.
I talk about this a little bit more in my post on Windows Phone 7 theming. That might be a good place to go if you’re working on fine-tuning the app bar to fit into a non-themed design.
January 17th, 2011
Let’s say you don’t really want to play nice with the theming engine in Windows Phone 7. This would be pretty understandable… when you play nice with theming you either need to 1) come up with some nice innovative solution that detects themes and sets brushes and colors dynamically or 2) use only the black, white, gray and accent colors that Windows Phone 7 theming gives you by default.
If you want to create a design that uses some custom colors, it can be difficult to make sure those colors fit both themes, which can throw a cramp into your creative juices. Additionally, if you decide to toss theme-compatibility to the wind in favor of your own design, you’ll need to make sure all your control templates conform and don’t go all wonky when the user changes their theme.
This can be a pain.
To help in this endeavor, I would like to present two resource dictionaries and a sample project.
DarkStyles.xamly – rename to DarkStyles.xaml (irritating download issue)
LightStyles.xamly – rename to LightStyles.xaml (irritating download issue)
Theme Resistant Sample Project
The basic idea is that I found the source style resource dictionary for all the Windows Phone 7 controls. These styles are implicitly set by the system depending on the users’ settings. We can override these settings with our own local resources. So all we need to so is set either point to the LightStyles.xaml or the DarkStyles.xaml as resource dictionaries in the App.xaml and all the controls will ignore the system settings and conform to our defined settings. Another bonus is that you can use take these dictionaries and use them to play around with colors to see how a solid theme is built in Silverlight.
So, let’s quickly walk through the process of forcing a theme in your project.
First, use Blend. It’s awesome. (You could probably use Visual Studio too, I guess.)
In your project, if you don’t have a “Resources” folder, right-click on your project and create that folder.’

Now right click on your Resources folder and “Add An Existing Item…”. In the resulting pop-up navigate to either the DarkStyles.xaml or the LightStyles.xaml file.

This should add the necessary code auto-magically into your App.xaml, but double check. You should see something like this:

And that’s it! Sort of. I want to make note of a couple of clean-up issues.
Use Blend To Check Themes
First of all, you should know how to quickly test theming changes in Blend. In the top left-hand corner, you should see a set of tabs that say “Parts”, “Projects”, “Assets” etc. If it doesn’t say “Devices”, go to the menu bar and select “Window –> Device”. This will bring up a tab that looks like this:

From here you can change the theme and accent on the fly and see the changes in your design without running the app.
HOWEVER!
Some things don’t show up very well in the Blend theming, so always always always test your app on the emulator or on the phone.
Set Your Root Background
One of those things is that the default status for a PhoneApplicationPage is to have a transparent background. You’ll want to make sure that the LayoutRoot Grid (or layout element) in your application has the background set to “PhoneBackgroundBrush”.

Turn Off Your System Tray (Maybe)
Next, you might want to turn off the System Tray at the top of your app. That’s this thing

You have no control over what color it is, only whether or not it can be seen. Select the PhoneApplicationPage in your “Objects and Timeline” tab and uncheck the “Show SystemTray”. This is not a must (most apps will still look fine with the SystemTray on) but it’s something to think about

Set The Colors On Your App Bar
Finally, if you have an Application Bar in your screen, you’ll want to make sure the colors are explicitly set on those. (Don’t know how to make an application bar? Check this post out.) Select the ApplicationBar in your “Objects and Timeline”. Now click on the little box next to the BackgroundColor property and select “Local Resources –> PhoneChromeColor”.

Similarly, set the ForegroundColor to “LocalResources –> PhoneForegroundColor”.You’re all set… you now have a theme-proof application.
January 10th, 2011
Normally, I wouldn’t blog something that seems obvious, but it took me hours to figure this out and I always try to write blog posts for stuff that it took me a long time to figure out. Enormous props to Walt Ritscher (Twitter: @waltritscher) who helped me figure this out.
This blog post is for you if you have a sound file and you want it to:
- be included with the application when the user downloads the app
- play no matter what… even if the user is listening to music
First, grab the audio you want to add to the application and, if it’s not already a .wav file, make it so. If you’re just trying this out for kicks (or for the learning experience), download this files.
Coyote.wav
When prepping your audio, keep in mind if you want the user to hear it over their music. If so, make sure it is LOUD. I spent almost an hour thinking this method didn’t work because I couldn’t hear the sound over my music.
Next, create a directory in your Windows Phone 7 project and add your audio file like so:

Then select your audio file and change the “Build Action” to “Resource”

Now right-click on the “References” in your project and click “Add Reference…”. Find the “Microsoft.Xna.Framework” reference and add it to your project.


To the top of your class, add:
using Microsoft.Xna.Framework;
Now we’re going to create a stream from that resource and use that stream to play our sound.
StreamResourceInfo streamInfo = Application.GetResourceStream(
new Uri("/MyProjectName;component/Sound/Coyote.wav",
UriKind.Relative));
SoundEffect se = SoundEffect.FromStream(streamInfo.Stream);
SoundEffectInstance soundInstance = se.CreateInstance();
soundInstance.Play();
And that’s it. Your sound should play.
If you’re reading this, I assume you’re working with sound in some capacity. If you’re new to the work of sound and just want a simple way to edit and export sound files for your app, I highly recommend the free sound editing application Audacity. It saved me on my current project.
If you’re using Audacity and editing/creating sounds to hear while music is running, take whatever sound you have and amp up the gain so that the volume is peaking at about 0.

This sounds extreme, but it’s the only way I’ve been able to get the sounds to reliably make themselves heard over rock music.
I also recommend checking out Jaime Rodriguez’s post on running a Windows Phone app under the lock screen. That way you can play sounds even if the user allows the phone to lock itself.