LIke most of my applications, I used to save all my application settings in the IsolatedStorageSettings.ApplicationSettings. It seems like a logical good choice. In my last application, I added a Background Agent to my project. When I was looking for best practices on how to exchange settings between the background agent and my application, I came across with this text from the MSDN library:
For Periodic and Resource-intensive Agents: Use LINQ 2 SQL or a file in isolated storage that is guarded with a Mutex. For one-direction communication where the foreground app writes and the agent only reads, we recommend using an isolated storage file with a Mutex. We recommend that you do not use IsolatedStorageSettings to communicate between processes because it is possible for the data to become corrupt.
After, I found someone who implemented a solution that uses a Mutex. While the solution is good, the only problem is that his personal settings are mixed with the IsolatedStorage operations.
To help the reuse of the solution in different projects, I created a IsolatedStorageHelper class. Also, instead of relying on the XmlSerializer in order to save an object, I based my solution using the powerful library of Json.NET.
Usage
The IsolatedStorageHelper has three methods:
WriteObjectToFileUsingJson
ReadObjectFromFileUsingJson
IsFileExists
Here is the example that uses all the methods:
Settings mySettings = new Settings();
IsolatedStorageHelper.WriteObjectToFileUsingJson("Settings.txt", mySettings, "MyMutexName");
if (IsolatedStorageHelper.IsFileExist(SettingsFileName))
{
Settings = IsolatedStorageHelper.ReadObjectFromFileUsingJson<Settings>("Settings.txt", "MyMutexName");
}
To use the IsolatedStorageHelper in your project:
1- Add the IsolatedStorageHelper.cs file into your project.
2- Add the Nuget package Json.net.
If your project does not have a background agent, you can still use my utility class, you can omit the mutexName parameter of the WriteObjectoToFileUsingJson and ReadObjectFromFileUsingJson.
For the past few months, I have been working on my first Windows Store app for Windows 8 called Canadian Developer Connection. Since yesterday, my application is now available in the Windows Store. The Canadian Developer Connection includes all the articles, videos-on demand, events, resources and more from the Microsoft Canadian evangelist team. Even if you are not a Canadian, the application contains useful information for any developers interested in Microsoft technologies.
Here are some screenshots:
The application allows you to stream a video to any Play To devices like an Xbox 360.
At the same time, I updated the Windows Phone version to includes the videos on-demand series and the developer events.
Don’t miss anything from the Canadian Developer Connection and download both versions!
There is a lot of examples in the Windows Phone community about creating a button with an image only. We can achieve this result with the following code:
<Button>
<Image Source="MyImage.png"/>
</Button>
The problem with the previous code is the impossibility to set a different image when the button is disabled or pressed.
Solution
I created a ButtonImage class to set a different image for the disabled and the pressed states.
If you are not interested on the code of the ButtonImage class, you can skip this section and go directly to the Usage section.
There is nothing fancy here, it is a button that has an image has content.
C# code
using System;
using System.Windows;
using System.Windows.Media.Imaging;
namespace DotNetApp
{
public partial class ButtonImage
{
#region Fields
public new static readonly DependencyProperty IsEnabledProperty = DependencyProperty.Register("IsEnabled", typeof (bool), typeof (ButtonImage), null);
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof (string), typeof (ButtonImage), null);
public static readonly DependencyProperty ImagePressedSourceProperty = DependencyProperty.Register("ImagePressedSource", typeof (string), typeof (ButtonImage), null);
public static readonly DependencyProperty ImageDisabledSourceProperty = DependencyProperty.Register("ImageDisabledSource", typeof (string), typeof (ButtonImage), null);
private BitmapImage _image;
private BitmapImage _imagePressed;
private BitmapImage _imageDisabled;
private bool _isPressed;
#endregion
#region Constructor
public ButtonImage()
{
InitializeComponent();
}
#endregion
#region Properties
public new bool IsEnabled
{
get { return (bool)GetValue(IsEnabledProperty); }
set
{
SetValue(IsEnabledProperty, value);
SetImageFromState();
}
}
public string ImageSource
{
get { return (string) GetValue(ImageSourceProperty); }
set
{
SetValue(ImageSourceProperty, value);
_image = SetImage(value);
SetImageFromState();
}
}
public string ImagePressedSource
{
get { return (string) GetValue(ImagePressedSourceProperty); }
set
{
SetValue(ImagePressedSourceProperty, value);
_imagePressed = SetImage(value);
SetImageFromState();
}
}
public string ImageDisabledSource
{
get { return (string) GetValue(ImageDisabledSourceProperty); }
set
{
SetValue(ImageDisabledSourceProperty, value);
_imageDisabled = SetImage(value);
SetImageFromState();
}
}
#endregion
#region Event Handlers
private void ButtonIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
SetImageFromState();
}
private void ButtonMouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
_isPressed = true;
SetImageFromState();
}
private void ButtonMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
_isPressed = false;
SetImageFromState();
}
#endregion
#region Private Methods
private static BitmapImage SetImage(string imageSource)
{
BitmapImage bitmapImage = null;
if (!string.IsNullOrEmpty(imageSource))
{
bitmapImage = new BitmapImage(new Uri(imageSource, UriKind.RelativeOrAbsolute));
}
return bitmapImage;
}
private void SetImageFromState()
{
if (!IsEnabled)
{
image.Source = _imageDisabled;
}
else if (_isPressed)
{
image.Source = _imagePressed;
}
else
{
image.Source = _image;
}
}
#endregion
}
}
Once again, there is nothing scientific here. I load the images and based on the event handlers (ButtonIsEnabledChanged, ButtonMouseEnter and ButtonMouseLeave), I set the right image.
Usage
The button has an image for each state:
Normal
Pressed
Disabled
To use the ButtonImage control in your app, just follow those steps:
Add the files ButtonImage.xaml and ButtonImage.xml.cs to your project.
Add the normal image, the pressed image and the disabled image to your project. If your button does not need a pressed image or a disabled image, you don’t have to specify one.
All the properties are important. The ImageSource, ImageDisabledSource, ImagePressedSource are the actual images that you want for each state. The Height and the Width need to be the same as the specified images.
The last piece of the puzzle is the Style property set to "{StaticResource ButtonImageStyle}". If you do not set this property, there will be an unwanted transparent area around the image and the image will be smaller. Your last step is to define the ButtonImageStyle into your project. You can add it into your page or in the App resources section. The code to copy is:
In the summer 2012, the WinSource website held a contest among the Windows Phone developers to create an official application for their website.
I was a participant in the contest and I can tell you that it was a really interesting and challenging contest. My application finished in third position.
You can download the application from the winner at here.
Important notice
Before I decided to put the full source code of my complete application. I asked the owners of the WinSource from the Neverstill company if I can publish the source code of my application. They accepted my idea, because it is a great way to help the Windows Phone community.
In the current form, the application has enough features that it can be an alternate WinSource application. The only restriction is a user cannot publish or use the WinSource’s logo, the assets or the content from the WinSource. NOTE, this project is licensed under a slightly modified MIT license which reflects the above restriction.
The purpose of having this open project is to help the community creating a professional news reader for any other websites that give the permissions. It also shows different concepts which can be applied in different type of applications.
The application
My application contains the following features:
The metro design is used throughout the app, while the main page is showcased using the panorama design.
Fast navigation between pages.
Articles classified by date.
Play YouTube videos.
A description of each team member, including a display of the author name & image on each author’s page. Also included is the option to send the author an email.
Article links can be shared on Twitter, Windows Live, Facebook, or by email.
The application bar contains shortcuts to the Facebook page and the Twitter page of the website.
The About page provides a way to send an email and to write a review of the app.
Option to automatically refresh articles when the application launches.
The following list contains advanced features:
Offline mode. Articles can be read even when no internet connection is available.
Unlimited space for saving articles, which can then be accessed using the Saved Articles page.
Articles can be periodically downloaded(every ~4 hours) in the background, even when the app is not running. This feature does not require server support.
Toast notification will display the number of new articles available, and a badge count in the application live tile will also display this number.
The back of the live tile will display the latest article title.
The application uses the Pivot control for the team members:
And a standard page for an article:
Open source libraries
I used three open source libraries that are well known in the developer community:
GalaSoft MvvmLight (http://mvvmlight.codeplex.com/): Used to architecture a modular application and to easily add future features.
I use the Model View-Model View (MVVM) pattern in my solution. The solution is separated in five assemblies:
DotNetApp.Toolkit: It includes utility classes that can be reused in any Windows Phone projects. There is also my Request class that helps calling web resources.
WinSource: This is the main project that includes the views, the data service, the view models and many more things.
WinSource.Agent: It is the project that includes the schedule background service which permits to periodically download articles in the background.
WinSource.Client: It contains all the web requests.
WinSource.Model: It contains only the data structure.
You won’t find a lot of comment in my code, but I’m an heavy user on code convention and I tend use write small methods so the code should be self-explanatory.
How to build the application
All the required files are built-in in the solution. Make sure that the selected project is “WinSource” then press F5 to launch the application.
The application has been tested with the Windows Phone SDK 7.1.
Future of the application
The application in its current form contains more features then some published news applications in the Windows Phone Store. That’s been said, the application is in a release state. As all software, it is always possible to polish and add features. You are welcome to add and suggest features.
What can you do with the source files of the application?
Simple answer: create your own news application! The source files provided are the best starting point to get your news application ready. The mechanism is ready and your tasks are:
Replace the assets in the Assets folder of the WinSource assembly.
Modify the classes in the WinSource.Client assembly in order to fetch the article descriptions and videos from your news source.
Remove or add sections in the Panorama.
Learning
Also, if you read the code you can learn a lot about the Windows Phone SDK and about some best practices. The application is more complete than the ones in the MSDN samples.
Conclusion
You can contribute directly to the project on the Nokia developer website or you can download the source code.
Creating animations in your Windows Phone application is easier than you think.
I created a simple application that shows how to create a static animation and a dynamic animation. Both animations fill the following red rectangle from the bottom to the top.
Static animation
An animation uses a Storyboard object. It is usually created in the XAML file, because it is easier this way. Here is the XAML code:
The DoubleAnimation is the simplest animation available, it animates a property that uses a double value. The above double animation is defined like this: Animate the Height property of the rectangleRed object from the current Height value to 700 in 5 seconds.
To start the animation, you need to call the Beginmethod on the animation:
using System.Windows.Navigation;
namespace SimpleAnimationApp
{
public partial class StaticAnimationPage
{
public StaticAnimationPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
staticAnimation.Begin();
}
}
}
It is not used in the sample app, but if you want to stop an animation at any time, you just have to call the Stop method on the animation.
Dynamic animation
For the dynamic animation, let’s pretend that the properties Duration and To are specified in the code behind. We have the similar XAML code:
There is one addition of the x:Name=”doubleAnimation” which will help to control the animation in the code behind:
using System;
using System.Windows.Navigation;
namespace SimpleAnimationApp
{
public partial class DynamicAnimationPage
{
public DynamicAnimationPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
doubleAnimation.Duration = new TimeSpan(0, 0, 0, 10);
doubleAnimation.To = 350;
dynamicAnimation.Begin();
}
}
}
Before starting the animation, I set the Duration to 5 seconds and the To to 350 which is half the size of the blue rectangle.
It is not complicated to create an animation. Those were simple animations, but if you want to create more complex animations and even combine animations, you can find more information on the web.
For developers, the biggest news for Windows Phone 8 is that it shares a core with Windows 8. It means that your code has more chances than ever before to be compatible on both platforms.
One of the easier components and surely the most used in applications is the File IO component. In this post, I’ll also cover the Windows Phone 7 code compatibility.
In Windows Phone 7
To write a file, you use the IsolatedStorageFile:
private void WriteFile(string fileName, string content)
{
using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile(fileName))
{
using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
{
streamWriter.Write(content);
}
}
}
}
To read a file:
private string ReadFile(string fileName)
{
string text;
using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.OpenFile(fileName, FileMode.Open))
{
using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
{
text = streamReader.ReadToEnd();
}
}
}
return text;
}
In Windows Phone 8
To write a file, you use the Windows.Storage component. The file and folder objects are respectively IStorageFile and IStorageFolder. The usage of the await and async keywords come in.
await WriteFile("Dummy.txt", "I love the Windows Phone");
string text = await ReadFile("Dummy.txt");
You can see that the code between Windows Phone 7 and Windows Phone 8 is quite different.
Compatibility
As we know already, Microsoft announced that the Windows Phone 7 applications will run on Windows Phone 8. This is great news. What is even better is that your Windows Phone 7 code that uses the IsolatedStorage will compile without any changes in Windows Phone 8. You can take the Windows Phone 7 code above and it will work.
You might be wondering if the internal folder structure is different between WP7 and WP8… The difference is minor.
In WP7, if you create a file at the root, the file will point to:
The difference is the IsolatedStore folder added in WP7. It means that if you have old WP7 code that you would like to use with new WP8 code, you just have to get the IsolatedStore folder:
In the end, you can mix both WP7 and WP8 code in your next Windows Phone 8 application. However, I would encourage you to use only the Windows Phone 8 version, as it will then be easier for you to use the same code in Windows 8.
Here is a complete step-by-step guide to create a WCF backup service for your Windows Phone applications.
You can implement your own hosting service with a cheap hosting server like GoDaddy. You can find deal at $5/month. Personally, I find it more professional saving your application data to a private server or in a cloud solution instead of relaying on SkyDrive.
To accomplish this, two things are required: A- Implementing the service on your server. B- Implementing the client code to send your data.
Alternatively, you can download the complete solution at the end of the article.
A) Server side
1- Let’s start with the hardest part. After you find a hosting server that supports the framework .NET 4.0, you create the WCF Service Application:
2- Rename the file IService1.cs to IFileUploader.cs
3- Replace the content of the IFileUploader.cs with:
using System.Runtime.Serialization;
using System.ServiceModel;
namespace FileUploadService
{
[ServiceContract]
public interface IFileUploader
{
// Returns null when there is no error, otherwise it is the exception message.
[OperationContract]
string Upload(UploadFile uploadFile);
}
[DataContract]
public class UploadFile
{
// Don't forget to set the variable FileUploadDirectoryWithReadWritePermission in your Web.config and set read/write permission in your web hosting.
// RelativeDirectory should be in the form as /Path1/Path2/ or null for the root directory.
[DataMember]
public string RelativeDirectory { get; set; }
[DataMember]
public string FileName { get; set; }
[DataMember]
public byte[] Content { get; set; }
}
}
This interface contains only the Upload method. The Upload needs a UploadFile which contains only 3 properties: RelativeDirectory, FileName and Content.
4- Rename the file Service1.svc to FileUploader.svc.
5- Replace the content of FileUploader.svc with:
using System;
using System.Configuration;
using System.IO;
using System.Web.Hosting;
namespace FileUploadService
{
public class FileUploader : IFileUploader
{
#region IFileUploader Members
public string Upload(UploadFile uploadFile)
{
string message = null;
try
{
string path = HostingEnvironment.MapPath(string.Format("~/{0}",ConfigurationManager.AppSettings["FileUploadDirectoryWithReadWritePermission"]));
if (path != null)
{
if (uploadFile.RelativeDirectory != null && uploadFile.RelativeDirectory.StartsWith("/"))
{
path = string.Concat(path, uploadFile.RelativeDirectory);
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!string.IsNullOrEmpty(uploadFile.FileName))
{
using (FileStream fileStream = File.Open(Path.Combine(path, uploadFile.FileName), FileMode.Create))
{
using (var binaryWriter = new BinaryWriter(fileStream))
{
binaryWriter.Write(uploadFile.Content);
}
}
}
}
}
catch (Exception exception)
{
message = exception.Message;
}
return message;
}
#endregion
}
}
– The section about the length of the service parameters: You don’t need to understand everything here. It just works as is. If you are curious, I invite you to read the documentation on MSDN.
7- The service is ready to be published. Right-click on the FileUploadService project and choose Publish. Depending on your web hosting service, you need to set the info.
For GoDaddy:
– Use the FTP method.
– Set the target location. For me, I used ftp://ftp.ultimatepokermanager.com/upm/ServerTest
– Set the credentials
8- The trickiest part is to configure the application settings for the WCF service in the hosting service. In GoDaddy, it’s in the IIS Management in the Tools section. You need to check Anonymous Access and Set Application Root.
The upmservertest points to http://www.ultimatepokermanager.com/upm/servertest
8- To check if your service is running, open your browser and put the address of the web service. With my web service, the address is:
In the sample, I generated a GUID for the directory name. Also, the uploaded files are public as long as the user (or the application) knows about the directory name and the file name. If you want to add a layer of privacy, you just have to implement a DownloadFile method into your service. It should not be difficult if you read the code of the Upload method.
I guarantee you that you’ll be happy to see when your web service is working!
In the past year and a half, I have read a lot of Windows Phone books. The first book I read was the excellent 101 Windows Phone 7 apps. At that time, I was recommended that book, but ever since Microsoft released the Mango update, 101 is a bit out of date.
At the end of 2011, I read Essential Windows Phone 7.5 by Shawn Wildermuth. I recommend this book for someone who has never owned a Windows Phone and who wants to start programming for the Windows Phone. It is an excellent book for beginners, as the author spends time about on basic Windows Phone concepts.
Now to my review of the latest Windows Phone book I have read: Windows Phone 7.5 Unleashed by Daniel Vaughan.
This book is huge with 1120 pages, and all of them are worth it. Here are some of the things that I like about the book:
Most of the code samples are done with the MVVM pattern. Nowadays, this pattern is the most popular one used when creating Windows Phone applications. The author even shares his known Calcium SDK that includes the MVVM philosophy. For a beginner who wants to start Windows Phone programming, starting off with the best pattern is a great idea, and this book will help you do that.
There is a lot of free code given. There are a lot of utility classes that can be used in many types of Windows Phone applications. Honestly, the book is worth buying for the free code alone, and it will save you a lot of time.
If you are new to use the SQL Compact Server database, this book will help you to learn the technology; the author has a large helpful section on this topic.
The author introduced the usage of Reactive Extensions. This technology is not for beginners, but I’m pretty sure it will intrigue you, as it did me. The author presents the benefits of Reactive Extensions. The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. You can find the rest of the definition at the official website.
The author knows the platform well and describes many useful hints and caveats in Windows Phone programming.
In conclusion, this excellent book is one that I recommend right now if you want to dive into Windows Phone programming or to learn more about the recent features added with Mango.
If you are developing an application for your company with a brand name or if you are developing the next Angry Bird game with a cool new name, this post is not for you.
However, if you are concocting a generic application like a calculator, a converter, a task manager, you might want continuing to read this post.
Last year, I released the Ultimate Poker Manager along with the ad based version Ultimate Poker Manager Free. Those apps are a poker timer, a hand reference helper and a statistic manager that can produce a whole website with game results and a leaderboard. After a couple of months, I realized that my apps were not gaining traction as much as simple apps like Poker Timer or Poker Hands even if my app was more appealing.
With these results, I tried to rebrand the app for Poker Hands & Timer and I added it to the marketplace (only as a free app). I kept the old Ultimate Poker Manager Free in order to be able update the users that installed my app.
After one and half year, I can tell you that the Poker Hands & Timer has been downloaded twice as much as the Ultimate Poker Manager Free. My download count is in thousands.
I do believe that the marketplace search algorithm put a lot of weight on application name first. So in the end, don’t look for fancy names, keep it simple!
This post is not based on exact science but on my experience. If you agree or not, please feel free to comment.
This week, Microsoft presented what I believe are the best announcements in the last 10 years: the coming release of the gorgeous Surface and the next Windows Phone 8 OS.
I was ready to blog about the new SDK of Windows Phone 8, but we have to wait until the SDK is released. However, we should be pleased that the core of Windows Phone 8 and Windows 8 will be the same.
Back to the blog post now!
Microsoft is serious about Windows 8. They ran a lot of interesting events for the developers. I must admit that living in a big city helps. Recently, I participated in the App Excellence Lab for Windows 8 where I was given early access to the Windows 8 Dashboard. I presented my port of my Windows Phone Canadian Developer Connection app to Windows 8. In a future blog post, I’ll talk about my experience porting an application from Windows Phone 7 to Windows 8.
For developers that submitted Windows Phone 7 applications, you will have dealt with the App Hub many times and you have probably seen some hiccups. Fortunately, the Windows Phone team gave the developers good news about the upcoming upgrade of the App Hub.
Right now, the Windows 8 Dashboard (that’s the current name) does not share the same system as the App Hub. In a couple of years, they might share a dashboard, but for now I’ll present some differences.
Dashboard
Submit an app
All the steps are well defined and you get the approximate time for each step.
Explore store trends
This is what I consider the best tool of the Windows 8 Dashboard. It gives you the ability to analyze what people install on Windows 8. I hope this feature will soon come to the App Hub.
Financial summary
This is the place where you find out if you’ll be millionaire one day.
Profile Account
I skipped the section Renewal, there was nothing interesting. The Profile Account is pretty normal except that you can change the Publisher name.
Microsoft Support
This is the second major feature of the Windows 8 Dashboard. Recently, I had a question to ask the certification team and I visited the support page. I was expecting to fill in a form and get an answer one or two days later like it is in the App Hub, but I was totally surprised that the Dashboard offers you the possibility of chatting with a support representative during the week days. I picked this option and 2 seconds later, I was chatting. I hope this wait time will stay the same!
Now, go back to your code and port all your beautiful Windows Phone apps to Windows 8!