Nico's digital footprint

I grew up in the nineties, that makes me awesome by default

IIS Express and the Windows Phone 8 emulator

by Nico

As an app developer you’re bound to run into a situation where you’re building both an app and a mobile website or REST based service. That means that you’re testing the ASP.net project in IIS Express while using the Windows Phone 8 emulator, since the emulator behaves like a separate device on the network you can’t use localhost to contact your IIS Express server.

There are a few ways to tackle this problem, you can finish the web project first and deploy it to a webserver. If your WP8 emulator is configured correctly it should have internet access and will be able to connect to your server just fine. A second option is to install an IIS server in your network and deploy to there from Visual Studio. But the most easy option would be to use the IIS Express server that comes with Visual Studio. That’s certainly an option but requires some (small) configuration tweaks.

First things first

We’ll need a webproject of course to test this. I’ll create a very very basic ASP.net WebAPI project and a very basic Windows Phone 8 app that will run in the emulator. I could have made my point with a simple hello world website and the mobile browser but that’s just boring.

Visual Studio 2012 ships with ASP.net MVC WebAPI, think REST services made ridiculously easy, to start a project select the MVC4 web template in Visual Studio 2012 and give it a name.

 

Once you click OK a second dialog will show up and that one holds the option to start a WebAPI project.

What this gives you is an MVC project with an API controller. This behaves much like the normal controller that you’re used to from MVC but instead of returning a view it returns data in a JSON format (serializing happens with JSON.net by the way, not with the .net serializer). I’m not going to dive very deep in WebAPI, there are a lot of bloggers out there that know way more about this stuff than I do. We’ll be using the default GET method from the ValuesController.

Code Snippet
  1. // GET api/values
  2. publicIEnumerable<string> Get()
  3. {
  4.     returnnewstring[] { "value1", "value2" };
  5. }

This just returns a collection of two strings.

Next step is adding a Windows Phone 8 project to the solution (a simple basic project started from the normal template). Now we have two projects in one solution that both need to start up. We could launch the api without debugging and launch the WP8 app in debug mode or we can set them both to launch at debug by selecting multiple startup projects in the solution properties.

You can easily see that the settings have applied successfully if no project in the solution is bold anymore.

Okay, time to hook them up. We’ll need two things, the IP address of the pc running IIS Express and the port that the ASP.net project will use. Getting the IP address should be easy, just enter ipconfig in a command prompt. To find out the port, navigate to the properties of the ASP.net project.

In the Web tab of the properties you can see the project url for the website, that url contains the port that will be used.

Time for some coding, in the Windows Phone app, add a constant that holds the url to the website.

Code Snippet
  1. privateconststring Url = "http://192.168.0.116:7145/";

And the code to fetch the REST data

Code Snippet
  1. privatevoid FetchData()
  2. {
  3.     WebClient client = newWebClient();
  4.  
  5.     client.DownloadStringCompleted += ClientOnDownloadStringCompleted;
  6.  
  7.     client.DownloadStringAsync(newUri(Url + "api/values"));
  8. }

The callback will use Json.net (added through NuGet) to deserialize the values into a List<string> that is then set as the ItemsSource of a LongListSelector.

Code Snippet
  1. privatevoid ClientOnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs downloadStringCompletedEventArgs)
  2. {
  3.     if (downloadStringCompletedEventArgs.Error == null)
  4.     {
  5.         var values = JsonConvert.DeserializeObject<List<string>>(downloadStringCompletedEventArgs.Result);
  6.  
  7.         ValueList.ItemsSource = values;
  8.     }
  9. }

All in all pretty easy but this won’t work because IIS Express is bound to localhost only by default, we’ll need to change the config to allow external connections.

The configuration of IIS Express can be found in the applicationhost.config xml file found in %userprofile%\documents\IISExpress\config (just copy-paste this path into the Windows 8 start screen and press enter)

