Skip to content

For a Universal Windows App I wanted to implement a Pivot. Reading the guidelines for tabs and pivots by Microsoft I got inspired by the examples given. However, no code samples are supplied so there is no indication how to actually create this in your own Xaml app.

In this blogpost I will show the different steps to get the basics done and I will supply the source code for you to use.

The examples

For mobile

Example design from pivot guidelines by Microsoft

For desktop

Example design for desktop from pivot guidelines by Microsoft

The default Pivot

The default Pivot looks just like the pivot we know from Windows Phone.

<PivotItem Header="item 1">
    <TextBlock>Content 1</TextBlock>

Default Pivot in a UWP app

Adding an icon to the header

So the first step is to add an icon and do some styling. A bit lazy I used the Pivot sample from the Windows Universal Samples as a starting point.

        <local:TabHeader Label="item 1" Glyph="&#xE716;" />
    <TextBlock>Content 1</TextBlock>

Icon in Pivot Header with problem

Immediatly we spot a problem. It seems the Pivot Header has a fixed height.
Browsing around I found a MSDN forum post and a Stack Overflow question about this. Both are resolved using code to adjust the height of the items.

Because we want a responsive solution where the height is not known beforehand, code is not the best option.
Lucky for us, Microsoft has added the Live Visual Tree tool in Visual Studio 2015 making it possible to debug what is happening in the app at runtime. This shows that the PivotHeaderItem has a default Style with a fixed height.

Visual Studio 2015 Live Visual Tree showing the fixed height from the default template

The problem is that Visual Studio does not have any option to edit (a copy of) this template. So we have to get it the hard way.

To find the default template of every control and style in UWP apps we have to go to the following file:

%ProgramFiles(x86)%\Windows Kits\10\DesignTime\CommonConfiguration\Neutral

Look for the PivotHeaderItem template and copy it to the Resources Dictionary for your preferred scope.
In the Style we change the Height to “Auto”

<Setter Property="Height" Value="Auto" />

If the height of your pivot header can be less than 36 you will also need the modify the height of the Previous and Next buttons in the Pivot Header as these have a fixed height too. These changes are made in the Pivot Style.

<Button x:Name="PreviousButton" ... Height="Auto" ... />
<Button x:Name="NextButton" ... Height="Auto"  ... />

Create a copy of the Pivot Style

If you don’t know how to edit a copy of a Style, here are the 3 steps to follow:

  1. Select the Pivot in the Document Outline
  2. Right Click and select “Edit Template”
  3. Choose “Edit a Copy…”

Make the Pivot Header Item reponsive

First I will list how I want the header items to repond:

  • If the app is narrow, the icon is centered above the label
  • If the app is wide, the label is on the right side of the icon
  • The transition from narrow to wide is at 500

Getting this working is quite easy in UWP apps without writing any code at all.
For this we use the new AdaptiveTrigger and the RelativePanel.

We alter the TabHeader.xaml adding a RelativePanel for layout and VisualStates for the transition. Something like this:

        <VisualState x:Name="Narrow">
                <AdaptiveTrigger MinWindowWidth="0" />
                <Setter Target="Icon.(RelativePanel.AlignHorizontalCenterWithPanel)" Value="True" />
                <Setter Target="LabelText.(RelativePanel.Below)" Value="Icon" />
                <Setter Target="LabelText.(RelativePanel.AlignHorizontalCenterWith)" Value="Icon" />
        <VisualState x:Name="Wide">
                <AdaptiveTrigger MinWindowWidth="500" />
                <Setter Target="Icon.(RelativePanel.AlignVerticalCenterWithPanel)" Value="True" />
                <Setter Target="LabelText.(RelativePanel.RightOf)" Value="Icon" />
                <Setter Target="LabelText.(RelativePanel.AlignVerticalCenterWith)" Value="Icon" />
                <Setter Target="RelativePanel.Margin" Value="0,0,12,0"/>
                <Setter Target="Icon.Margin" Value="0,0,0,0"/>
