
Yesterday the SDK for Windows Phone 8 was finally announced at Build 2012. It shares part of the code-base with Windows 8, and the SDK is pretty similar with the Windows 8 one. This is good news for developers, since it will be pretty easy to migrate Windows Phone Apps to Windows Store Apps and vice versa.
As an individual developer you can register to develop apps for Windows Phone for only $8 before the 7th of November.
These are the icons available by default for the App Bar:
Click to see a large version of the image.
As I am currently working in a Windows 8 Metro app, I needed to implement several Settings Flyouts. I didn’t want to reinvent the wheel, so I decided to use Callisto toolkit.
1. Installing Callisto from NuGet:
Right click in your project -> Manage NuGet Packages…

2. Adding custom settings to your App:
As I am using the same settings menu in the whole app, I can register it in my Application class. In the App Class:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
// Do not repeat app initialization when already running, just ensure that
// the window is active
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
{
Window.Current.Activate();
return;
}
// Settings
SettingsPane.GetForCurrentView().CommandsRequested += Settings_CommandsRequested;
// Etcetera
}
I need to implement an Event Handler to provide the OS with my new Settings menu items.
private void Settings_CommandsRequested
(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args
)
{
// Settings Wide
SettingsCommand settingsw
= new SettingsCommand
("SettingsW",
"Settings Wide",
(x
) =>
{
SettingsFlyout settings
= new SettingsFlyout
();
settings
.FlyoutWidth = Callisto
.Controls.SettingsFlyout.SettingsFlyoutWidth.Wide;
settings
.HeaderText = "Settings Wide";
settings
.Content = new CallistoSettings
.SettingsViews.SettingsWide();
settings
.IsOpen = true;
});
args
.Request.ApplicationCommands.Add(settingsw
);
}
As you can notice in the code, the Content is a User Control. So I can edit it in Blend, and it’s much easier to make it look nice.
Some screen-shoots:




In one of the projects that I am currently working on I needed to implement this. I needed this because I am using the ItemsControlto display a list of Items. The problem that I had is that I have several type of objects in my list, and I wanted to use a different template for each of them.
1. Markup for a standard ItemsControl
- Define the DataTemplate as a static resource:
<Page.Resources>
<DataTemplate x:Key="TempA">
<Border Background="Red">
<TextBlock Text="{Binding Title}" />
</Border>
</DataTemplate>
</Page.Resources>
- Declare your Items Control to use the Data Template:
<ItemsControl x:Name="items"
ItemsSource="{Binding Items}"
ItemsTemplate="{StaticResource TempA}" />
2. Implement a DataTemplateSelector to use several Templates in an ItemsControl
- Implement the selector to use a different template based in the object type:
public class ItemsTemplateSelector
: DataTemplateSelector
{
public DataTemplate TemplateA
{ get
; set
; }
public DataTemplate TemplateB
{ get
; set
; }
protected override DataTemplate SelectTemplateCore
(object item, DependencyObject container
)
{
if (item
is ObjectTypeA
)
{
return TemplateA
;
}
else if (item
is ObjectTypeB
)
{
return TemplateB
;
}
else
{
return base.SelectTemplate(item, container
);
}
}
}
- Declare your DataTemplates in Resources
<Page.Resources>
<DataTemplate x:Key="TempA">
<Border Background="Red">
<TextBlock Text="{Binding Title}" />
</Border>
</DataTemplate>
<DataTemplate x:Key="TempB">
<Border Background="Blue">
<TextBlock Text="{Binding Title}" />
</Border>
</DataTemplate>
</Page.Resources>
- Declare your DataTemplateSelector in Resources
<views:ItemsTemplateSelector x:Key="itemsTemplateSelector"
TemplateA="{StaticResource TempA}"
TemplateB="{StaticResource TempB}" />
- Update the ItemsControl to use your DataTemplateSelector
<ItemsControl x:Name="items"
ItemsSource="{Binding Items}"
ItemTemplateSelector="{StaticResource itemsTemplateSelector}" />
This is a functionality that many apps will need, and the OS is making it very easy to integrate. Metro introduces the concept of Contracts, they are like interfaces to indicate the OS that our app can perform certain functionalities (Search / Share / File Picker). This post will focus on integrating SEARCH.
1. Open your project in Visual Studio 2012, open the App Manifest (Package.appxmanifest). Under the tab “Declarations” add Search.