Open the XML file and search for the name of your ASP.net project. It should look something like this

Code Snippet
  1. <site name="IisExpressDemo" id="13">
  2.     <application path="/" applicationPool="Clr4IntegratedAppPool">
  3.         <virtualDirectory path="/" physicalPath="c:\users\nico\documents\visual studio 2012\Projects\IisExpressDemo\IisExpressDemo" />
  4.     </application>
  5.     <bindings>
  6.         <binding protocol="http" bindingInformation="*:7145:localhost" />
  7.     </bindings>
  8. </site>

Line 6 contains the binding, copy this line and paste it underneath, change localhost with the IP address of your pc, like this

Code Snippet
  1. <site name="IisExpressDemo" id="13">
  2.     <application path="/" applicationPool="Clr4IntegratedAppPool">
  3.         <virtualDirectory path="/" physicalPath="c:\users\nico\documents\visual studio 2012\Projects\IisExpressDemo\IisExpressDemo" />
  4.     </application>
  5.     <bindings>
  6.         <binding protocol="http" bindingInformation="*:7145:localhost" />
  7.         <binding protocol="http" bindingInformation="*:7145:192.168.0.116" />
  8.     </bindings>
  9. </site>

Close the IIS Express server if it’s still running and run the project.

Now there’s a pretty big chance that you’ll see this.

Visual Studio 2012 needs to be started as administrator to allow IIS Express to create bindings for external connections, so if you get this error, close and restart Visual Studio 2012 as an administrator.

Run the project again and the Windows Phone application should be able to fetch the data from the API.

 

Conclusion

In this post I’ve talked about opening up your IIS Express development server to allow external connections. This is needed to allow the Windows Phone 8 emulator to connect to websites or APIs hosted locally. It’s basically two steps

  • Add the IP address of your pc to the IIS config
  • Launch Visual Studio as administrator to be able to set the binding

 


Tags:

.Net | Devices | IIS | Metro | Web development | WP8

Extending the Windows Phone pivot

by Nico

As I was working on a Windows Phone 8 project I needed a pivot that could hide its title, giving back some screen real-estate when needed. The basic pivot that is included in the Windows Phone SDK doesn’t have this kind of behavior so it was a great opportunity to try out custom controls in Windows Phone. I’ve build custom controls in XAML before but never based on an existing one, so fun times ahead. Let me start by showing a side-by-side comparison between both views of my pivot.

don’t mind the overlapping textblock and button, point is that when the button is clicked, the title of the pivot disappears.

Building a XAML custom control

It’s quite easy to build a custom control in XAML as long as you follow the guidelines. It requires you to add a folder called Themes and in the folder a file called generic.xaml. The generic.xaml file is a resource dictionary, no code behind file is needed. Do follow the naming conventions exactly or your control won’t work. Next step is adding a class that inherits from ContentControl (or a control that already inherits from ContentControl). The project for my ExtendedPivot looks like this

The project type is a WP8 class library containing two custom controls, one for the pivot and one for the pivot items.

Extending the pivot

Since I only want to add a functionality to an existing control, the Pivot, my ExtendedPivot class inherits from Pivot instead of CustomControl.

Code Snippet
  1. publicclassExtendedPivot : Pivot
  2. {
  3.     publicstaticreadonlyDependencyProperty HeaderVisibilityProperty =
  4.         DependencyProperty.Register("HeaderVisibilityProperty", typeof (Visibility), typeof (ExtendedPivot), newPropertyMetadata(null));
  5.  
  6.     publicVisibility HeaderVisibility
  7.     {
  8.         get { return (Visibility)GetValue(HeaderVisibilityProperty); }
  9.         set { SetValue(HeaderVisibilityProperty, value); }
  10.     }
  11.  
  12.     public ExtendedPivot()
  13.     {
  14.         DefaultStyleKey =  typeof(ExtendedPivot);
  15.     }
  16. }

