# Retrieve pitch and roll from the accelerometer data [Update]

UPDATE:
You will find an updated version of this post HERE

So what happens if you designed your application to drive a bluetooth device using the Motion class (because the output is less noisy) and then you realize that on the Lumia 520 and Lumia 625 the Motion class is not supported and you have to use the accelerometer. In my case, as i only use pitch and roll,  the solution was pretty simple as it is actually possible to calculate the pitch and roll values directly from the accelerometer data. This way I can still use the Motion class and when not available fallback on the data extracted from the accelerometer. To better understand the algorithm behind this transformation have a look at this LINK.

Before applying the transformation I also apply a low-pass filter to remove short-term fluctuations. The difference between the Arduino sample is that the pitch and roll are inverted and also the pitch was 180 degrees off so I remapped the values (when holding in postion 0 it was telling 180 degrees). I also transformed from radians to degrees for easier visualization (the multiplication with 180/Math.Pi)
``     const double alpha = 0.5;       double fXg = 0;       double fYg = 0;       double fZg = 0;       void acc_ReadingChanged(Windows.Devices.Sensors.Accelerometer sender, AccelerometerReadingChangedEventArgs args)       {         //Low Pass Filter         fXg = args.Reading.AccelerationX * alpha + (fXg * (1.0 - alpha));         fYg = args.Reading.AccelerationY * alpha + (fYg * (1.0 - alpha));         fZg = args.Reading.AccelerationZ * alpha + (fZg * (1.0 - alpha));         //Roll & Pitch Equations         double pitch = (Math.Atan2(-fYg, fZg) * 180.0) / Math.PI;         double roll = (Math.Atan2(fXg, Math.Sqrt(fYg * fYg + fZg * fZg)) * 180.0) / Math.PI;         //rotate 180 degrees         pitch=(pitch>=0)?(180-pitch):(-pitch-180);       }  ``
I have also built a small sample that does comparative plots of the two values using the motion class and the transformation from accelerometer data. Initially I have added also the Microsoft.Devices.Sensors.Accelerometer but the data is almost the same with Windows.Devices.Sensors.Accelerometer with small delays between updates.

Here is the  SOURCE CODE of the sample.

It is been a while since my last post, but I have a good reason (on the 20th of July – so tired that the first time I’ve mistaken the date by one month –  my son Mattia was born and between work and my duties and no sleep there is not much time left for writing on my blog even if I have a lot of posts that I want to do).
I will get right to the subject (the title is not one of the best chosen). A few days ago I was talking with my friend Alessandro Scardova about the possibility of implementing side menus inside an Windows Phone application (similar to the ones in the Facebook application). Even if not 100%”Modern UI” design it is a good approach for applications that have multiple options that need to be accessed quickly (also the approach can be applied cross-platform). So I took it as a challange and tried to implement it.
My initial thought was that I might be able to implement it using an templated panorama or pivot, but after some tests I was not able to get the desired behaviour:
• when we start the application we will have the selected ViewPort selected
• swiping left or right we can open/close the side menus
• also using the buttons on the upper left and on the right corners we can also close and open the side menus
• the side menus have a width smaller than 480 this way, when opened, we can still see a part of main viewport (including the upper button)
• when opening the menus the ApplicationBar is not visible
The solution I have implemented (doesn’t use MVVM pattern) it is more a proof of concept on how to implement the functionality. The approach is pretty simple. We have the whole view that we move inside a canvas using manipulations and animations. Initially I thought that I can use only  grid without the canvas and animate the margin of the grid but, as Windows Phone doesn’t have ThicknessAnimation, my animations for opening and closing the menus were not very smooth. Also I’ve tried implementing the swipe behaviour using the Touch.FrameReported event but the results I got were not very good.
So how does my implementation work:
• I have a canvas/grid that has a width of 1320 and the height stretches to the whole available height that contains my whole view
• The view is inserted in a canvas with initial Canvas.Left position set to -420 this way we see the main view port (component)
• The “stable” positions inside the canvas are:  0: left menu opened, -420: main view and -840:right menu opened
• When pressing the buttons we will use a resource Storyboard with a  DoubleAnimation to set the the Canvas.Left position inside the canvas to 0,-420 or -840:
``  <Canvas.Resources>         <Storyboard x:Name="moveAnimation">           <DoubleAnimation Duration="0:0:0.2" To="0" Storyboard.TargetProperty="(Canvas.Left)" Storyboard.TargetName="LayoutRoot" d:IsOptimized="True" />         </Storyboard>       </Canvas.Resources>  ``
Use the animation to open/close the menus:
``  void MoveViewWindow(double left)       {         _viewMoved = true;         if (left==-420)           ApplicationBar.IsVisible = true;         else           ApplicationBar.IsVisible = false;         ((Storyboard)canvas.Resources["moveAnimation"]).SkipToFill();         ((DoubleAnimation)((Storyboard)canvas.Resources["moveAnimation"]).Children[0]).To = left;         ((Storyboard)canvas.Resources["moveAnimation"]).Begin();       }  ``

• To implement the swipe I use the ManipulationStarted, ManipulationDelta and ManipulationEnded on the canvas container. On delta we set the Canvas.Left value directly (no need for animations) between a maximum of 0 and a minimum of -840.
``  private void canvas_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)       {         if (e.DeltaManipulation.Translation.X != 0)           Canvas.SetLeft(LayoutRoot, Math.Min(Math.Max(-840, Canvas.GetLeft(LayoutRoot) + e.DeltaManipulation.Translation.X), 0));       }  ``
• when swiping we also memorize the initial Canvas.Left position. If substracting the final Canvas.Left and the initial one the absolute value is lower then 100 (not a long swipe) we bounce back to the initial position. Otherwise we move to the next position.
``  private void canvas_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)       {         var left = Canvas.GetLeft(LayoutRoot);         if (_viewMoved)           return;         if (Math.Abs(initialPosition - left) < 100)         {           //bouncing back           MoveViewWindow(initialPosition);           return;         }         //change of state         if (initialPosition - left > 0)         {           //slide to the left           if (initialPosition > -420)              MoveViewWindow(-420);           else             MoveViewWindow(-840);         }         else         {           //slide to the right           if (initialPosition< -420)              MoveViewWindow(-420);           else             MoveViewWindow(0);         }       }  ``
• _viewMoved is used to see if the view was already moved by another event since our manipulation started (like a button was pressed)
Here are some screenshots from the sample that you can download and play with:
Hope you will find it useful.
Here is the SOURCE CODE

NAMASTE!

That was quite a long time with no blog post, but I am coming back. Recently I had to investigate the possibility to embed youtube videos in an Windows Phone application. The easy way is to simply launch IE with the Uri of the video, but this way you have no control over the video as your app will get suspended. I then had a look at the Youtube client apps available in the Windows Phone Store and saw that some of them integrate the video directly into the app. So wanna know how they are doing this?
Well there is a library availabe on codeplex called MyToolkit. This library has a class that is able to retreieve the Uri of the video stream directly from the YouTube video id. You can then download the stream for offline access or can directly play the video using the MediaPlayerLauncher. MyToolkit is also available as a nu-get component so you can directly add a reference to it.
The MyToolkit library is really nice, but what if we could improve it a little bit more and have more control over the video? If we would be able to play the video inside our application page would give us the possibility, for example, to add advertising on top of the video (video apps have a good chance of monetizing using advertising as the user, just like in games, would probably stay longer on that page). For this task we can use Microsoft Player Framework that is available for both Windows Phone 8 and Windows 8. Even more the Player Framework will handle the buffering depending on your connection speed, it is a control inside your page and also will give you full-control over the video playback. (the Player Framework is awesome and is expandible).
So let’s create a small test application. First download and install the Player Framework as it is not available on nu-get (yet). I have used the version 1.3 beta. Then create a new Windows Phone 8 project add reference to the Media Player Framework Windows Phone extension and then, from nu-get, get the MyToolkit.Extended library. For simplicity my MainPage looks like this :

``   <Grid x:Name="LayoutRoot" Background="Transparent">       <mmppf:MediaPlayer x:Name="player">        </mmppf:MediaPlayer>     </Grid>  ``

where mmpf is:

`` xmlns:mmppf="clr-namespace:Microsoft.PlayerFramework;assembly=Microsoft.PlayerFramework"  ``

Now on Loaded event I use MyToolkit to retrieve the YouTube stream Uri and then pass it to the MediaPlayer:

`` private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)       {         var videoUri = await MyToolkit.Multimedia.YouTube.GetVideoUriAsync("PQVlW4xbNuI", MyToolkit.Multimedia.YouTubeQuality.Quality480P, MyToolkit.Multimedia.YouTubeQuality.Quality480P);         if (videoUri != null)           player.Source = videoUri.Uri;       }  ``

For convenience the page is set to landscape. I don’t know if playing Youtube video using this method is 100% legal as it bypasses the advertising (it is what every other windows phone YouTube app is using including the one from Microsoft that was pulled out of the store).
Also pay attention that there are some videos where the resulting stream is protected/encoded and cannot be played by the Player Framework. One of these videos is Girl on fire by Alicia Keys. Also Microsoft’s Youtube app (if you still have it installed ) was not able to open this type of streams and just gives an error while MetroTube, after realizing that it cannot open the stream inside the app, it launches Internet Explorer with the “classic” link to the video.
The same method and libraries can be used for your Windows 8 store application.

Here is the Source Code. (the video I use is my own).

NAMASTE

# Why setting a control Height and Width to 0 is not the brightest idea inside a Windows Phone project

I am doing this small post because I have battled the whole morning with this bug and finally got it and it might save you some time if you read it and have the same problem.
Scenario: Pivot with two items and at some point the swipe on one of the items doesn’t work anymore. Putting a button on the PivotItem that doesn’t swipe I can still change the selected item and the second item still swipes correctly.
Cause: I was setting the Height=0 and Width=0 on a control inside the PivotItem (in my project I don’t want my control to be collapsed). The problem presents itself if you set any of the controls inside a PivotItem to Height and Width = 0 when the PivotItem is selected. If on the other hand you set the Height and the Width to anything >1 the PivotItem continues to swipe correctly. Even more strange: if the PivotItem is not selected when  you set the Width and Height to 0 and swipe to the control’s PivotItem everything will still work correctly. So pay attention better not use set Width and Height =0 on UI controls.
If you want to test it yourself and maybe tell me what really happens I am attaching a small project created from a Windows Phone Pivot application where I’ve added a menu that will set the Height and Width of the list inside the first PivotItem to 0. I also set the background of the first PivotItem to green so you will see that it is still expanded.
How to reproduce the problem: If you execute the menu command with the first PivotItem selected you will see that the pivot doesn’t swipe anymore. If you change the values to 1, run the app again and execute the menu with the first PivotItem selected you will see that the pivot still swipes correctly. If, on the other hand, you let the values set to 0 but when executing the menu you have the second PivotItem selected you will see that the first item stil swipes correctly. Bug? Feature? Just pay attention to setting controls to Width and Height 0 because you might have problems with the UI and you won’t know what is causing it.
NAMASTE

# Why setting a control Height and Width to 0 is not the brightest idea inside a Windows Phone project

I am doing this small post because I have battled the whole morning with this bug and finally got it and it might save you some time if you read it and have the same problem.
Scenario: Pivot with two items and at some point the swipe on one of the items doesn’t work anymore. Putting a button on the PivotItem that doesn’t swipe I can still change the selected item and the second item still swipes correctly.
Cause: I was setting the Height=0 and Width=0 on a control inside the PivotItem (in my project I don’t want my control to be collapsed). The problem presents itself if you set any of the controls inside a PivotItem to Height and Width = 0 when the PivotItem is selected. If on the other hand you set the Height and the Width to anything >1 the PivotItem continues to swipe correctly. Even more strange: if the PivotItem is not selected when  you set the Width and Height to 0 and swipe to the control’s PivotItem everything will still work correctly. So pay attention better not use set Width and Height =0 on UI controls.
If you want to test it yourself and maybe tell me what really happens I am attaching a small project created from a Windows Phone Pivot application where I’ve added a menu that will set the Height and Width of the list inside the first PivotItem to 0. I also set the background of the first PivotItem to green so you will see that it is still expanded.
How to reproduce the problem: If you execute the menu command with the first PivotItem selected you will see that the pivot doesn’t swipe anymore. If you change the values to 1, run the app again and execute the menu with the first PivotItem selected you will see that the pivot still swipes correctly. If, on the other hand, you let the values set to 0 but when executing the menu you have the second PivotItem selected you will see that the first item stil swipes correctly. Bug? Feature? Just pay attention to setting controls to Width and Height 0 because you might have problems with the UI and you won’t know what is causing it.
NAMASTE

# Fix Panorama layout when upgrading your project to OS 8.0 SDK

This will be a really short blog post but might save you some time if you have an OS 7.1 Panorama project and decide to upgrade the project to 8.0 SDK. After the upgrade you might see that the layout of your old page changed and you have less content available for the items and also the header looks different. Don’t try to fix the problem by changing the margin of the control on the OS 8.0 SDK. The reason why this happens is because the Windows Phone SDK team decided to “tweak” a little bit the default style for the Panorama control, to be more precise the TitleLayer part of the style.
On Windows Phone OS 7.1 projects the TitleLayer looks like this:
`` <controlsPrimitives:PanningTitleLayer x:Name="TitleLayer" CacheMode="BitmapCache" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" FontSize="187" FontFamily="{StaticResource PhoneFontFamilyLight}" HorizontalAlignment="Left" Margin="10,-76,0,9" Grid.Row="0"/>  ``
while on OS 8.0 we have:

`` <Primitives:PanningTitleLayer x:Name="TitleLayer" CharacterSpacing="-35" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" FontSize="170" FontFamily="{StaticResource PhoneFontFamilyLight}" HorizontalAlignment="Left" Margin="10,-34,0,0" Grid.Row="0"/>  ``

You can see that not only the margin have changed (the reason why on OS 8.0 version we have less space in the content -44px ), but also the font size changed from 187 to 170 producing these visual differences:

The solution to this problem is pretty simple: extract the old style of the Panorama control (the easiest way is using Blend) and apply to both WP7.1 and OS 8.0 versions of your project. This way the UI will be consistent between the two versions of the app. If you don’t want to use Blend I am attaching the default OS 7.1 style so you can directly copy/paste it in your project and apply it to your Panorama control.

`` <Style x:Key="PanoramaStyleWP71" TargetType="controls:Panorama">                  <Setter Property="ItemsPanel">                       <Setter.Value>                            <ItemsPanelTemplate>                                 <controlsPrimitives:PanoramaPanel x:Name="panel"/>                            </ItemsPanelTemplate>                       </Setter.Value>                  </Setter>                  <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>                  <Setter Property="Background" Value="Transparent"/>                  <Setter Property="Template">                       <Setter.Value>                            <ControlTemplate TargetType="controls:Panorama">                                 <Grid>                                      <Grid.RowDefinitions>                                           <RowDefinition Height="auto"/>                                           <RowDefinition Height="*"/>                                      </Grid.RowDefinitions>                                      <controlsPrimitives:PanningBackgroundLayer x:Name="BackgroundLayer" HorizontalAlignment="Left" Grid.RowSpan="2">                                           <Border x:Name="background" Background="{TemplateBinding Background}" CacheMode="BitmapCache"/>                                      </controlsPrimitives:PanningBackgroundLayer>                                      <controlsPrimitives:PanningTitleLayer x:Name="TitleLayer" CacheMode="BitmapCache" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" FontSize="187" FontFamily="{StaticResource PhoneFontFamilyLight}" HorizontalAlignment="Left" Margin="10,-76,0,9" Grid.Row="0"/>                                      <controlsPrimitives:PanningLayer x:Name="ItemsLayer" HorizontalAlignment="Left" Grid.Row="1">                                           <ItemsPresenter x:Name="items"/>                                      </controlsPrimitives:PanningLayer>                                 </Grid>                            </ControlTemplate>                       </Setter.Value>                  </Setter>             </Style>  ``

NAMASTE

# Fix Panorama layout when upgrading your project to OS 8.0 SDK

This will be a really short blog post but might save you some time if you have an OS 7.1 Panorama project and decide to upgrade the project to 8.0 SDK. After the upgrade you might see that the layout of your old page changed and you have less content available for the items and also the header looks different. Don’t try to fix the problem by changing the margin of the control on the OS 8.0 SDK. The reason why this happens is because the Windows Phone SDK team decided to “tweak” a little bit the default style for the Panorama control, to be more precise the TitleLayer part of the style.
On Windows Phone OS 7.1 projects the TitleLayer looks like this:
`` <controlsPrimitives:PanningTitleLayer x:Name="TitleLayer" CacheMode="BitmapCache" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" FontSize="187" FontFamily="{StaticResource PhoneFontFamilyLight}" HorizontalAlignment="Left" Margin="10,-76,0,9" Grid.Row="0"/>  ``
while on OS 8.0 we have:

`` <Primitives:PanningTitleLayer x:Name="TitleLayer" CharacterSpacing="-35" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" FontSize="170" FontFamily="{StaticResource PhoneFontFamilyLight}" HorizontalAlignment="Left" Margin="10,-34,0,0" Grid.Row="0"/>  ``

You can see that not only the margin have changed (the reason why on OS 8.0 version we have less space in the content -44px ), but also the font size changed from 187 to 170 producing these visual differences:

The solution to this problem is pretty simple: extract the old style of the Panorama control (the easiest way is using Blend) and apply to both WP7.1 and OS 8.0 versions of your project. This way the UI will be consistent between the two versions of the app. If you don’t want to use Blend I am attaching the default OS 7.1 style so you can directly copy/paste it in your project and apply it to your Panorama control.

`` <Style x:Key="PanoramaStyleWP71" TargetType="controls:Panorama">                  <Setter Property="ItemsPanel">                       <Setter.Value>                            <ItemsPanelTemplate>                                 <controlsPrimitives:PanoramaPanel x:Name="panel"/>                            </ItemsPanelTemplate>                       </Setter.Value>                  </Setter>                  <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>                  <Setter Property="Background" Value="Transparent"/>                  <Setter Property="Template">                       <Setter.Value>                            <ControlTemplate TargetType="controls:Panorama">                                 <Grid>                                      <Grid.RowDefinitions>                                           <RowDefinition Height="auto"/>                                           <RowDefinition Height="*"/>                                      </Grid.RowDefinitions>                                      <controlsPrimitives:PanningBackgroundLayer x:Name="BackgroundLayer" HorizontalAlignment="Left" Grid.RowSpan="2">                                           <Border x:Name="background" Background="{TemplateBinding Background}" CacheMode="BitmapCache"/>                                      </controlsPrimitives:PanningBackgroundLayer>                                      <controlsPrimitives:PanningTitleLayer x:Name="TitleLayer" CacheMode="BitmapCache" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" FontSize="187" FontFamily="{StaticResource PhoneFontFamilyLight}" HorizontalAlignment="Left" Margin="10,-76,0,9" Grid.Row="0"/>                                      <controlsPrimitives:PanningLayer x:Name="ItemsLayer" HorizontalAlignment="Left" Grid.Row="1">                                           <ItemsPresenter x:Name="items"/>                                      </controlsPrimitives:PanningLayer>                                 </Grid>                            </ControlTemplate>                       </Setter.Value>                  </Setter>             </Style>  ``

NAMASTE

# Type forwarding and XAML sharing between WP OS 7.1 and 8.0 projects

This post is about a new feature available in Windows Phone OS 8.0 SDK called Type Forwarding.

Have you ever wondered how does the Windows Phone 8.0 SDK handles the fact that the Panorama, Pivot controls changed the namespace and the assembly from OS 7.1 SDK to OS 8.0 SDK? (80% that you haven’t ). I recently had to migrate an OS 7.1 project to OS 8.0, but also keep the old one (duplicated the old project and upgrade the duplicated one).

Here is the story of what happens when you upgrade an OS 7.1 project that uses Panaroma or Pivot to OS 8.0:
If you start a new Windows Phone Pivot App with the target OS 8.0 inside MainPage.xaml the prefix “phone” is used for the Pivot control where “phone” is:

`` xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"  ``
If, on the other hand, you create a new Windows Phone Pivot App with the target OS 7.1 inside MainPage.xaml the prefix “controls” is used for the Pivot/Panorama control where “controls” is:
`` xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"  ``
The real “magic” happens when you upgrade the Windows Phone 7.1 project to OS 8.0. The MainPage.xaml page doesn’t change (you will still see the “controls” tag is kept in order to be able to better share the code between the versions), but instead a reference to Microsoft.Phone.Controls.dll is added to the OS 8.0 reference that is not used if you create a new project with target OS 8.0. If you wonder if by adding this reference you use the old version of the controls the answer is NO. What this assembly does is that is uses a really neat and new  feature of the .Net compiler called Type Forwarding. This feature can be used when you move a class from one namespace/dll (assembly) to another and you don’t want to recompile the application to reference the new dll but you will only deploy the two dlls where the first one (the one that the application already knew uses the Type Forwarding to tell the application that a certain class/es moved to another assembly). In the case of Windows Phone OS 8.0 SDK the usage is even “cooler” as it enables you to use the same XAML for both OS 7.1 projects and OS 8.0 ones. Inside AssemblyInfo.cs of Microsoft.Phone.Controls.dll OS 8.0 version we have all the declarations needed to forward the types to their new locations:

`` [assembly: TypeForwardedTo(typeof(Panorama))]   [assembly: TypeForwardedTo(typeof(PanoramaItem))]   [assembly: TypeForwardedTo(typeof(Pivot))]   [assembly: TypeForwardedTo(typeof(PivotItem))]   [assembly: TypeForwardedTo(typeof(PivotItemEventArgs))]   [assembly: TypeForwardedTo(typeof(AnimationDirection))]   [assembly: TypeForwardedTo(typeof(PanningBackgroundLayer))]   [assembly: TypeForwardedTo(typeof(PanningLayer))]   [assembly: TypeForwardedTo(typeof(PanningTitleLayer))]   [assembly: TypeForwardedTo(typeof(PanoramaPanel))]   [assembly: TypeForwardedTo(typeof(PivotHeaderItem))]   [assembly: TypeForwardedTo(typeof(PivotHeadersControl))]  ``

I am attaching a small project called TypeForwarding that implements the same functionality as Microsoft.Phone.Controls.dll OS 8.0 version.

Other usages that I can thing of:

• Flurry SDK changes the name of the namespace for the Api class for WP7SDK to WP8SDK (bad choice when you need code sharing). If you want to keep the same code for the OS 7.1 and the OS 8.0 version of the app you will have to use conditional compiling for every file where you use the Api class. Much easier would be to create an OS 8.0 library project with the default namespace WP7SDK and forward the Api class to the WP8SDK added as a reference to the library project. This way the old WP7SDK will continue to work as it was on the OS 8.0 using the OS 8.0 version of the Flurry SDK.
• MVVM Light. If you use inside your XAML the EventToCommand this is not xaml shareable between OS 7.1 and OS 8.0 because the assemblies changes from GalaSoft.MvvmLight.Extras.WP71.dll to GalaSoft.MvvmLight.Extras.WP8.dll. The easiest approach in this case (an open source) would be to recompile the dll and use the same name for both versions of the dll. But if you don’t have access to the source code of the dll you could use type forwarding.  Also a third approach would be to derive your on class like MyEventToCommand and use this inside the xaml.
Keep in mind this neat feature because you might need it. I would also love to see, in the next version of the SDK, the possibility to use MarkupExtension this way we could conditionally compile parts of the XAML depending on the version of the SDK the app is running on. Have a look at this blog post that explains how it works on WPF projects.

Till next post NAMASTE and have fun coding for Windows Phone!

# Type forwarding and XAML sharing between WP OS 7.1 and 8.0 projects

This post is about a new feature available in Windows Phone OS 8.0 SDK called Type Forwarding.

Have you ever wondered how does the Windows Phone 8.0 SDK handles the fact that the Panorama, Pivot controls changed the namespace and the assembly from OS 7.1 SDK to OS 8.0 SDK? (80% that you haven’t ). I recently had to migrate an OS 7.1 project to OS 8.0, but also keep the old one (duplicated the old project and upgrade the duplicated one).

Here is the story of what happens when you upgrade an OS 7.1 project that uses Panaroma or Pivot to OS 8.0:
If you start a new Windows Phone Pivot App with the target OS 8.0 inside MainPage.xaml the prefix “phone” is used for the Pivot control where “phone” is:

`` xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"  ``
If, on the other hand, you create a new Windows Phone Pivot App with the target OS 7.1 inside MainPage.xaml the prefix “controls” is used for the Pivot/Panorama control where “controls” is:
`` xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"  ``
The real “magic” happens when you upgrade the Windows Phone 7.1 project to OS 8.0. The MainPage.xaml page doesn’t change (you will still see the “controls” tag is kept in order to be able to better share the code between the versions), but instead a reference to Microsoft.Phone.Controls.dll is added to the OS 8.0 reference that is not used if you create a new project with target OS 8.0. If you wonder if by adding this reference you use the old version of the controls the answer is NO. What this assembly does is that is uses a really neat and new  feature of the .Net compiler called Type Forwarding. This feature can be used when you move a class from one namespace/dll (assembly) to another and you don’t want to recompile the application to reference the new dll but you will only deploy the two dlls where the first one (the one that the application already knew uses the Type Forwarding to tell the application that a certain class/es moved to another assembly). In the case of Windows Phone OS 8.0 SDK the usage is even “cooler” as it enables you to use the same XAML for both OS 7.1 projects and OS 8.0 ones. Inside AssemblyInfo.cs of Microsoft.Phone.Controls.dll OS 8.0 version we have all the declarations needed to forward the types to their new locations:

`` [assembly: TypeForwardedTo(typeof(Panorama))]   [assembly: TypeForwardedTo(typeof(PanoramaItem))]   [assembly: TypeForwardedTo(typeof(Pivot))]   [assembly: TypeForwardedTo(typeof(PivotItem))]   [assembly: TypeForwardedTo(typeof(PivotItemEventArgs))]   [assembly: TypeForwardedTo(typeof(AnimationDirection))]   [assembly: TypeForwardedTo(typeof(PanningBackgroundLayer))]   [assembly: TypeForwardedTo(typeof(PanningLayer))]   [assembly: TypeForwardedTo(typeof(PanningTitleLayer))]   [assembly: TypeForwardedTo(typeof(PanoramaPanel))]   [assembly: TypeForwardedTo(typeof(PivotHeaderItem))]   [assembly: TypeForwardedTo(typeof(PivotHeadersControl))]  ``

I am attaching a small project called TypeForwarding that implements the same functionality as Microsoft.Phone.Controls.dll OS 8.0 version.

Other usages that I can thing of:

• Flurry SDK changes the name of the namespace for the Api class for WP7SDK to WP8SDK (bad choice when you need code sharing). If you want to keep the same code for the OS 7.1 and the OS 8.0 version of the app you will have to use conditional compiling for every file where you use the Api class. Much easier would be to create an OS 8.0 library project with the default namespace WP7SDK and forward the Api class to the WP8SDK added as a reference to the library project. This way the old WP7SDK will continue to work as it was on the OS 8.0 using the OS 8.0 version of the Flurry SDK.
• MVVM Light. If you use inside your XAML the EventToCommand this is not xaml shareable between OS 7.1 and OS 8.0 because the assemblies changes from GalaSoft.MvvmLight.Extras.WP71.dll to GalaSoft.MvvmLight.Extras.WP8.dll. The easiest approach in this case (an open source) would be to recompile the dll and use the same name for both versions of the dll. But if you don’t have access to the source code of the dll you could use type forwarding.  Also a third approach would be to derive your on class like MyEventToCommand and use this inside the xaml.
Keep in mind this neat feature because you might need it. I would also love to see, in the next version of the SDK, the possibility to use MarkupExtension this way we could conditionally compile parts of the XAML depending on the version of the SDK the app is running on. Have a look at this blog post that explains how it works on WPF projects.

Till next post NAMASTE and have fun coding for Windows Phone!

# Detect the screen resolution for Windows Phone OS 7.1 applications

As you probably know Windows Phone 7.1 applications run perfectly on Windows Phone 8 devices. This means that your application/s could run on multiple display resolutions (which are the resolutions supported by Windows Phone 8 devices). If you want to take advantage of the new resolutions (for example downloading higher quality images for higher resolutions devices, fix some minor UI anomalies on higher resolutions) you will need to know the ScaleFactor of the device. The property is only available in the Windows Phone 8.0 SDK, but the good news is that you can access it using reflection.

Solution:

We retrieve the Get method of the ScaleFactor property and invoke it only if the application is running on an Windows Phone 8 device.
Here is the source code:
``  public static Size DisplayResolution       {         get         {           if (Environment.OSVersion.Version.Major<8)             return new Size(480,800);           int scaleFactor=(int) GetProperty(Application.Current.Host.Content, "ScaleFactor");           switch (scaleFactor)           {             case 100:               return new Size(480, 800);             case 150:               return new Size(720, 1280);             case 160:               return new Size(768, 1280);           }           return new Size(480, 800);         }       }       private static object GetProperty(object instance, string name)       {         var getMethod= instance.GetType().GetProperty(name).GetGetMethod();         return getMethod.Invoke(instance, null);       }  ``
I am also attaching a small sample Windows Phone OS 7.1 test project.

SOURCE CODE

P.S. I think Telerik could use this method to fix this RadToolTip visual anomaly (the 1 pixel width lines that I have filled with blue for contrast) :

NAMASTE