Posts Tagged ‘Windows Phone 7’
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 2nd, 2012
I just spent a couple days on this and, in the end, I didn’t really figure it out. Someone else at my work (the brilliant Rylan Barnes) showed me the workaround for it.
So… you want to add a cookie to your Windows Phone 7 Silverlight HttpWebRequest. Guess what? It sucks to be you! Or, at least, it sucked to be me because I couldn’t find anything on how to do this that worked.
I was working on a project that requires the user to authenticate and, on authentication, sends back a token (unique to that user) to be attached as a cookie for further authentication. However, when I attached the cookie and made my next request, it made that request without the authorization header. Our server said “Hey, looks like you’re not authenticated, I will now forget about that last cookie because you obviously didn’t get it. Have a new one!”
First I’m going to show you things that don’t work.
Didn’t Work: Adding An Empty Cookie Container to the Request
public void DoSomeCRUD(string userName, string pass)
{
HttpWebRequest request = System.Net.HttpWebRequest.Create("https://myurl.com") as HttpWebRequest;
if (HasSavedCookieContainer)
request.CookieContainer = SavedCookieContainer();
else
request.CookieContainer = new CookieContainer();
request.Credentials = new NetworkCredential(userName, pass);
request.BeginGetResponse(new AsyncCallback(GetMyResponse), request);
}
private void GetMyResponse(IAsyncResult MyResponseAsync)
{
HttpWebRequest request = (HttpWebRequest)MyResponseAsync.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResponseAsync);
// this method save the cookie container to IsolatedStorage
// so I can attach it to the request the next time I open the app.
SaveCookieContainer(request.CookieContainer);
}
The saving worked, the cookie container came back just as I saved it. And then… it didn’t work. It was as if the cookie didn’t exist.
Didn’t Work: Ripping The Token Out Of the “Set-Cookie” Header
public void DoSomeCRUD(string userName, string pass)
{
HttpWebRequest request = System.Net.HttpWebRequest.Create("https://myurl.com") as HttpWebRequest;
if (IsolatedStorageSettings.ApplicationSettings.Contains["MyToken"])
{
string myToken = (string)IsolatedStorageSettings.ApplicationSettings["MyToken"];
Cookie c = new Cookie("MyCookieName", myToken, "[valid path]", "[valid domain]");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Uri("http://myurl.com"), c);
}
else
request.CookieContainer = new CookieContainer();
request.Credentials = new NetworkCredential(userName, pass);
request.BeginGetResponse(new AsyncCallback(GetMyResponse), request);
}
private void GetMyResponse(IAsyncResult MyResponseAsync)
{
HttpWebRequest request = (HttpWebRequest)MyResponseAsync.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResponseAsync);
// this method looked for "Set-Cookie" information in the header
// and the pulls out the token data by brute force and save the
// token as a string
if (ResponseHasSetCookieInHeader(response))
{
string rawToken = GetTokenFromResponse(response);
IsolatedStorageSettings.ApplicationSettings["MyToken"] = rawToken;
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
The save worked here too, but the same result… it was like the cookie didn’t exist.
This Worked: Adding the Cookie as a Header
Finally we added the token and the credential information as header items. This finally worked.
public void DoSomeCRUD(string userName, string pass)
{
HttpWebRequest request = System.Net.HttpWebRequest.Create("https://myurl.com") as HttpWebRequest;
if (IsolatedStorageSettings.ApplicationSettings.Contains["MyToken"])
request.Headers["Cookie"] = "MyTokenName=" + (string)IsolatedStorageSettings.ApplicationSettings["MyToken"];
request.Headers["Authentication"] = "Basic " + Convert.ToBase64String(StringToAscii(userName, pass));
request.BeginGetResponse(new AsyncCallback(GetMyResponse), request);
}
private void GetMyResponse(IAsyncResult MyResponseAsync)
{
HttpWebRequest request = (HttpWebRequest)MyResponseAsync.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResponseAsync);
// this method looks for "Set-Cookie" information in the header
// and the pulls out the token data, saving it to Isolated Storage
if (ResponseHasSetCookieInHeader(response))
{
string rawToken = GetTokenFromResponse(response);
IsolatedStorageSettings.ApplicationSettings["MyToken"] = rawToken;
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
For the sake of giving credit, here is the StringToAscii method for the Authentication, tweaked from this StackOverflow answer from Hans Passant
public static byte[] StringToAscii(string userName, string pass)
{
string s = userName + ":" + pass;
byte[] retval = new byte[s.Length];
for (int ix = 0; ix < s.Length; ++ix)
{
char ch = s[ix];
if (ch <= 0x7f) retval[ix] = (byte)ch;
else retval[ix] = (byte)'?';
}
return retval;
}
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.
April 18th, 2011
I know there are about a thousand blog posts on implementing push notifications in a Windows Phone 7 application. But having now implemented push notifications a couple times into WP7 projects, I felt like something was missing from the community knowledge base. So, in order to try to cover WP7 Push notifications for the uninitiated, I’m putting together a set of posts will try to cover the following topics:
- Windows Phone 7 Push Notifications (10,000 Foot View)
- Implementing Push Notifications on a Device (with Project code)
- Testing Push Notifications On My Device Without Writing a Goddamn Web Service (Also, How To Write A WP7 Push Service in PHP)
Windows Phone 7 Push Notifications (10,000 Foot View)
The Windows Phone 7 push notification is actually an extremely elegant way of doing push notifications. Personally, I love it. I’ll walk through the steps conceptually here and then mirror the steps in the code post.
(Note to experts: I may be getting some of the details about how this works in the underlying architecture wrong. However, this is how it seems to me that it works and it makes sense this way.)
Step 1: Say “Hey, phone! I want to send you push notifications about some stuff.” When you do this, you’re doing it with a couple of conditions. The first is that you’re giving your specific push service a name (like “Bob” but hopefully a little more specific).
Next, you’ll need to determine if you want to use the “Toast” notification or the “Tile” notification or the “Raw” notification or some combination of these three. When you know what kind of notifications you want, you’ll basically write a magic piece of code which communicates to the magical push notification fairy, who, in return for your good deeds, gives you a device/application specific URL that you will use to send notifications to your phone.

You think I’m kidding. I’m not. As a preview, the code you need to write is: “myPushStuff.Open()”. And that’s it. Then you just wait for the magical push notification fairy to give you the URL you’ll use to send notifications to your phone.
You don’t actually need to send information about toast and tile to the push registration service. However, if you decide later on thatyou actually wanted to send a toast notifications, not a tile notification, your old URL won’t work… you’ll need to save a new one. Don’t know why or how exactly this happens… just passing along helpful information.
If you’re looking for information about the difference between tile, toast and raw notifications, the image below was stolen from the msdn article that talks about the differences. Go read about it there… I won’t stoop to copying and pasting all their excellent information into my blog post.

Step 2: Once you have your magical URL, save it in such a way that whatever webservice you’re using can recognize which phone it’s tied to. Maybe you’re saving it along with a username or with a zip code (like with a weather service). In any case, you’ll want to be able to send the right push notifications to the right phones.
When the time comes to send the notification, your webservice will need to send an XML chunk created for your notification (see details here) to the phone-specific URL. Then, the Microsoft Push Notification Service handles your push request and forwards it to the phone, sending a response telling you that it worked (or didn’t work).

I’ve got my gripes with Windows Phone 7, but the push notification implementation ain’t one of them. It’s very straightforward and can be implemented on the phone with very little code and on a server with similar ease. If you’re a newbie mobile developer and this looks complicated, go try to implement push notification on Android or iOS. For all you Android and iOS people out there I would like to say:
Ha.
The next post will walk through the steps to register your app for push notifications. I’ll post a link to it in this post when I get it up.
April 8th, 2011
UPDATE (4/9/2011) : MIX Outsider has been updated to fix some “no network” issues and refine the message creation.

MIX11 Outsider is the MIX11 app that doesn’t care about your schedule. It cares about something more important: the people you want to talk to, meet, or otherwise hang out with at MIX. Using a map of the conference floor and a simple “battleship” mapping metaphor, you can tweet, email or text your position at the conference. Don’t eat alone in awkward silence… instead find that Twitter friend who doesn’t have a clear picture of themselves in their avatar. Don’t spend half your pre-keynote time waving your hands in the air. Just tap where you are on the map and send out a link like this one.
http://mixoutsider.com/H60
And a quick video of the application in action
MIX11 Outsider Windows Phone 7 App Screencast from Matthias Shapiro on Vimeo.
I wish I could introduce this app with a bit more fanfare, but I’ve been waiting since Monday for my app to get through the submission process. I was hopeful that, if I got it in a week before MIX, I would make it in time for the conference. At the moment, that hope fades. As a result, until I can get the app into the Marketplace, it will be available here for download so Windows Phone 7 devs can sideload it onto their phones
MIX Outsider (for sideloading)
(Don’t know how to sideload an app? James Ashley has a great post on sideloading to the emulator or to a device.)
The funniest thing is that the “big idea” in this app isn’t really even the app itself. The app is really just the most complete extension of the original idea.
You see, last year at MIX 10, there was a massive coordination effort among my colleagues to try and sit together during the keynote talks. This led to e-mails, text messages, phone calls, and tweets with hard to understand directions like
“We’re 12 rows from the back in the middle of the far right side as you come in (stage left).”
But my decision to do something about it came when a friend spent 10+ minutes with his lunch plate in hand trying to find our table. I thought, “This is absurd… there must be a better way to find people.”
Unfortunately, my GPS did not work very well inside the conference… which didn’t really matter since (I assume) no one wants to open up a Google Maps or Bing Maps to find people inside a building.
So Jason Alderman and I discussed the problem and thought that it might be fun to do a “Battleship” metaphor for finding people at MIX11, laying the grid on a map of the conference floor. Based on that concept, I wrote a little application that allows user to tap to see where they are and send that information out. It then collects all the messages sent out with the app and shows them on the map with the users’ twitter avatars.
Users can send public messages using Twitter or private messages via text message or e-mail. Private messages are not broadcast and cannot be seen by anyone. They contain only the helpful link to the MIX Outsider reference website (designed by the aforementioned Jason Alderman) without any identifying information.
But my biggest hope is that this application gives people a point of reference so that even people who don’t have a Windows Phone 7 device can see the tweets, reference the website and still find the people they want to meet at MIX11.
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 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.
November 30th, 2010
I’m working on a new project in which I need multiple ListPickers in a ScrollViewer.
The ListPicker is available via the Silverlight Toolkit for Windows Phone 7. If you don’t have it, you should get it. Get the source as well, for reasons that will be clear in one more sentence.
The only problem is that I can’t scroll if I do this because I run the risk of accidentally opening the ListPicker (which should be a tap interaction) when swiping (which is a gesture interaction):
I posted this as a work item on codeplex, so it will probably be fixed in a couple months (sometime in early 2011), but if you’re having a problem with it, do the following:
Open up the source, go to the Microsoft.Phone.Controls.Toolkit project, the ListPicker folder and open the ListPicker.cs file. Go down to the OnManipulationCompleted event and after the line
base.OnManipulationCompleted(e);
add the following conditional for the rest of the code in the method:
if ((Math.Abs(e.TotalManipulation.Translation.X) < 20) && (Math.Abs(e.TotalManipulation.Translation.Y) < 20)){
[Other code]
}
This catches manipulations that are less tap-y and more scroll-y and lets them slide by without opening the ListPicker. If you wanted to be really careful, you could probably change the conditional to 10 or even 5. Most of the taps I checked had pretty small (single digit) manipulation deltas.