We’ll start with the constructor, Line 14 is necessary when developing a custom control, it sets the style of the control to the style defined in generic.xaml (we’ll get to that style in a minute). Lines 6 – 10 are a property that will be used by the DependencyProperty. The DependencyProperty (lines 3-4) is a property that we can bind a value to when using the control in a project, it might seem a bit overwhelming at first but there’s a great snippet in VS2012 to easily write them. Basically, the parameters for the Register function are a name, the type of the property, the owner type (type of the control where you’re declaring the DP) and some metadata.

The get and set method of the normal property use the DP to get and set values through databinding.

generic.xaml

This is the style for the ExtendedPivot as declared in generic.xaml

Code Snippet
  1. <Style TargetType="local:ExtendedPivot">
  2.     <Setter Property="Margin" Value="0" />
  3.     <Setter Property="Padding" Value="0" />
  4.     <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}" />
  5.     <Setter Property="Background" Value="Transparent" />
  6.     <Setter Property="ItemsPanel">
  7.         <Setter.Value>
  8.             <ItemsPanelTemplate>
  9.                 <Grid />
  10.             </ItemsPanelTemplate>
  11.         </Setter.Value>
  12.     </Setter>
  13.     <Setter Property="Template">
  14.         <Setter.Value>
  15.             <ControlTemplate TargetType="local:ExtendedPivot">
  16.                 <Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
  17.                     <Grid.RowDefinitions>
  18.                         <RowDefinition Height="Auto" />
  19.                         <RowDefinition Height="Auto" />
  20.                         <RowDefinition Height="*" />
  21.                     </Grid.RowDefinitions>
  22.                     <Grid Grid.RowSpan="3" Background="{TemplateBinding Background}" />
  23.                     <ContentControl Grid.Row="0"
  24.                                     Margin="24,17,0,-7"
  25.                                     HorizontalAlignment="Left"
  26.                                     Content="{TemplateBinding Title}"
  27.                                     ContentTemplate="{TemplateBinding TitleTemplate}"
  28.                                     Visibility="{TemplateBinding HeaderVisibility}" />
  29.                     <primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1" />
  30.                     <ItemsPresenter x:Name="PivotItemPresenter"
  31.                                     Grid.Row="2"
  32.                                     Margin="{TemplateBinding Padding}" />
  33.                 </Grid>
  34.             </ControlTemplate>
  35.         </Setter.Value>
  36.     </Setter>
  37. </Style>

Basically, I’ve created a xaml page in some very basic Windows Phone project, right-clicked it, selected Edit Template > Edit a copy. This gives you a copy of the template for the Pivot. I copied that template in the generic.xaml style. The ContentControl at Lines 23-28 show the title in the pivot. I added the Visiblity property here and bound it to the HeaderVisibility property in the ExtendedPivot class. To bind a property in a style you need to use the TemplateBinding keyword instead of the normal Binding one.

Don’t forget to set TargetType to the type of your custom control.

Using the custom control in an app

The control is ready, now it’s time to use it. Create a new Windows Phone app and reference the project or DLL of the custom control. This is the MainPage of the sample app.

Code Snippet
  1. <phone:PhoneApplicationPage x:Class="ExtendedPivot.MainPage"
  2.                             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.                             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.                             xmlns:control="clr-namespace:ExtendedPivot.Control;assembly=ExtendedPivot.Control"
  5.                             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6.                             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  7.                             xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  8.                             xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  9.                             FontFamily="{StaticResource PhoneFontFamilyNormal}"
  10.                             FontSize="{StaticResource PhoneFontSizeNormal}"
  11.                             Foreground="{StaticResource PhoneForegroundBrush}"
  12.                             Orientation="Portrait"
  13.                             SupportedOrientations="Portrait"
  14.                             shell:SystemTray.IsVisible="True"
  15.                             mc:Ignorable="d">
  16.  
  17.     <!--  LayoutRoot is the root grid where all page content is placed  -->
  18.     <Grid x:Name="LayoutRoot" Background="Transparent">
  19.         <!--  Pivot Control  -->
  20.         <control:ExtendedPivot HeaderVisibility="{Binding Visibility}" Title="MY APPLICATION">
  21.             <control:ExtendedPivotItem Header="item 1">
  22.                 <Grid>
  23.                     <TextBlock Text="item1" />
  24.                     <Button Click="ButtonBase_OnClick" Content="button" />
  25.                 </Grid>
  26.             </control:ExtendedPivotItem>
  27.  
  28.             <control:ExtendedPivotItem Header="item 2">
  29.                 <TextBlock Text="item2" />
  30.             </control:ExtendedPivotItem>
  31.         </control:ExtendedPivot>
  32.     </Grid>
  33. </phone:PhoneApplicationPage>