2. Declare the Search Pane in your App class. If you want to provide search suggestions, also declare the array in the App class.
sealed partial class App
: Application
{
private SearchPane searchPane
;
private static string[] suggestionList
;
public App
()
{
this.InitializeComponent();
this.Suspending += OnSuspending
;
}
protected override async
void OnLaunched
(LaunchActivatedEventArgs args
)
{
// Do not repeat app initialization when already running, just ensure that
// the window is active
if (args
.PreviousExecutionState == ApplicationExecutionState
.Running)
{
Window
.Current.Activate();
return;
}
// SearchPane
this.searchPane = SearchPane
.GetForCurrentView();
// Suggestion list
suggestionList
= DataService
.GetSearchSuggestions().ToArray();
searchPane
.SuggestionsRequested +=
new TypedEventHandler
<SearchPane, SearchPaneSuggestionsRequestedEventArgs
>
(OnSearchPaneSuggestionsRequested
);
}
/* Continue with the window initialization */
}
3. Add the method to provide the search suggestions to the search pane (For simplicity in this sample it is done in the App class too)
private void OnSearchPaneSuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs e)
{
var queryText = e.QueryText;
if (!string.IsNullOrEmpty(queryText))
{
var request = e.Request;
foreach (string suggestion in suggestionList)
{
if (suggestion.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
{
// Add suggestion to Search Pane
request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);
// Break since the Search Pane can show at most 5 suggestions
if (request.SearchSuggestionCollection.Size >= 5)
{
break;
}
}
}
}
}
4. Now we need a UI to display the search results. Visual Studio has a template.
This action will also add the method OnSearchActivated to the App class to declare the Search Contract, indicating to Windows 8 that our app allows Searching.

/// <summary>
/// Invoked when the application is activated to display search results.
/// </summary>
/// <param name="args">Details about the activation request.</param>
protected override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
{
App1.SearchResultsPage1.Activate(args.QueryText, args.PreviousExecutionState);
}
5. Implement your search functionality and provide the results to the Search Results view:
protected override void LoadState
(Object navigationParameter, Dictionary
<String,
Object> pageState
)
{
var queryText
= navigationParameter
as String;
// TODO: Application-specific searching logic. The search process is responsible for
// creating a list of user-selectable result categories:
//
// filterList.Add(new Filter("<filter name>", <result count>));
//
// Only the first filter, typically "All", should pass true as a third argument in
// order to start in an active state. Results for the active filter are provided
// in Filter_SelectionChanged below.
// TODO: Add your results
this.DefaultViewModel["Results"] = new List
<SearchResult
>()
{
new SearchResult
()
{
Title
= "Result 1",
Subtitle
= "Subtitl",
Description
= "Description",
Image
= null
}
};
var filterList
= new List
<Filter
>();
filterList
.Add(new Filter
("All",
0,
true));
// Communicate results through the view model
this.DefaultViewModel["QueryText"] = '\u201c' + queryText
+ '\u201d';
this.DefaultViewModel["CanGoBack"] = this._previousContent
!= null;
this.DefaultViewModel["Filters"] = filterList
;
this.DefaultViewModel["ShowFilters"] = filterList
.Count > 1;
}
6. Use the search pane, and you will get a list of suggestions as well.

7. Search results (Not implemented):

Good luck!
Currently I am working in an app for Windows 8 Metro, and I need to use a SQLite database. The steps to get it set up are not really straight forward, but Tim Heuer created a really good tutorial. He recommends to use a little wrapper (ORM), called sqlite-net available in GitHub. It works pretty well, but the main problem is that only supports databases auto-generated from your class model. That’s a problem for my use case, since the database that I need to use already exists. I need to create my own mappings. Ouch! For this reason I forked the library in GitHub to support custom mappings using two simple annotations:
[MapToTable("StockTable")]
public class Stock
{
[MapToColumn("StockId")]
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MapToColumn("StockSymbol")]
[MaxLength(8)]
public string Symbol { get; set; }
}
This class would try to use a table called ‘StockTable’ and the columns would be: StockId, StockSymbol. It is a simple modification that works nicely for my needs. Enjoy it!
Feedback appreciated.
Update: Now you don’t need to compile the Dll for SQLite for x86 and x64 WinRT, they are available to download in the SQLite website.
Update 2: Now you don’t even need to reference any static DLL, you can just install SQLite as a Visual Studio 2012 extension and it will embed the right DLL depending on the architecture of the build. Reference: SQLite with windows 8.
It has taken two rejections, but I am happy to announce that Daylight is available in the Windows Phone Marketplace. Here is a summary of some things learnt while developing it.
1. Make your life easy using open source libraries from NuGet
Following the idea of not reinventing the wheel, this is the list of libraries used:
- Coding4Fun: Set of controls (progress overlay, toggle button, colour picker, etc.) and converters. Essential for any app.
- Northern Lights WP7 Toolkit: This is a library with a set of classes that will simplify the usage of Isolated Storage (persistent cache on the phone), asymmetric encryption, handling of errors sending a report via email, among other things.
- Your Last About Dialog: To get your app certified by Microsoft you need to include information about the publisher, and a way to contact you. This library gives you that in a Pivot control and you only have to enter de data in a XML file. It supports localization.
2. Getting icons to use in the app
There are many open source collections, but I like these 2:
Metro Icons: 130 icons from the Windows Phone 7 preview shown at the Mobile World Congress 2010 in Barcelona.