<RelativePanel x:Name="RelativePanel">
    <FontIcon x:Name="Icon"
                Glyph="{Binding Glyph}"
                FontSize="16" />
    <TextBlock x:Name="LabelText"
                Text="{Binding Label}"
                Style="{StaticResource CaptionTextBlockStyle}"
                Margin="2,4,2,4" />

Run the app and resize it so we see the pivot items change when it’s wide enough.
Responsive Pivot Header Items

Aligning the Pivot Header Items

I like it when the pivot items are centered in the mobile layout. To achieve this we need to add the Visual States to the Pivot Style.
If you didn’t have a Pivot Style already look in the previous section how to create a copy of the Style.

We add the Visual State Group the existing VisualStateManager.VisualStateGroups in the RootElement of the Pivot ControlTemplate:

    <VisualState x:Name="Narrow">
            <AdaptiveTrigger MinWindowWidth="0" />
            <Setter Target="HeaderClipper.HorizontalContentAlignment" Value="Center" />
    <VisualState x:Name="Wide">
            <AdaptiveTrigger MinWindowWidth="500" />
            <Setter Target="HeaderClipper.HorizontalContentAlignment" Value="Stretch" />

Now the items are centered when the app is “narrow”, and left aligned when the app is “wide”.
The Pivot Header Items centered

Source code

You can download my Universal Windows Platform App sample project on GitHub.


I received a couple of comments on my article about making the pull-down-to-refresh work with a Windows Phone virtualizing list control.

The problem was that the functionality stopped working after navigating away from the page containing the ItemsControl.
To prevent events from triggering when the list is not in view I deregistered all events. But when the list came back in view I didn’t start monitoring these events again.
Today I committed the code to GitHub to fix this issue.

Source code

You can download my Windows Phone 8 example project on GitHub.


Every Microsoft Dynamics CRM developer has faced this problem: How to get the entity type code for your custom entity in JavaScript. If you need the entity type code for the current form there are several supported ways to get it. But when you want the entity type code for a different custom entity, you are in trouble. The SDK has no real solution for this, and hard-coding is no option as the numbers can change per deployment.

So how do most people solve this? A popular choice is the unsupported Remote Command and Lookup service. Because of the asynchronous nature the use of a service adds a performance penalty and complexity to your code. It also seems this will break in CRM 2015 Update 1.

Digging through the client side object model I found a nice, although still unsupported, treasure which works with CRM 2011 and up, including the latest installment: 2015 update 1.


This class contains a dictionary of all out-of-the-box entities but also all custom entities. And as it’s already loaded in memory there is no performance loss.

Form JavaScript

When using JavaScript in a form the goodies are readily available:

// 1

// 1

// 10025

Web Resource

From a web resource just target the parent window:


Or if you have included the ClientGlobalContext.js.aspx, you can also use the class directly:


Turbo Forms

With the introduction of the turbo forms in CRM 2015 update 1 you need an additional line of code to make the mapping work:

if (Mscrm.EntityPropUtil == null) {
    Mscrm.EntityPropUtil = parent.Mscrm.EntityPropUtil;

From entity type code to entity type name

If you want to use this map to get the entity type name from the entity type code you can use the following line of JavaScript:

Object.keys(Mscrm.EntityPropUtil.EntityTypeName2CodeMap).filter(function(key) { 
  return Mscrm.EntityPropUtil.EntityTypeName2CodeMap[key] === 10025 
// "wv_country"

It’s that easy!


The other day I was working on a Windows Phone app. I wanted to add a “pull down to refresh” panel to a large list of images. Just like the Facebook and Twitter apps have.

Pull-to-refresh in the Twitter app animation. Showing a text to encourage the user pull down further to refresh the list. When pulled down far enough the text changes to let the user know the list will be refreshed after the user releases his finger from the screen.

Pull-to-refresh in the Twitter app. Image by David Washington

As Microsoft does not provide this functionality in their default controls I started searching the web if somebody else has build something like this already.
I found a blog post by Jason Ginchereau where he provided this functionality for Windows Phone 7.
In my app I use an ItemsControl with a VirtualizingStackPanel to prevent memory issues. After I added the PullDownToRefreshPanel control to my list and started testing it on my phone, I ran into some issues.

The issues

Adding the control to my page was easy. But I noticed two things.

  1. Performance, it’s taking up a lot of processing power, resulting in visual lag. Specially when using a low powered phone.
  2. Scrolling, when scrolling through the list with a quick flicking motion the same images kept scrolling by, making the list scroll endlessly until I stopped flicking

In this blog post I will describe my contributions to fix these 2 issues and I will supply the source code for you to use.

1. Improving performance

Looking at the code, the first thing I noticed was that the control subscribes to the LayoutUpdated event. The code in the event handler tries to find the ScrollViewer control to attach to. After the ScrollViewer is successfully found, the event is never unsubscribed and keeps firing quite often. When you add a debug message to the method you’ll see the event fires constantly during the actual scrolling, but also fires when the control is not even on the screen. So the first fix was to unregister the event if the ScrollViewer is found. There is no need to fire unnecessary code.

private void PullDownToRefreshPanel_LayoutUpdated(object sender, EventArgs e)
    if (this.targetScrollViewer == null)
        this.targetScrollViewer = 
        if (this.targetScrollViewer != null)
            this.LayoutUpdated -= PullDownToRefreshPanel_LayoutUpdated;
            // *snip*

The second thing I observed were the NegativeValueConverters. The ValueConvertor adds negative space at the bottom to keep the ScrollViewer positioned on the same location if the PullDownToRefreshPanel was growing in height.
Inside the convertor there is an unnecessary Convert from Object to Double. When resizing the control this conversion was called a lot of times. So this could be written a bit simpler as the value is already of the type Double.

//double doubleValue = -System.Convert.ToDouble(value);
double doubleValue = -(double)value; // No System.Convert needed

When looking at the original example project by Jason, the negative space was needed because the control and the list are in separate rows in a grid. By changing the XAML to put both controls in the same grid cell there is no need for this negative space because the controls are now floating on top of each other. Eliminating the ValueConvertors all together made the process much lighter.
My XAML looks a bit like this:

  <rlb:PullDownToRefreshPanel x:Name="refreshPanel"
                              VerticalAlignment="Top" />
  <ItemsControl x:Name="listBox"
          <VirtualizingStackPanel Orientation="Vertical" />
        <ControlTemplate TargetType="ItemsControl">
          <ScrollViewer ManipulationMode="Control">

2. Fixing the scrolling

To make the pull-to-refresh list work, it’s mandatory to change the ManipulationMode property of the ScrollViewer to “Control“. This allows you to catch the MouseMove event and the MouseLeftButtonUp event. With these events you can detect the change of the position of the content inside the ScrollViewer by monitoring the TranslateY property which changes when the compression happens.

Because I noticed the same images kept scrolling by, I was suspecting the VirtualizingStackPanel was not receiving the correct signals and was recycling the same placeholders (and images) over and over without getting fresh data as it should.
Searching the web again I came across a blog post by Matthijs Krempel describing that the Mango update added some new candy that would allow you to detect the compression using VisualStates and therefore you can leave the ManipulationMode on “System”. Resulting in a better performance and in a correctly functioning VirtualizingStackPanel. This does not work out-of-the-box, you need to add a specific template to the ScrollViewer.
Matthijs added this to his own “PullToRefreshPanel” control.

However, the VisualStates let you only know if compression has started or ended. It doesn’t let you know how much compression is applied. Without the mouse events I needed another way to detect the amount of compression. Which led me to build my own version of the control.

Building a new Pull-Down-To-Refresh Panel

Windows Phone provides the Touch class which is an application-level service that processes touch input from the operating system and raises the FrameReported event. Inside this event you can read what kind of interaction is happening between the fingers and the screen.

private void TouchFrameReported(object sender, TouchFrameEventArgs e)
    var primaryTouchPoint = e.GetPrimaryTouchPoint(this);

    switch (primaryTouchPoint.Action)
        case TouchAction.Down:
            this.initialPoint = primaryTouchPoint.Position;

            if (this.isCompressed)


        case TouchAction.Move:
            if (this.isMeasuring)
                // Only update if the finger moves up/down the screen
                if (this.currentPosition.Y != primaryTouchPoint.Position.Y)
                    this.currentPosition = primaryTouchPoint.Position;
                this.initialPoint = primaryTouchPoint.Position;


        case TouchAction.Up:


So I combined the control Jason originally wrote with the extensions Matthijs made to detect compression. Then I replaced the mouse events with touch actions. Resulting in a faster control that also works with virtualized controls like an ItemsControl with a VirtualizingStackPanel or the ListBox.

I’ll have to note that the PullDownToRefreshPanel control will not work with the LongListSelector as that control does not expose a ScrollViewer.

Source code

You can download my Windows Phone 8 example project on GitHub.


With Windows Azure we can use Windows Azure SQL Database service (formerly known as SQL Azure) when we need a Relational Database. Microsoft offers a 99.9% monthly SLA for this service. But Microsoft doesn’t provide you with the service to restore your data to a moment back in time when you (accidentally) delete of corrupt data.

With an “on premise” Microsoft SQL Server installation you would solve this by configuring and scheduling (transactional log) backups. But this isn’t possible for the Windows Azure service.

You could replicate a copy of your database using SQL Data Sync with a delay. But if you fail to discover the issue in time for the next scheduled sync your copy won’t make a difference.

To have a backup in time I wrote some code to allow a Worker Role to backup my Windows Azure SQL Database every hour. Most solutions you find online are relying on the REST Endpoints but the address of the endpoint is different depending on which datacenter your database is hosted. I found a different solution where you only need the connection string to your database using the DacServices.


To make a backup I use the Microsoft SQL Server 2012 Data-Tier Application Framework. This framework provides the DacServices Class.

You need to configure Local Storage to store the backup temporary and you need a Storage Account to store the backup file permanently.

The solution

// Get the Storage Account
var backupStorageAccount = 

// The container to store backups
var backupBlobClient = backupStorageAccount.CreateCloudBlobClient();
backupContainer = backupBlobClient.GetContainerReference("backups");

// The backup file on blob storage
var storageName = 
  string.Format("Backup_{0}.bacpac", DateTime.Now.ToString("yyyyMMdd-HHmmss"));
var backupFile = backupContainer.GetBlobReference(storageName);

// Get a reference to the temporary files
var localResource = RoleEnvironment.GetLocalResource("TempFiles");
var file = string.Format("{0}{1}", localResource.RootPath, backupFile.Name);

// Connect to the DacServices
var services = new DacServices(ConfigurationManager
services.Message += (sender, e) =>
        // If you use a lock file, 
        // this would be a good location to extend the lease

// Export the database to the local disc
services.ExportBacpac(file, "DatabaseName");

// Upload the file to Blob Storage
backupFile.Properties.ContentType = "binary/octet-stream";

// Remove the temporary file


The code does the following:

  1. Connect to the Storage Account
  2. Get a reference to the container and file where you want to store the backup
  3. Get a reference to the local storage location
  4. Connect to the DacService using the database connection string
  5. Export the database to a “.bacpac” file
  6. Upload the file to blob storage
  7. Delete the local file

A Catch

Before you deploy your Worker Role you’ll have to make sure each of the listed assemblies are referenced and the property “Copy Local” is set to “True” otherwise you will run into trouble.

  • Microsoft.Data.Tools.Schema.Sql
  • Microsoft.Data.Tools.Utilities
  • Microsoft.SqlServer.Dac
  • Microsoft.SqlServer.TransactSql
  • Microsoft.SqlServer.TransactSql.ScriptDom
  • Microsoft.SqlServer.Types