Line 4 defines the namespace that holds the ExtendedPivot. Line 20 puts the control on the actual page. Notice that we bind the HeaderVisibility property of our control. I defined the datacontext of this page in code behind to be of type MainViewModel. MainViewModel implements INotifyPropertyChanged and only holds one property of type Visibility, that property is bound to the ExtendedPivot’s HeaderVisibility.

The Button in the pivot will switch the HeaderVisibility between Collapsed and Visible, this happens in the code behind of this page.

Code Snippet
  1. publicpartialclassMainPage : PhoneApplicationPage
  2. {
  3.     privateMainViewModel _mainViewModel;
  4.  
  5.     // Constructor
  6.     public MainPage()
  7.     {
  8.         InitializeComponent();
  9.  
  10.         _mainViewModel = newMainViewModel();
  11.  
  12.         DataContext = _mainViewModel;
  13.     }
  14.  
  15.     privatevoid ButtonBase_OnClick(object sender, RoutedEventArgs e)
  16.     {
  17.         if (_mainViewModel.Visibility == Visibility.Collapsed)
  18.         {
  19.             _mainViewModel.Visibility = Visibility.Visible;            
  20.         }
  21.         else
  22.         {
  23.             _mainViewModel.Visibility = Visibility.Collapsed;          
  24.         }
  25.     }
  26. }

Not really the best way of writing a Windows Phone app but it’s just for making the point Glimlach

Conclusion

Extending a Windows Phone control isn’t hard as long as you follow the naming conventions, adding some extra functionality is as easy as copying the xaml template and adding some dependency properties.

The sample code can be found on my SkyDrive

 


Tags:

.Net | Binding | Devices | WP7 | WP8 | XAML

Presenting at Multi-mania

by Nico

Today I delivered a session at Europe’s biggest free multimedia conference. The session was an introductory session on Windows Phone 8. As promised during the session, here are the slides

The demos can be found on my SkyDrive

In case you’re interested in the session but couldn’t make it to Multi-mania, I’ve delivered this talk before as an MSDN webcast and there’s a recording of that session.

 


Tags:

.Net | Community | Presenting | WP8 | XAML

  Log in

About the author

Hi,

My name is Nico, I’m an MVP Windows Platform Development living in Belgium.
I’m currently employed as a .NET consultant at RealDolmen, one of Belgium’s leading IT single source providers.

I'm also founding member and board member of the Belgian Metro App Developer Network, a user group focussed on Windows 8 and Windows Phone development. If you're in Belgium feel free to drop by if we're doing an event. http://www.madn.be

Since June 2012 I'm a proud member of Microsoft's Extended Experts Team Belgium. And in February 2013 I became a member of DZone's Most Valuable Bloggers family.

In 2013 I became a book author and wrote "Windows 8 app projects, XAML & C# edition".

In 2014 I received the MVP award for the very first time.

I hope to get feedback from my readers either through comments, mail (nico_vermeir@hotmail.com), twitter, facebook, …

 

mvp

 

mvp

 

 

MeetLogo

 

MVBLogo

mybook

 

Month List