8 days of Windows Phone 8 | Day 5: .net 4.5 & C# 5.0

 8 days of windows phone 8

Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 5th day of this series we’ll talk about the new features in the .net framework 4.5 and the C# 5.0 language that can help you build great Windows Phone apps. The main features we’ll handle in this post are the async and await keywords and the DataContractJsonSerializer

  • Day 1: SDK Overview
  • Day 2: Live tiles and Lock screen
  • Day 3: Emulator & Simulation dashboard  
  • Day 4: New screen resolutions
  • Day 5: .net 4.5 & C# 5.0
  • Day 6: Speech
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases



    .net framework 4.5 & C# 5.0

    With Windows 8 we’re also upgrading our applictions from silverlight to the .net 4.5 framework and the C# 5.0 language. This does give Windows Phone developers some new features that are not actually new features in the SDK but are really useful for you as a developer of mobile applications. One of these new features are the async and await keywords. This makes building asynchronous applications so much easier and your UI more responsive. The other thing i want to elaborate on today is the use of the DataContractJsonSerializer. This class helps you to serialize or deserialize json strings to or from objects. Really useful when you’re connecting to services on the web.

    Unfortunately not all APIs in the SDK are rewritten to make use of these async and await keywords so you can’t use them to do calls from the web. WebClient and HttpWebRequest do not make use of these features so hopefully sometime we can use HttpClient like we can in Windows 8.

    My ideal situation in creating a demo for this post was combining the async and await keywords together with the json serializer. so if we can’t use it when getting the file from the web lets just use a local file instead. local file access APIs are written using the Task, async and await keywords. so lets get started and build a very very basic To Do list app to check the

    Create a new Windows Phone 8 project and add a ToDo class to store our things we need to so. It’s just a property bag with a Title, Date and some text. To save this file as a json file later we’ll add some attributes so the DataContractJsonSerializer knows how this object can be serialized to a json file. To do this add the [DataContract] attribute to the ToDo class and add the [DataMember] attribute to each property you want to be serialized to json. By default the Serializer will give the properties in the json file the same name as the properties in your class. If you want to have different names you can change this in the DataMember attribute as shown for the Content property which we changed to the word “Text”

       1: [DataContract]

       2: public class ToDo

       3: {   

       4:     [DataMember]

       5:     public string Title { get; set; }


       7:     [DataMember]

       8:     public DateTime Date { get; set; }


      10:     [DataMember(Name="Text")]

      11:     public string Content { get; set; }

      12: }

    So we’ve created a simple container for our objects lets create a business service called ToDoService to save a list of To Do items and get them back again from a file stored in the Local Folder. Local folder is the root of your applications data store which was called the Isolated storage in Windows Phone 7.

    First we’ll add a method to our ToDoService to save a list of To Do items.

  •    1: public async Task<string> SaveToDos()

       2: {

       3:     List<ToDo> todos = new List<ToDo>();

       4:     todos.Add(new ToDo(){Title="todo 1", Date = DateTime.Now, Content="finish this series of blogposts"});

       5:     todos.Add(new ToDo(){Title="todo 2", Date = DateTime.Now, Content="Pick up milk from the store"});

       6:     todos.Add(new ToDo(){Title="todo 3", Date = DateTime.Now, Content="Wash my car"});


       8:     var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;


      10:     DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<ToDo>));

      11:     MemoryStream ms = new MemoryStream();

      12:     dcjs.WriteObject(ms,todos);

      13:     string json = Encoding.UTF8.GetString(ms.ToArray(),0,(int)ms.Length);



      16:     StorageFile todoFile = await localFolder.CreateFileAsync("todos.json",CreationCollisionOption.ReplaceExisting);

      17:     using (var f = await todoFile.OpenStreamForWriteAsync())

      18:     {

      19:         await f.WriteAsync(ms.ToArray(),0,(int)ms.Length);

      20:         f.Close();

      21:     }


      23:     return json;

      24: }

    Please note the async keyword before the return type of this method. by adding this, this method can be called asynchronous and it will always return a Task containing your return type. In the method we first add a few ToDo items to a list. after that we create a new DataContractJsonSerializer and in the constructor we add the type of object it should serialize. We then use the DataContractJsonSerializer to serialize our list of ToDo items to a json string which will be returned at the end of the method.

    When we have this json string we’ll create a new file in the local folder by calling the CreateFileAsync method. please note the await keyword before this method which means that the code below this line should be waiting until this asynchronous call is finished. When we have the local file we’ll just write the json string to this file and close the stream.

    So now the ToDo items are saved in the local file, lets read them back and show them on the screen. We’ll add a new method to our ToDoService called GetToDos() which will read the json file and will deserialize it back to a list of ToDo items.

       1: public async Task<List<ToDo>> GetToDos()

       2: {

       3:     var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

       4:     StorageFile todoFile = await localFolder.GetFileAsync("todos.json");


       6:     DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<ToDo>));

       7:     var stream = await todoFile.OpenStreamForReadAsync();

       8:     var todos = dcjs.ReadObject(stream) as List<ToDo>;


      10:     return todos;


      12: }

    We’ll start again by getting a reference to the local folder and the json file in the local folder. When we have this StorageFile object we can now create a new DataContractJsonSerializer again. Now we open a stream from our StorageFile and pass it to the DataContractJsonSerializer to change it back to a List of ToDo items. We’re all done.

    To finish up the demo application we’ll add a textbox to the mainpage where we can display our json string and we’ll also add an ItemsControl to display the To Do items.

       1: <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

       2:     <ScrollViewer>

       3:         <StackPanel>

       4:             <TextBlock x:Name="JsonText" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

       5:             <ItemsControl x:Name="TodoList" ItemTemplate="{StaticResource TodoItemTemplate}" Margin="0,12,0,0"></ItemsControl>

       6:         </StackPanel>

       7:     </ScrollViewer>

       8: </StackPanel>

    In our code behind we’ll hook everything up to write and read the data and show it on the page.

       1: public async void SaveAndGetTodos()

       2: {

       3:     ToDoService ts = new ToDoService();

       4:     string json = await ts.SaveToDos();


       6:     List<ToDo> todos = await ts.GetToDos();


       8:     JsonText.Text = json;

       9:     TodoList.ItemsSource = todos;

      10: }

    If we now run our application we’ll see the json string that is created and also the list of To Do items in the itemscontrol.


    you can download the demo project here: http://sdrv.ms/QSJ2yx

    Hopefully you enjoyed reading this post or learned some usefull features of the async and await keywords and the DataContractJsonSerializer. More tomorrow on one of the coolest new things in the SDK: the Speech APIs

    Geert van der Cruijsen

    Share on Facebook
    Kick It on DotNetKicks.com
    Shout it
    Post on Twitter

    Comments are closed.