Templarian Icons: a project started a few months ago to supply creative commons licensed icons to Windows Phone developers. Built specifically for Windows Phone and include vector icons. If you need an icon not included, just mention @Templarian on Twitter explaining the icon, and you’ll get it. Currently there are more than 600 icons.

3. Using Location Services and getting your app certified
Another requirement by Microsoft to get your app certified when using Location Services, is to include a Privacy Policy in your app. You also need to let the user disable Location Services from your app.
This is the reason why this app needed a Settings section:

The correspondent XAML for this is:
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Daylight"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Settings" Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<toolkit:ToggleSwitch Header="Location" Name="EnableLocation"
Checked="EnableLocation_Checked" Unchecked="EnableLocation_Unchecked" />
<TextBlock Text="Privacy policy ...." TextWrapping="Wrap" />
<TextBlock Tap="EnableLocation_Contact" Margin="0 10 0 0">
<Underline><Run Text="Email Us"/></Underline>
</TextBlock>
</StackPanel>
</Grid>
The code behind, not using MVVM for simplicity in this example:
public partial class Settings
: PhoneApplicationPage
{
public Settings
()
{
InitializeComponent
();
if (NorthernLights
.PersistentVariables.Get<bool?>("enableLocation") == true)
{
EnableLocation
.IsChecked = true;
}
else
{
EnableLocation
.IsChecked = false;
EnableLocation
.Content = Localization
.AppResources.Off;
}
}
private void EnableLocation_Checked
(object sender, RoutedEventArgs e
)
{
NorthernLights
.PersistentVariables.Set<bool?>("enableLocation",
true);
}
private void EnableLocation_Unchecked
(object sender, RoutedEventArgs e
)
{
NorthernLights
.PersistentVariables.Set<bool?>("enableLocation",
false);
}
private void EnableLocation_Contact
(object sender,
System.Windows.Input.GestureEventArgs e
)
{
new EmailComposeTask
{
Subject
= "Privacy Question",
Body
= "Daylight",
To
= "email@comyoucom.com"
}.Show();
}
}
4. Localising your app
Daylight is currently available in English and Spanish. The first thing that I’d recommend you to read if you are planning to localize your app is to follow the Best practices for Windows Phone. To set up your app to support localization, you can follow the official documentation, or this good tutorial from windows phone geek.


5. Make sure that your app works with the Dark and Light themes
By default Windows Phone supports two colour themes: dark (black background) and light (white background). Your app must work when the phone is set up to use any of those. You are not obligated to have two colour themes in your app too, but it’s a nice to have. In order to achieve that, instead using hard-coded styles, you could use the styles that are defined in the phone already.

This is a code snippet that I use and reuse in many projects, I thought that it’d be useful to publish it.
private static bool ResizeSquaredBitmapAndSave(Bitmap bitmap, string destImage, int squaredImageSize)
{
float originalImageWidth = bitmap.Width;
float originalImageHeight = bitmap.Height;
int tempHeight = squaredImageSize;
int tempWidth = squaredImageSize;
int x_offset = 0;
int y_offset = 0;
// Landscape
if (originalImageWidth >= originalImageHeight)
{
tempWidth = (int)((float)squaredImageSize * (originalImageWidth / originalImageHeight));
x_offset = (tempWidth - squaredImageSize) / 2;
}
// Portrait
if (originalImageHeight > originalImageWidth)
{
tempHeight = (int)((float)squaredImageSize * (originalImageHeight / originalImageWidth));
y_offset = (tempHeight - squaredImageSize) / 2;
}
Bitmap thumbnail = ResizeBitmap(bitmap, -x_offset, -y_offset,
tempWidth, tempHeight, squaredImageSize, squaredImageSize, Color.Transparent);
if (thumbnail != null)
{
thumbnail.Save(destImage, ImageFormat.Png);
thumbnail.Dispose();
return true;
}
else
{
return false;
}
}

