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

     

     day5

    .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; }

       6:  

       7:     [DataMember]

       8:     public DateTime Date { get; set; }

       9:  

      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"});

       7:  

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

       9:  

      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);

      14:  

      15:  

      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:     }

      22:  

      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");

       5:  

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

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

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

       9:  

      10:     return todos;

      11:  

      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();

       5:  

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

       7:  

       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.

    day5demo

    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

    8 days of Windows Phone 8 | Day 4: New Screen Resolutions

     8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 4th day of this series we’ll dive into the new screen resolutions of Windows Phone 8 and what you should do to support these as a Windows Phone developer.

  • 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

     

    day4

    Available Screen resolutions

    3 screen resolutions are supported in Windows Phone 8: WVGA, WXGA and 720p.

      Resolution Ratio
    WVGA 480*800 15:9
    WXGA 768*1280 15:9
    720P 720*1280 16:9

    The most important thing to notice is there are 2 different screen ratio’s. 15:9 and 16:9. If you look at the picture below that is a representation of the 3 resolutions the WVGA (480*800) and the WXGA (768*1280) share the same Ratio so apps build for WVGA can be scaled to WXGA or the other way around. the 720P resolution however uses a 16:9 ratio that is higher so you have to make sure your UI layout is capable of using this longer screen estate.

    wp8 resolutions

    So what should you do to support all these resolutions? The first thing is all the assets Tile image etc should be used in the largest sizes. The OS will resize them to the right size for you. In your app however you should create a flexible UI that will scale certain UI elements like list boxes to change depending if the screen is longer as in the 720p resolution or shorter as in the other 2 resolutions. Also something to keep in mind is that WXGA is 1.6x the resolution of WVGA the canvas is still 480*800. all UI elements will be scaled to 160%. You don’t have to change your UI for WXGA compared to WVGA except for images. You can check for the current device resolution in code.

    To check the current resolution in code you can use the properties in the Application.Current.Host object. In the example project I’ll print these properties on the screen so you can see the actual values in the screenshots below. We’ll also use these values to select appropriate images for the resolution.

    First we’ll add some text fields to the main page XAML together with an image. In the code behind we’ll set these text boxes to the actual screen height/width/scale and resolution name properties.

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

       2:     <StackPanel Orientation="Horizontal">

       3:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Height</TextBlock>

       4:         <TextBlock x:Name="TextHeight" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

       5:     </StackPanel>

       6:     <StackPanel Orientation="Horizontal">

       7:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Width</TextBlock>

       8:         <TextBlock x:Name="TextWidth" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

       9:     </StackPanel>

      10:     <StackPanel Orientation="Horizontal">

      11:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Scale</TextBlock>

      12:         <TextBlock x:Name="TextScale" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

      13:     </StackPanel>

      14:     <StackPanel Orientation="Horizontal">

      15:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Resolution</TextBlock>

      16:         <TextBlock x:Name="TextResolution" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

      17:     </StackPanel>

      18:     <Image Height="100" x:Name="ScaledImage"></Image>

      19: </StackPanel>

       1: TextHeight.Text = Application.Current.Host.Content.ActualHeight.ToString();

       2: TextWidth.Text = Application.Current.Host.Content.ActualWidth.ToString();

       3: TextScale.Text = Application.Current.Host.Content.ScaleFactor.ToString();

       4:  

       5: //use the scale to check which resolution you're using

       6: switch (Application.Current.Host.Content.ScaleFactor)

       7: {

       8:     case 100:

       9:         ScaledImage.Source = new BitmapImage(new Uri("Assets/wvga.png", UriKind.Relative));

      10:         TextResolution.Text = "WVGA";

      11:         break;

      12:     case 150:

      13:         ScaledImage.Source = new BitmapImage(new Uri("Assets/720p.png", UriKind.Relative));

      14:         TextResolution.Text = "720P";

      15:         break;

      16:     case 160:

      17:         ScaledImage.Source = new BitmapImage(new Uri("Assets/wxga.png", UriKind.Relative));

      18:         TextResolution.Text = "WXGA";

      19:         break;

      20: }

     

    The 3 images: wvga, wxga and 720p are images scaled to the correct size. the WVGA image is 432*100 (the same size as the image width and height in the XAML). the 720p and WXGA are both larger the 720p emulator is 1.5x the size of the WVGA image and the WXGA image is 1.6x the size of the WVGA image. this image is chosen dynamically by the scale property as shown in the code above.

    used images: (text font size is the same on all images to give you an idea of the image quality. click the image to see the actual size)

    wvga

    720p

    wxga

    results in the emulators for all 3 resolutions:

    resolution wvga resolution 720p

    resolution wxga 

     

  • So now we know how to handle images in your UI. the last part you need to know is that apps on the 720p resolutions have a higher height compared to the WVGA and WXGA resolution (as you can see in the screenshots above). If you fix your design on 800 pixels high you’ll have an empty piece of screen on the bottom that is not used by your app. It’s better to design your app with certain parts with dynamic heights of your page like a listbox, map control or scrollviewer so they will fill up the screen with just a bit longer list, map etc.

    Hopefully this gives you an idea on how to build apps supporting all resolutions.

    You can download the sample project here: http://sdrv.ms/QSJ2yx

    Thanks for reading my 4th post in this series of 8 about the new features in Windows Phone 8. Tomorrow a post on some new features in the .net framework 4.5 and the C# 5.0 language which can be important for you as a Windows Phone developer.

    Geert van der Cruijsen

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

    8 days of Windows Phone 8 | Day 3: Emulator & Simulation Dashboard

    8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 3rd day of this series we’ll dive into the new Emulator and the Simulation Dashboard in Visual Studio 2012.

  • 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

     

    day3

    Windows Phone Emulator

    The Windows Phone 8 emulator has changed a lot from the Windows Phone 7 emulator. The new emulator is actually a Hyper-V virtual machine so it feels like an actual phone. When starting the Windows Phone 7 emulator you only had a your app, internet explorer and the settings app available for testing. When starting the Windows Phone 8 emulator you’ll see all the apps you would expect when you buy a Windows Phone. From the dialer to the people hub everything is there in the emulator.

    The reason the new emulator is running in Hyper-V is also the reason why you can only develop for Windows Phone on Windows 8 Pro or higher. You’ll also need a processor that supports Second Level Address Translation (SLAT). This should be available on machines running an I3/I5/I7 processor from intel (my old dual core intel laptop wouldn’t run the emulator because of missing SLAT).

    If you don’t have SLAT you can still develop apps in Visual studio and compile them you’ll only not be able to run the emulator.

    When you open a new Windows Phone project in Visual studio you’ll see several options when choosing an emulator. You can choose to test on a connected device like you could in Windows Phone 7 and there are a bunch of emulators.

    From the 4 emulators you can choose the WVGA, WXGA and 720P these are emulators which run in different resolutions. on the lowest resolution WVGA there’s an extra emulator that runs on 512MB internal memory. The others run on 1024MB. This 512MB emulator is the Windows Phone 8 equivalent of the 256MB Windows Phone 7 emulator which has some restrictions and will not run every app available in the store. Currently the only phone that is announced with 512MB is the HTC 8S. All other phones by HTC, Nokia and Samsung have 1024MB.

    image

    When we press F5 and build and deploy our app the emulator boots up and will automatically launch your app. Booting the emulator will take a bit longer than it did on Windows Phone 7 but it’s understandable since it’s a complete working phone now instead of only your app running in a empty shell.

    wp8 emulator theme settings accent colors wp8

    When the emulator is started you can do everything you can do on a Windows Phone 8 device. you can select the theme color and language like you could on Windows Phone 7 and you can also check all build in apps like the market place, the people hub or the office hub. Great for inspiration when designing and developing your apps since These build-in apps implement the Microsoft Design Language and Windows Phone grid really well.

    There is also an option to open aditional tools like you could on Windows Phone 7 by pressing the arrow key on the bottom of the menu bar next to the emulator. By default it will open the first tab where you can test the accelerometer. This works exactly the same as was the case for Windows Phone 7. you can move the phone around by clicking and dragging the emulator image to see the result in the emulator. You can also change the orientation or play a shake movement.

    accelerometer 

    the 2nd tab is the location tab. Again nothing changed here from Windows Phone 7. you can select a location on the map to see it change in the emulator immediately or record several locations and play it back with set intervals between the locations to emulate a moving phone.

    location 

    The third tab is the screenshot tab. You can take screenshots here of apps running on the emulator. For Windows Phone 7 developers again nothing else new here. On a side note, if you are testing on your device you can also take screenshots by holding the power button together with the start button.

    screenshot

    The last tab in the additional tools menu is the Network tab. On this tab you can see the which virtual network adapter the emulator is using.

    network 

    Simulation Dashboard

    The emulator gives you lots of features to test your application. You can test most test scenarios like test with multiple accent colors, dark/light theme. Test multiple languages and cultures etc. Some use cases however were really hard to test on Windows Phone 7. You had to have a device to test cases like what would happen when your phone goes on the lock screen or what happens on a slow data connection. Some of those cases like a slow data connection are still really hard to test in a consistent way even if you have a device. Luckily Microsoft had the same idea so they came up with a solution for these use cases called the Simulation Dashboard in Visual Studio 2012.

    You can find the Simulation dashboard in the tools menu of Visual Studio.

    simulationdashboardlink

    When you open the Simulation Dashboard you’ll see a new screen on the right where you can set some features of the emulator (don’t know why they didn’t add the simulation dashboard as a to the additional tools of the emulator, would be logical in my opinion)

    simulationdashboard

    The first option is to change your network connection speed to 2G/3G/4G, Wi-Fi or no network. you can also switch the signal strength from good to poor. This gives you a lot of options to see what happens with your app when a user uses your app on a slow connection so you can see if you should improve your app to support slow connection scenarios.

    The next option is to lock the screen of your emulator. really usefull when testing the new lock screen features as described in yesterdays post. This feature can also be useful when building and testing apps that should be able to run under the lockscreen.

    The last scenario is to trigger a reminder. this was also a pain to test before but now it’s just 1 press of a button and a reminder will pop up on your emulator. fun fact: if you press the snooze button another reminder WILL pop up again after the set time ;)

    That’s all i can tell you about the new features available in the Windows Phone 8 emulator and Simulation Dashboard. I think these features really add more value and make it easier for developers to build and test their applications for Windows Phone 8.

    If you have any feedback on this post or this blog serie let me know on twitter or a comment below this post. Tomorrow we’ll discuss what you should do to support all screen resolutions that are available in Windows Phone 8.

    Geert van der Cruijsen

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

    8 days of Windows Phone 8 | Day 2: Live tiles & Lock screen

    8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 2nd day of this series we’ll dive into the new possibilities of Windows Phone 8 live tiles and the lock screen.

    • 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 

      day2

      Live tiles

      If you are familiar with developing for Windows Phone 7 you already know about live tiles. They are one if the unique features of Windows Phone that everyone loves. In Windows Phone 8 Microsoft added more possibilities to create live tiles and also made them more flexible for the end users to really personalize their phone.

      One of the main changes is that live tiles now can be set by any user to 3 different sizes. Small, medium and wide. There are also 3 different templates to create live tiles that show information on different ways: the Flip template, the Cycle template and the Iconic template.

      Sizes used for these templates are:

      Flip Cycle Iconic
      Small 159 * 159px 159 * 159px 110 * 110px
      Medium 336 * 336px 336 * 336px 202 * 202px
      Wide 691 * 336px 691 * 336px -

      You might expect that there would be even more resolutions for the images because of the new resolutions that are supported in Windows Phone 8 but this is not the case. The OS will scale the images for you so you only have to supply them once.

      Flip template

      In Windows Phone 7 it was possible to create tiles and set certain properties on them like a title, count, a back ground image and a text located on the back of the tile. In Windows Phone 8 this is still possible but Microsoft created 2 more tile templates to create live tiles. The template that was used in Windows Phone 7 is now called the Flip Template because it has data on it’s back and will flip at random intervals showing this data. The other templates are called the Iconic template and the Cycle template.

      So lets start looking at some code. At the end of the post you can download all the example code in 1 project to set the different kinds of tiles. Let’s create a Flip tile first:

      We start with a new empty project and add a button to set our flip template. Lets add a click event and place our tile creation code there to make it as easy as possible. In the click event we’ll start adding the code for adding the live tile

       

       1: private void FlipButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
       4:
       5:     FlipTileData fliptile = new FlipTileData();
       6:     fliptile.Title = "WP8";
       7:     fliptile.Count = 9;
       8:     fliptile.BackTitle = "day 2";
       9:
       10:     fliptile.BackContent = "back medium";
       11:     fliptile.WideBackContent = "back of the wide tile";
       12:
       13:     fliptile.SmallBackgroundImage = new Uri("Assets/159.png",UriKind.Relative);
       14:     fliptile.BackgroundImage = new Uri("Assets/336.png", UriKind.Relative);
       15:     fliptile.WideBackgroundImage = new Uri("Assets/wide.png", UriKind.Relative);
       16:
       17:     tile.Update(fliptile);
       18: }

      First of you can get the current active tile by querying the ShellTile class. After that we’ll be creating a new FlipTileData object where we can set all the properties of the new tile. We’ll set the title, count and other properties. Some properties are only for the tile in small mode, some are only used in medium or wide mode and some are used in all modes like the count. We’re adding 3 different images for the 3 sizes of the tile. When we finished setting the properties on the tile we can call the update method on our tile object and pass the FlipTileData to it to set the new tile.

      You can set the following properties on the flip tile:

      Title The title is shown on the bottom left of the front of the tile. it will be shown on the medium and wide tiles.
      Count The count is the number in the black circle on the top right of every tile. The count is shown at all tile sizes.
      BackgroundImage The background image is the image shown on the background of the front of the tile at medium size
      BackBackgroundImage To set the background of the back of the tile use the BackBackgroundImage
      BackContent BackContent is the text shown on the back of a tile at medium size
      BackTitle Title shown on bottom left of the back of a tile on medium and wide size
      SmallBackgroundImage The background of the tile at small size.
      WideBackgroundImage The background of the tile ad wide size
      WideBackBackgroundImage The background of the back of the tile at wide size
      WideBackContent Text shown on the top left of the back of a tile at wide size

      The result will look something like this:

      Small: (note small tile doesn’t flip)

      small

      Medium:

      medium medium example back

      Wide:

      wide example  wide example back

      If you were used to creating live tiles in WP7 there aren’t that much changes as you can see. All that is different are the small and wide sizes of the tile.

      Iconic template

      The iconic template is a new template that is available in Windows Phone 8 and i think this is a really good addition to the Windows Phone SDK. Lots of apps use tiles with a white icon and a transparent background so it looks like the native Windows Phone apps. However lots of people have trouble sizing the icon and the count in the black circle doesn’t look as good as the build in apps like mail or the message hub. To make this easier for everyone Microsoft created the Iconic tile template and it works almost similar to the FlipTile except for we’re using a IconicTileData object instead of the FlipTileData. I think the Iconic tiles will be used a lot on Windows Phone 8.

       1: private void IconicButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
       4:
       5:     IconicTileData icontile = new IconicTileData();
       6:     icontile.Title = "WP8";
       7:     icontile.Count = 12;
       8:
       9:     icontile.IconImage = new Uri("Assets/202.png", UriKind.Relative);
       10:     icontile.SmallIconImage = new Uri("Assets/110.png", UriKind.Relative);
       11:
       12:     icontile.WideContent1 = "8 days of windows phone 8";
       13:     icontile.WideContent2 = "day 2";
       14:     icontile.WideContent3 = "Live tiles and lock screen";
       15:
       16:     ShellTile.Create(new Uri("/MainPage.xaml",UriKind.Relative), icontile, true);
       17: }

      As you can see creating the tile is done the same way as the as the first tile we created except for using the IconicTileData.

      The properties in the IconicTileData are a bit different. one key aspect are the images you can add to the Iconic tiles. They are set to different sizes compared to the other tile templates because they only use part of the tile. In the current beta build i’ve used to create this blogpost the images don’t seem to work that well but my guess this will be finished in the final SDK build.

      Another thing that is different is the last line of generating the live tile. The default live tile is made by a FlipTileData object and you can’t update an existing tile to another template so we’re creating a new tile for the Iconic tile.

      Small: (seems to be a bug in the 8.0 build of the sdk where the count falls of the edge of the tile. Don’t know if this only happens in the emulator or also on actual devices since i haven’t tested it on a device yet because i don’t have a device.)

      iconsmall

      Medium:

      iconmedium

      Wide: (also the rendering of this seems to be a bit off since there should be a margin below the icon that doesn’t seem to be here right now in this build of the SDK)

      iconwide

      The wide template also has 3 lines of text you can add to the wide tile. because of this this template is really versatile and probably one of the reasons this template will be used a lot. A complete list of the IconTileData properties is:

      Title Title shown on bottom left of the tile in medium and wide size
      Count Count shown on the right of the icon image at all sizes
      BackgroundColor Set the background of the tile. if not set it will use the phone accent color
      IconImage Image used in the medium tile size
      SmallIconImage Image used in the small and wide (bottom right) tile size
      WideContent1 Line 1 in the largest font on the wide tile size
      WideContent2 Line 2 of text on the wide tile size
      WideContent2 Line 3 of text on the wide tile size

      Cycle template

      The Iconic tile adds a lot of new possibilities for the live tiles that developers tried to achieve on Windows Phone 7. One example of Windows Phone 7 tiles that lots of people liked was the photo tile where there is a set of images that get rotated in turns on the tile. On Windows Phone 7 there was no way to recreate this as a developer but now with Windows Phone 8 there is a possibility using the Cycle Template.

      Creating a cycle live tile is done the same way as creating the other 2 templates so lets get started and implement the code under the 3rd button in our example app to create a Cycle tile.

       1: private void CycleButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     CycleTileData cycleicon = new CycleTileData();
       4:     cycleicon.Title = "WP8";
       5:     cycleicon.Count = 5;
       6:
       7:     cycleicon.SmallBackgroundImage = new Uri("Assets/159.png", UriKind.Relative);
       8:
       9:     List<Uri> images = new List<Uri>();
       10:     images.Add(new Uri("Assets/cycle1.png", UriKind.Relative));
       11:     images.Add(new Uri("Assets/cycle2.png", UriKind.Relative));
       12:     images.Add(new Uri("Assets/cycle3.png", UriKind.Relative));
       13:     cycleicon.CycleImages = images;
       14:
       15:     ShellTile.Create(new Uri("/MainPage.xaml?id=cycle", UriKind.Relative), cycleicon, true);
       16: }

      The Cycle tile uses the CycleTileData object to set it’s properties and this tile has fewer properties compared to the other templates. The title and count are available as on every other template and the other property that is unique for this template is the CycleImages property. It’s an IEnumerable of Uri’s to images (1 size) that will be used on the medium and wide sizes. it will center the image if it is larger as the tile itself is showing only a part of the image. if the tile is set to small it will only show a static image set in the SmallBackgroundImage property.

      Small:

      cyclesmall

      Medium:

      cyclemedium

      Large:

      cyclewide

      The IEnumerable of images used in the medium and wide tiles can contain up to 9 images and will be rotated using a smooth slide animation. The complete list of properties available in the CycleTileData is:

      Title Tile shown on medium and wide tile sizes in the bottom left corner
      Count Counter shown on all tile sizes at the top right corner
      SmallBackgroundImage Static image shown at the background of the tile at small tile size
      CycleImages List of up to 9 images which will be rotated on the tile at medium and wide tile size.

      Looking at all the live tile features Microsoft added for Windows Phone 8 i believe it really adds some nice new options to create live tiles. I can’t wait for people to use them in their apps.

      Lock screen

      New in Windows Phone 8 is the possibility to add your own apps to the lock screen of Windows Phone 8. As a developer you can’t force an app to be shown on the lockscreen but you can enable your app for it so users can add your app to their lock screen. You can also change the lock screen image in your app by code.

      lock screen app icon, count and Text

      The image on the lock screen is an image you have to include in your project that uses a transparent background and a white icon.

      To set the lock screen image ad an image of 30 * 30 pixels to your solution and open up the WMAppManifest.xml and change the DeviceLockImageURI element to the URL of your lock screen image. Also set the IsRelative attribute to true and IsResource attribute to false. The count and text will be taken of the live tile count property of the current main tile in your app.

       1: <DeviceLockImageURI IsRelative="true" IsResource="false">Assets\LockImage.png</DeviceLockImageURI>

       

      To enable the lock screen image and text you also have to add the following lines of XML to the WMAppManifest.xml below the Tokens element

       1: <Extensions>
       2:       <Extension ExtensionName="LockScreen_Notification_IconCount" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
       3:       <Extension ExtensionName="LockScreen_Notification_TextField" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
       4: </Extensions>

      The settings for displaying data on the lock screen is now complete so we can change our settings on our phone to add our app to the lock screen. To do this. open up settings and go to the lock screen settings. On this screen you can select 1 app that can show the text (default is the calendar app) and 5 apps that are allowed to show an icon + counter. Select your app and you’re ready to go.

      settings lock screen lock screen app added lock screen enabled

      As you can see it uses the counter of our main tile (the flip tile example) and the the text is also the same as we’ve set to the BackContent property of the FlipTileData.

      Lock screen Image

      The last thing I’ll show you is how to set the lock screen background image from within your app. Like using the lock screen icon you’ll also need to add an extension to the WMAppManifest.xml to enable setting the lock screen image

       1: <Extensions>
       2:       <Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
       3: </Extensions>

      When you’ve added the extension to the manifest it’s time to start writing the code to change the lock screen image. First you’ll need to check if your app already provided the current lock screen image and if that isn’t the case you need to ask the user’s permission to change the lock screen image. if the user accepts you can change the lock screen image.

      I’ve added an image of 768*1280 pixels (largest supported resolution right now) set the image to embedded resource and added the following code to the click event of the 4th button to set the lock screen image when we press the button.

       1: private void LockBackgroundButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     SetLockScreenImage();
       4: }
       5:
       6: private async void SetLockScreenImage()
       7: {
       8:     //check if current app provided the lock screen image
       9:     if (!Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication)
       10:     {
       11:         //current image not set by current app ask permission
       12:         var permission = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();
       13:
       14:         if (permission == Windows.Phone.System.UserProfile.LockScreenRequestResult.Denied)
       15:         {
       16:             //no permission granted so return without setting the lock screen image
       17:             return;
       18:         }
       19:     }
       20:
       21:     Windows.Phone.System.UserProfile.LockScreen.SetImageUri(new Uri("ms-appx:///Assets/lockscreen.png", UriKind.Absolute));
       22: }

      As you can see the SetLockScreenImage is using the async keyword because asking the user for permission can only be done by using an async call. therefore we’re using the await keyword there when asking for permission and the app will wait untill the response comes back from the user.

      When we run the app now and press the button we’ll see the old lock screen image being replaced by the newly added image

      lock screen before lock permission

      After pressing yes:

      lock screen new

      This is all for day 2 of my series of blog posts called “8 days of Windows Phone 8”. Tomorrow we’ll have a look at the emulator and the simulation dashboard which give you a lot of options to test your apps.

      Download the sample project here: http://sdrv.ms/QSJ2yx

      Liked the post or have any feedback? leave a comment below!

      Geert van der Cruijsen

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

    8 days of Windows Phone 8

    Yesterday Windows Phone 8 was announced at the live broadcasted event in San Francisco and today the SDK was made available to the public on BUILD. To celebrate this I wrote this series of blog posts to inform you on the new features in the Windows Phone 8 SDK. Inspired by the 31 days of Mango by Jeff Blankenburg when Windows Phone 7.5 Mango was released I thought it was a good idea to create a blog series called “8 days of Windows Phone 8” where I could inform you on using the new features of the just released Windows Phone 8 SDK.

    8 days of windows phone 8

    This first day I would like to start off with a quick summary of all the features that are added in the new SDK. After that I’ll post a new post for the coming 7 days where we’ll dive deeper in each of these features with code samples and demo’s.

  • 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 API 
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases

     

    day1

    SDK overview

    So what’s new in the SDK? Well the most important change that was already announced before this SDK is the merge with the Windows 8 kernel. Because of this the foundation where Windows Phone 7 was built on was replaced by WinRT. In Windows Phone 8 you’ll have access to a subset of the full Windows 8 WinRT and it’s currently called WinPRT. (Don’t know if that will be the official name). The WinPRT contains a subset of the Windows 8 WinRT APIs and also contains a set of new APIs that are only used for phone specific features.

    Application Platform & .net framework

    It’s now possible to build native applications in C++ and you can also use Direct3D to create 3d graphics on Windows Phone. Javascript and HTML however are not included in the SDK and I don’t know if Microsoft has any plans to add this in the future either.

    If you just want to port your Windows Phone 7.5 app to Windows Phone 8 it’s not that much work. A few namespaces have changed so you might have to replace the namespace of these controls. The controls that were moved by Microsoft are the Pivot and the Panorama controls because Microsoft wanted to improve their performance. The LongListSelector is also moved from the Silverlight Toolkit to the SDK itself. Existing Windows Phone 7.5 apps will also run on Windows Phone 8 devices so your existing apps will all keep working on the new devices that will be released.

    The new .net framework 4.5 and C# 5.0 language also add new features that are really useful when building apps. Some examples are the new async and await keywords and serialization features for JSON files. More on these new features at day 5.

    Tiles and notifications

    The new home screen of Windows Phone 8 with the 3 sizes of tiles also needs changes to the API to support this of course. It is now possible to set more texts and images on your tiles which will be used in the different size scenarios. A great addition is that you can also add notifications of your tiles to the lockscreen. In Windows Phone 7.5 it was only possible to see updates on your lockscreen for missed calls, text messages or emails but now you can set up to 5 different apps to have notifications on the lockscreen. It’s also possible to add a text notification to the lockscreen like in Windows Phone 7.5 the Agenda did. The user can select 1 application that is allowed to show it’s notifications there in text. The data of the count on the lockscreen and the text notification on the lockscreen are pulled from the data of the main Tile so you only have to set this to use these new features. More information and examples will be posted in tomorrow’s post that is completely dedicated to these features.

    wp8

    Multi-resolution

    Microsoft also announced earlier that there will be multiple resolutions available on the phones. The 3 available resolutions are: 480X800 (WVGA), 768X1280 (WXGA) and 720×1280 (720P). Both WVGA and WXGA are in a 15:9 ratio where 720P is 16:9 Ratio. Every app will always work on each phone. You can make your UI a bit flexible so that for example listboxes will fill the extra screen space that is available on the 16:9 ratio. If you don’t change anything to your existing design the app will still work but will show a bit of empty space below the app. On day 3 we’ll dive deeper in how to build a flexible UI with these new screen resolutions.

    Maps

    Microsoft replaced the old Bing maps by Nokia maps. New features of these maps are that you can use the system launchers to download a piece of map through the MapDownloaderTask and you can also use the MapsDirectionTask to get directions to a location on the map. You can also launch the Maps application by a MapTask Launcher.

    Speech

    Speech and voice commands are one of the coolest things in the SDK in my opinion. With the new features in the SDK you can start your app by saying commands like “Start MyApp, go to ThisPage”. You can also add a list of available commands which people will hear when they hold the Windows button and say “What can i say?”.

    Wallet & In-app Purchases

    The wallet gives Windows Phone users a place where they can collect coupons, credit card and payment info and accounts, Memberships and loyalty cards. By adding a few capabilities in your manifest (So the user knows you’re going to use the wallet) you can extend the wallet with your apps. You can add/ read update or delete wallet items. (you can only change items linked to your app, so it’s not possible to steal someones credit card info for example). This feature will need to prove itself in the future if it is going to be used a lot or not. One other feature I know for sure will be used a lot are in app purchases. This feature finally gives you the possibility to charge your users for features in an app so the business models on making money are being extended by a lot. examples of this are: buying extra levels for a game. buy a month subscription to a newspaper app etc.

    Proximity

    NFC is one of the features in Windows Phone that are highly anticipated by all the users. It’s possibilities are endless and i’m really curious of what developers are going to use it for. All currently announced phones have NFC capabilities so only time will tell. More on this on day 7.

    Data Sense

    Data sense is a new feature in Windows Phone 8 that allows users to keep track of their data plan. The api also allows developers to support their users by adapting data usage in their apps by checking if the user is on a data plan or not. It can also check if the user exceeded his data plan or is near  exceeding it and because of that it can disable (or ask the user to disable) certain parts of the app that use a lot of data.

     wp8-2

    Simulation dashboard

    Some scenarios are always hard to test without a real device or even when you have a device simulating scenarios like low bandwidth or poor phone signal are nearly impossible to test even though chances are high actual users will run into these scenarios and they might break your app. Microsoft came with a really cool solution to this for Windows Phone 8 and it’s called the Simulation dashboard that is available in Visual Studio 2012. From the Simulation dashboard you can change the bandwidth or signal quality, throw interruptions like getting a call or a notification popup while your app is playing and you can even make the emulator jump to the lock screen to test if everything keeps working when you apps need to keep running under the lockscreen. At day 4 we’ll dive deeper in the possibilities of the new emulator and the simulation dashboard.

    Globalization

    Globalization and localization support was already quite good in Windows Phone 7.5 but now with Windows Phone 8 available in 180+ countries and 50+ languages Microsoft added support for apps to read from right to left which is common in certain languages. I don’t know if a lot of people are going to use these new globalization features but it is nice to mention it’s available.

    That was my quick overview of the SDK. From tomorrow on we’ll dive deeper in the SDK with code samples and more details. What will be discussed in the next blog posts of this series:

  • 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 API
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases

     

    Hopefully you’ll be back tomorrow for the next post in this series!

    Geert van der Cruijsen

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

    I’ll be speaking on Windows 8 and Windows Phone 8 in November

    November is going to be a big month for everyone who likes developing for Windows. 2 days ago Windows 8 was officially launched and this Monday Windows Phone 8 will be launched.

    Lots of events are organized and in November I’m speaking on two of them. First is a Dutch event called “Bedrijf zoekt app” held on the 13th in Bussum. In this session we’ll dive into the possibilities of building apps for Windows 8 without focusing on the development techniques themselves but we’ll be looking more into why companies should develop for Windows 8 and what are the possibilities when you’re going to develop apps for Windows 8.

    More info on the “Bedrijf zoekt app” event here.

    bedrijf zoekt app - logo-vierkant

    2 days later on November 15th I’ll be doing a session on Windows Phone 8 on the Avanade “Masters in Microsoft” event held for software engineering students. This event is FREE and includes food before we start the sessions (should be enough reason for every student to sign up ;) ). This evening I’ll be talking on all the new features of Windows Phone 8 and showing code demo’s on how to use these new features.

    More info on how to sign up for this free event here (Masters in Microsoft Event)

    avalogo

    Hope to see you there!

    Geert van der Cruijsen

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

    Solving Windows 8 enterprise activation error 0×80070005

    So Windows 8 RTM launched yesterday and lots of people installed their copy from MSDN. I did the same but after the installation i couldn’t get my copy to activate. I kept receiving an error 0×80070005 when i wanted to activate my windows copy.

    The problem is that you didn’t have to fill in your key during the installation and now Windows 8 is trying to activate with a default key which is failing.

    You can fix this in a few easy steps:

    • Press the “Windows” key on your keyboard or go back to the “Metro” start screen
    • type “slui 3” and press enter
    • a popup shows up where you can enter your new key. enter this key and press activate
    • Your copy of windows 8 is now activated

    image

    Enjoy windows 8!

    Geert van der Cruijsen

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

    Solving Windows 8 enterprise activation error "DNS name does not exist" 0x8007232B

    So Windows 8 RTM launched yesterday and lots of people installed their copy from MSDN. I did the same but after the installation i couldn’t get my copy to activate. I kept receiving an error “DNS name does not exist ” 0x8007232B when i wanted to activate my windows copy.

    windows 8 activation error 0x8007232b

    The problem is that you didn’t have to fill in your key during the installation and now Windows 8 is trying to activate with a default key which is failing.

    You can fix this in a few easy steps:

    • Press the “Windows” key on your keyboard or go back to the “Metro” start screen
    • type “slui 3” and press enter
    • a popup shows up where you can enter your new key. enter this key and press activate
    • Your copy of windows 8 is now activated

    image

    Enjoy windows 8!

    Geert van der Cruijsen

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

    Introducing: PhoneCompare for Windows Phone 7

    I’ve built a new Windows Phone App that lets you compare 2 Windows Phone devices with all available specs right next to each other to see which is the best. You can also just check the specifications of one of the available windows phones at this moment when you are in a heated argument with friends or colleagues again where you are not sure if that phone had a 1.4GHZ processor or a 1.5 GHZ processor.

    My new app is called PhoneCompare and is available in all Windows Phone Marketplaces for 99 cents. you can also install a free trial that has 100% of the functionality but shows ads.

    PhoneCompare has the following features:

    • List all available Windows Phones
    • Check specifications for a single phone to see its screen size, dimensions, weight, processor, storage, memory, battery and camera.
    • Select 2 phones to compare all these specs next to each other
    • Check the specs of your current phone
    • Browse phones by brand
    • View a list of new phones that are just released or are about to get released

    My plans for the future are to also make it possible to rate phones so you can see which phones are rated the highest and I also want to store most used phones by visitors of the app. All this in version 1.1 :)

      

      

     

    If you have any feedback on this app please let me know by a comment on this post, by sending me a tweet @geertvdc or by rating or using the in app mail function

    Enjoy!

    Geert van der Cruijsen

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

    Windows Phone developer introduction sessions at UTwente & TU/E

    Last week I visited Twente University and today I went to the University of Eindhoven to do a session on building your first Windows Phone App. This post is mainly created for visitors of those sessions so they can download the slide deck and sample code we’ve created during the session.

    imaginecup  utwente  tue

    My sample code and powerpoint deck including lots of resources to start developing for windows phone can be found here:

    https://skydrive.live.com/redir.aspx?cid=ef12210979e9f6b0&resid=EF12210979E9F6B0!1485&parid=EF12210979E9F6B0!1463

    During the session we created a twitter app that downloads the data from an xml feed asynchronous and placing this list of twitter items in a listbox. After that we created some sample data and created a template for the listbox so the twitter list looks nice.

    Hopefully these sessions made you join the Windows Phone community and I expect to see your apps in the marketplace soon :)

    If you have any questions regarding Windows Phone development please send me an email or contact me on twitter @geertvdc

    Happy Coding!

    Geert van der Cruijsen

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