-
Async pack for Visual Studio 2012: why it’s useful also for Windows Phone 8 projects
Microsoft has recently released the Async Pack for Visual Studio 2012: it’s a very helpful package and it’s the successor of the old Async CTP that was available for Visual Studio 2010. Its purpose is to add support to the new asynchronous pattern introduced in C# 5 (based on the async and await keywords) also to “old” technologies that, since are still based on C# 4, couldn’t make use of it. Some example of these technologies are Silverlight or Windows Phone 7: basically, we’re talking about all the stuff that relies on .NET Framework 4, since the new .NET Framework 4.5 (that has been shipped with Windows 8) is based on C# 5.
Installing it is very easy: you simply have to use NuGet, by right clicking on the project and choosing Manage Nuget packages. First you have to change the filter that is applied by default: since the async package is still in beta, you have to change the default filter at the top of the window from Stable only to Include prerelease. After that, you can search for the keyword Bcl.Async and install the Async for .NET Framework 4, Silverlight 4 and 5 and Windows Phone 7.5 package. Automatically NuGet will resolve all the references and it will install also the Microsoft.Bcl package for you.
But why this package should be interesting also for developing Windows Phone 8 applications? Windows Phone 8 is a new technology, based on a subset of the Windows Runtime, so the async and await support is built in.
The answer is that, due to maintain compatibility with the old platform (that didn’t have async and await support), some old classes doesn’t offer a way to use them with the new pattern. Take the WebClient class for example, which is very popular to make network operations (like downloading a file). Unlike the other WinRT APIs (like the ones to work with storage or sensors), it still relies on the old callback pattern: you register for an event handler that is invoked when the operation is finished, you launch the network operation and, inside the event handler (that is the callback), you manage all the operations that should be done with the result (like storing the file in the local storage or displaying it).
Here is an example:
WebClient client = new WebClient(); client.DownloadStringCompleted += (obj, args) => { if (args.Error == null) { MessageBox.Show(args.Result); } }; client.DownloadStringAsync(new Uri("http://wp.qmatteoq.com"));
We download the HTML content of the page of this blog and, when the operation is completed, if no errors have occurred, we display it using a MessageBox.
This approach is not so easy to write and understand like with the async and await keywords, basically because the code we wrote is not sequential: the code that is written after the DownloadStringAsync method is executed right after we have issued the network operation but, at a certain point, the execution will stop and the application will start running through the DownloadStringCompleted event handler.
Plus, probably we’ll have some sort of “spaghetti” code: we’re using the callback approach to manage network operations but, for example, we’ll have to use the async and await pattern if we want to use the new storage APIs to save the HTML in a file in the local storage.
Here comes the Async pack: other than adding support to async and await (that is not needed, since Windows Runtime for Windows Phone already supports it) it adds a bunch of extension methods, that add to many “old style” classes new methods to work with Task objects and the new async pattern.
Some examples of classes that can take benefit of these extension methods are WebClient, HttpWebRequest and Stream. This way we change the previous example to use the new approach:
private async void OnDownloadAsync(object sender, RoutedEventArgs e) { WebClient client = new WebClient(); string result = await client.DownloadStringTaskAsync("http://wp.qmatteoq.com"); MessageBox.Show(result); }
Or, for example, we can start a network request using the HttpWebRequest class in a much simpler way:
private async void OnDownloadAsync(object sender, RoutedEventArgs e) { HttpWebRequest request = HttpWebRequest.CreateHttp("http://wp.qmatteoq.com"); HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse; MessageBox.Show(webResponse.StatusDescription); }
Or, in the end, we can use the Stream extension methods to get the content of the previous HttpWebRequest example:
private async void OnDownloadAsync(object sender, RoutedEventArgs e) { HttpWebRequest request = HttpWebRequest.CreateHttp("http://wp.qmatteoq.com"); HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse; Stream responseStream = webResponse.GetResponseStream(); using (StreamReader reader=new StreamReader(responseStream)) { string content = await reader.ReadToEndAsync(); MessageBox.Show(content); } }
For all of the reasons I’ve explained in this post, I strongly suggest you to add the Async targeting pack to every Windows Phone 8 project you’re going to develop. Have fun!
in
-
Unit testing in Windows Phone 8 – The basics
Unit testing in Windows Phone has never been really supported by Microsoft: the only semi-official way to do unit tests in Windows Phone 7 is using an adaptation of the Silverlight Unit Test Framework made by Jeff Wilcox. This library is able to render a Windows Phone application, that is capable of running the unit tests included in the project. The downside of this approach is that you have to use a dedicated Windows Phone app to run the tests, instead of using a built-in tool like Resharper. The biggest advantage, instead, is that unit tests are executed into a real environment, so it’s easy to write integration tests that makes use, for example, of the storage or of a real Internet connection.
Since unit tests are an important part of every project, especially the most complex ones, Microsoft has now adapted the Silverlight Unit Test Framework to Windows Phone 8, dropping the Silverlight part of the name and adding it as a part of the new Windows Phone 8 toolkit. Let’s see how to use it, how to run simple tests and, in the next post, how to face some more complicated scenarios (like mocking and dealing with async methods).
Preparing the environment
As I anticipated you, the tests are executed in a separate Windows Phone application: for this reason, you’ll have to add another Windows Phone project to your solution. Once you’ve done it, you can install the Windows Phone toolkit from NuGet and the unit testing framework: now we are ready to set up the application.
The first thing is to open the code behind file of the MainPage, that is MainPage.xaml.cs and add in the constructor, right below the InitializeComponent() method, the following code:
public MainPage() { InitializeComponent(); this.Content = UnitTestSystem.CreateTestPage(); }
This way when the application is launched the unit test runner is displayed: you can see it by yourself by launching the application in the emulator. The first screen will ask you if you want to use tags or not (we’ll see later which is their purpose): if you press the Play button in the application bar you’ll be redirected to the main window of the unit test runner, even if you won’t see no tests at the moment since we haven’t added one yet.
The next step is to create one or more classes that will hold our tests: in a real scenario we would create a unit test class for every real class that we need to test. For this example, we’re simply going to create a single class: we can place it everywhere we want but, to keep the structure of the project organized, we will add a new folder **called **UnitTests and we will add the new class there: in my example, I’ve called it SimpleUnitTest. To add it, simply right click on the new folder, choose Add – New item and add a Class file.
The first thing to do is to add the namespace Microsoft.VisualStudio.TestTools.UnitTesting at the top of your class: this way we can access to the attributes and classes needed to test our code. The second step is to mark the entire class with the attribute [TestClass]: this way we’ll tell to the application that this class contains unit tests that should be processed and executed.
Now let’s add a simple unit test (to be honest, it’s more stupid than simple ): the purpose is just to make you comfortable with the basics.
[TestClass] public class SimpleUnitTest { [TestMethod] public void SimpleTest() { int a = 1; int b = 2; int c = a + b; Assert.IsTrue(c == 3); } }
Notice the [TestMethod] attribute that we used to mark the SimpleTest method: with this attribute we’re telling to the application that this method actually contains a unit test that should be executed. The test is really stupid: we sum two numbers and we check that the sum is correct, using the Assert class, which contains different methods that can be used to check the results of our test. In this case, we need to test a boolean condition, so we can use the IsTrue method. Other examples of methods are IsNotNull (to check that a object actually has a value) or IsInstanceOfType (to check if the object’s type is the one we expect).
Run the application and launch the tests: this time you’ll see the test run and you’ll be prompted with the results. Obviously, in this case, the test will pass, since 1+2 = 3.
Let’s test a fail case: change the condition that is tested in a way that is not true anymore, like in the example:
[TestClass] public class SimpleUnitTest { [TestMethod] public void SimpleTest() { int a = 1; int b = 2; int c = a + b; Assert.IsTrue(c == 4); } }
Run again the application: this time you’ll see that test is failed. Clicking on the test will let you see the details and why it failed: in this case, you’ll clearly understand that the Assert.IsTrue operation is failed.
Using tags
Sometimes you don’t want to run all the tests that are available in your classes, but just a subsets: this is what tags are for. To use them, you have to add to your test class the namespace Microsoft.Phone.Testing, which will allow you to decorate a test method with the Tag attribute, followed by a keyword. To see this feature in action, let’s add another test method: we’ll set the Tag attribute just for one of them.
[TestClass] public class SimpleUnitTest { [Tag("SimpleTests")] [TestMethod] public void SimpleTest() { int a = 1; int b = 2; int c = a + b; Assert.IsTrue(c == 3); } [TestMethod] public void SimpleTest2() { int a = 3; int b = 1; int c = a + b; Assert.IsTrue(c == 4); } }
Now run again the application and this time, in the first screen, trigger the Use tags switch to On. You will be prompted to specify a keyword that will be used by the application to determine which test run: insert the keyword SimpleTests (which is the tag we’ve set for the test method called SimpleTest) and press the Play button. You’ll see that, despite the fact you have two test methods in your class, only the first one will be executed.
Tagging is a great way to group unit tests so that, if you need to test just a specific class or feature, you don’t have to go through all the unit tests.
Debugging
If a test fails and you don’t know, it’s really easy to debug it: since, when you launch the unit test runner from Visual Studio, you are launching a standard Windows Phone application, you can simply set breakpoints in your test methods: they will be hit when the tests are executed and you can step into the code to see what’s going on.
Asynchronous tests, mocking and a lot more
In the next post we’ll cover some advanced but quite common scenarios, like mocking and asynchronous method testing. Keep up the good work meanwhile!
in
-
Azure Mobile Services for Windows Phone 8
During the BUILD conference, right after the announcement of the public release of the Windows Phone 8 SDK, Microsoft has also announced, as expected, that Azure Mobile Services, that we’ve learned to use in the previous posts, are now compatible with Windows Phone 8.
Do you remember the tricky procedure that we had to implement in this post to manually interact with the server? If you’re going to develop an application for Windows Phone 8 you can forget it, since now the same great SDK we used to develop a Windows Store app is now available also for mobile. This means that we can use the same exact APIs and classes we’ve seen in this post, without having to make HTTP requests to the server and manually parsing the JSON response.
The approach is exact the same: create an instance of the MobileServiceClient class (passing your service’s address and the secret key) and start doing operations using the available methods.
The only bad news? If your application is targeting Windows Phone 7, you still have to go with the manual approach, since the new SDK is based on WinRT and it’s compatible just with Windows Phone 8.
You can download the SDK from the following link: https://go.microsoft.com/fwLink/?LinkID=268375&clcid=0x409
in
subscribe via RSS