Yesterday I just submitted my first windows phone app: Daylight, to the market. I have used several libraries for different purposes, but to create the “Loading” overlay that looks like the original one, I have used Coding4Fun Toolkit for windows phone.
1. Install Coding4Fun libraries using NuGet
VS > Tools > Library Package Manager > Package Manager Console
PM > Install-Package Coding4Fun.Phone.Controls.Complete
2. Add references to the namespaces in the XAML that you want to add the overlay
xmlns:slToolkit ="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns:c4f="clr-namespace:Coding4Fun.Phone.Controls;assembly=Coding4Fun.Phone.Controls"
xmlns:Converters="clr-namespace:Coding4Fun.Phone.Controls.Converters;assembly=Coding4Fun.Phone.Controls"
3. Add resources
<phone:PhoneApplicationPage.Resources>
<Converters:BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</phone:PhoneApplicationPage.Resources>
4. Overlay markup
The app is using a Grid with 2 rows as main layout, the overlay is using the same layout to cover the whole screen:
<!-- Loading Overlay -->
<c4f:ProgressOverlay Canvas.ZIndex="1000" Name="progressOverlay"
Visibility="{Binding Path=OverlayVisibility, Converter={StaticResource BoolToVisibilityConverter}}"
Grid.RowSpan="2" Opacity="80" d:IsLocked="True" d:IsHidden="True">
<c4f:ProgressOverlay.Content>
<StackPanel>
<slToolkit:PerformanceProgressBar IsIndeterminate="True" />
<TextBlock HorizontalAlignment="Center">Loading</TextBlock>
</StackPanel>
</c4f:ProgressOverlay.Content>
</c4f:ProgressOverlay>
5. ViewModel attribute that will set the overlay to visible or collapsed
public bool OverlayVisibility { get; set; }
Enjoy Coding4Fun!
Recently we decided to host a campaign website in AWS using EC2. The site had to run only under SSL / HTTPS, so we needed to redirect the users trying to use HTTP to the HTTPS protocol. That can be set up on IIS using the rewrite module, because this solution didn’t work. We ended up doing the redirect in code.
The way that the cluster is set up is:
ELB listen to HTTPS (443), forwarding to HTTP (80) on the instance.
ELB listen to HTTPS (80), forwarding to HTTP (80) on the instance. In this case we want to redirect the user to HTTPS.
The communication between the Load Balancer and the instance is clear HTTP. On each request we need to check if the user is using a secure connection, otherwise, we need to redirect him:
Global.asax:
protected void Application_BeginRequest()
{
if (!SslHelper.IsSecureConnection() && !HealthcheckRequest())
{
Response.Redirect("https://www.home.com");
}
}
Notice, that if the request is from the ELB to the Health-check URL we don’t want to redirect, it would cause an infinite loop.
The way that the Elastic Load Balancer notify the instance the protocol that the user used to make the request is setting the HTTP Header: “X-Forwarded-Proto”.
SSL Helper, this would work locally and also on AWS:
public static class SslHelper
{
public static bool IsSecureConnection()
{
return IsSecureInAws()
|| HttpContext.Current.Request.IsSecureConnection;
}
private static bool IsSecureInAws()
{
return string.Equals(HttpContext.Current.Request
.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
}
}
Helper method to filter the health-check requests from ELB
private static bool HealthcheckRequest()
{
return HttpContext.Current.Request.Url.ToString().ToLower().EndsWith("/healthcheck");
}
Another thing to notice when you’re running a cluster behind ELB is that if you want to log the original request IP of the user, that is also set in a HTTP header, and this helper method would suffice to get it:
public static string FetchUserIP()
{
string ip = HttpContext.Current.Request.Headers["X-Forwarded-For"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.UserHostAddress;
}
return ip;
}