VS code and bash shell scripts

The other day, I was working on moving a lot of RUN statements from my Dockerfile into separate shell scripts when I encountered the following issue:

/var/dockerscripts/installsudo.sh: line 3: sudo: command not found



This is how the shell file looked like :

#!/bin/bash

apt-get update && apt-get install -y --no-install-recommends \

        sudo

adduser jenkins sudo

Nothing in particular, right ?

However, it did not recognize the multiline statement character \.

So I had to change the line ending character from \r\n to \n. This can easily be done in VS code via a button in the bottom right of the editor.

LF

CRLF

Upgrading your Surface Pro to Windows 10

Windows 10 came out on June 29th at 00:00 here in Belgium which gave me about a head start of 8 hours compared to the consumers in the US, so I prepared my Surface Pro 2 (SP2) running Windows 10 Insider Preview (IP) 10240 for the upgrade.
So, here’s my story.

I wanted to do the upgrade, not a clean install, which meant I had to revert to Windows 8.1 that shipped with my Surface Pro 2. Also, I didn’t wanted to waste my Windows 10 MSDN keys on my personal devices.
A factory reset can easily be done via Settings => Update and Security => Recovery => Reset this PC => Get started => Restore factory settings in Windows 10 IP.
Unfortunately, this failed because I deleted my recovery partition that came preinstalled on the SP2.

Actually, I deleted all of them, so I could get more disk space.

So, I downloaded the SP2 recovery image from Microsoft : https://www.microsoft.com/surface/en-us/support/warranty-service-and-recovery/downloadablerecoveryimage?productId=100110237
After that I unzipped it onto a FAT32 formatted USB drive and booted the SP2 into recovery (VOL DOWN during startup)

I wasn’t able to Reset my PC. These where the errors I got :

  • The drive where windows is installed is locked
  • Unable to reset your pc a required drive partition is missing

Eventually, I ended up reinstalling Windows 10 IP 10166 to get a working version onto my SP2 and restart the process.
This time, I let the Windows 10 IP installation re-create the partitions for me.

So at that point, I had Windows 10 IP 10166 running on my SP2.

Then, I tried to revert to the SP2 recovery image again, with the same errors as mentioned above.

I rebooted the SP2, got into recovery and cleaned the Windows 10 IP partition using DiskPart : http://knowledge.seagate.com/articles/en_US/FAQ/005929en?language=en_US
After this, I was able to Reset my PC using the SP2 recovery USB image.

At this point, I had Windows 8.1 running on my system as the Microsoft gods intended when they shipped the SP2.
So, this meant I had to wait for the KB3035583 update to install and reserve my copy of Windows 10.
I decided not to wait that long and downloaded the Media Creation Tool : http://windows.microsoft.com/nl-nl/windows-10/media-creation-tool-install to start the upgrade.

I chose Upgrade this PC now to start upgrading.

Since then, everything went smoothly, I ended up with Windows 10 PRO fully activated on my SP2!
After a Disk Cleanup of Windows Updates and Previous versions of Windows, my C:\ had about 16,4GB in use!

But I wanted a clean installation of Windows 10, so I opened Settings => Update and Security => Recovery => Reset this PC => Get started => Remove Everything. After all of that, I had about 10,4 disk space in use, my version of Windows 10 PRO was activated and running smooth.

I tried to upgrade the Windows 7 ULT PC at home, but due to limited disk space (50GB SSD, 10GB free) I had no option but to clean install Windows 10 from ISO. So I created a bootable USB drive using the Media Creation Tool and booted the PC up, did the Upgrade. After doing the upgrade it was activated and genuine.
Then I did a Disk Cleanup, Reset my PC, Remove Everything.

Now I have an upgraded, clean SP2(WIN8.1) and PC(WIN7SP1) running Windows 10 PRO, activated, genuine.

I can see myself reusing the Reset this PC feature quite a lot in the future, since it takes away a lot of the effort on finding a legitimate product key and installation media to do a new clean install. The downside, is that you won’t be able to alter your hardware since Microsoft creates a hash of the machine it upgraded in order to activate it. So, I think having a store-bought copy of Windows 10 is something that can not be avoided in the near future.

 

Please note that both of my machines where eligable for upgrade to Windows 10 (WIN8.1 and WIN7SP1) Both of them where genuine and activated before the upgrade.

 

 

Cheers,

Maarten

Adding content to your XAML controls / behaviors / dependencyobjects

I’m all in for clean, readable and non-redundant code. For JavaScript, C# and XAML alike.

So instead of writing XAML like this :

<myNs:MyObject>
	<myNs.MyObject.MyCollectionOfItems>
		<myNs:MyItem Text="Item 1">
			<myNs:MyItem.Child>
					<myNs:Child Text="Child of Item 1"/>
			</myNs:MyItem.Child>
		</myNs:MyItem>
		<myNs:MyItem Text="Item 2"/>
		<myNs:MyItem Text="Item 3"/>
	</myNs.MyObject.MyCollectionOfItems>
</myNs:MyObject>

I’d rather look at something in the likes of this :

<myNs:MyObject>
		<myNs:MyItem Text="Item 1">
			<myNs:Child Text="Child of Item 1"/>
		</myNs:MyItem>
		<myNs:MyItem Text="Item 2"/>
		<myNs:MyItem Text="Item 3"/>
</myNs:MyObject>

In order to get this to work for your custom XAML elements, you’ll need to specify the property that will act as the content property of the element. This can be done via the ContentPropertyAttribute.

So let’s say you have a Control, FrameworkElement or DependencyObject that you want to apply this to :

[ContentProperty(Name = "Items")] //Set the attribute and the name of the DP that holds the content
    public class MyObject : Control
    {
        public DependencyObjectCollection Items //This property will act as the content of MyObject, this is a collection, but it can also be a DependencyObject
        {
            get
            {
                DependencyObjectCollection collection = (DependencyObjectCollection)base.GetValue(MyObject.ItemsProperty);
                if (collection == null) //Initialize in case of NULL
                {
                    collection = new DependencyObjectCollection();
                    base.SetValue(MyObject.ItemsProperty, collection);
                }
                return (DependencyObjectCollection)GetValue(ItemsProperty);
            }
            set { SetValue(ItemsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Items.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemsProperty =
            DependencyProperty.Register("Items", typeof(DependencyObjectCollection), typeof(MyObject), new PropertyMetadata(null));

        protected override Windows.Foundation.Size ArrangeOverride(Windows.Foundation.Size finalSize) //When added to the visual tree, write a debug line of the content of this control
        {
            Debug.WriteLine(ToString());
            return base.ArrangeOverride(finalSize);
        }

        public override string ToString()//This is pretty obvious
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("This is a MyObject");

            int itemCount = 0;
            foreach (MyItem item in Items)
            {
                builder.AppendLine(String.Format("This is a MyItem {0} with text {1}", ++itemCount, item.Text));
                var child = item.Child as MyChild;
                if (child != null)
                    builder.AppendLine(String.Format("And with child {0}", child.Text));
            }

            return builder.ToString();
        }
    }

Now for the rest of the classes :

//A child doens't have content, just Text
public class MyChild : DependencyObject
    {
        public String Text
        {
            get { return (String)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(String), typeof(MyChild), new PropertyMetadata(null));
    }
//The MyItem can have content, the contentproperty is Child
    [ContentProperty(Name = "Child")]
    public class MyItem : DependencyObject
    {
        public DependencyObject Child //This is just a dependencyobject, not a collection
        {
            get { return (DependencyObject)GetValue(ChildProperty); }
            set { SetValue(ChildProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Child.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ChildProperty =
            DependencyProperty.Register("Child", typeof(DependencyObject), typeof(MyItem), new PropertyMetadata(null));

        public String Text
        {
            get { return (String)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(String), typeof(MyItem), new PropertyMetadata(null));

    }

As stated above, this could be the XAML, since MyObject is a Control, we can add it to a Panel, a grid, for example :

<Grid>
           <myNs:MyObject>
                <myNs:MyItem Text="Item 1">
                    <myNs:MyChild Text="Child of Item 1"/>
                </myNs:MyItem>
                <myNs:MyItem Text="Item 2"/>
                <myNs:MyItem Text="Item 3"/>
            </myNs:MyObject>
</Grid

Please note that nothing is rendered, this control doesn’t have a visual representation, however, the ArrangeOverride method is called, thus output can be found in the Debug window:

This is a MyObject
This is a MyItem 1 with text Item 1
And with child Child of Item 1
This is a MyItem 2 with text Item 2
This is a MyItem 3 with text Item 3

Some final notes, first is that a control can only have one piece of content, it can be a DependencyCollection, this allows you to add multiple elements to the control.

Also, note that Items and Child are not strongly typed, they are DependencyObjectCollection and DependencyObject respectively. This requires you to cast the content to a MyItem and MyChild. You could create your own DependencyObjectCollection, MyItemCollection, for example. But that’s a refinement for another day.

Keep on XAML’n 😉

Creating a bootable USB recovery disk for Surface Pro 2

With Windows 10 (Technical/Insider) preview emerging everywhere on the web, you might just want to do a clean install of the OS on your SP2.

I’ve tried several times in order to get it right, here’s what you need to do to create a bootable USB disk.

First off, i’d recommend a 8GB USB2.0 disk or higher, USB3.0 will speed things up tremendously.

Make sure you have the ISO of the OS you want to install, mount the ISO using your favorite ISO mounting tool, also, write down the product key.

This is a sample setup :

  • ISO to install : Windows 10 Insider Preview Build 10074
  • OS that will create the USB bootable disk : Windows 8.1 PRO
  • USB disk : 32GB USB3.0
  • Product Key Windows 10 Insider Preview Build 10074
  • Drive letter with the mounted ISO : D:\
  • Drive letter with the USB disk : E:\

These are the steps :

  1. Insert the USB disk into a Windows 8, 8.1 or 10 machine.
  2. Run command prompt as an administrator, WINDOWS-KEY + R, type ‘cmd’ press enter
  3. type ‘diskpart’ in the command prompt
  4. type ‘list disk’ to sum up the disks on your system
  5. Make sure your USB disk is shown in the list
  6. type ‘select disk X’ where X is your USB disk
  7. Now type the following commands, these will WIPE THE DISK and copy the contents of the ISO to the USB disk
    1. clean
    2. create partition primary
    3. select partition 1
    4. active
    5. format quick fs=fat32
    6. assign
    7. xcopy D:\* E:\ /s /e
  8. At this point the command prompt will start copying all of the files from the ISO to the USB disk

We’re not done yet, you’ll need to reboot the Surface Pro 2 from the USB disk. These are the requirements in order to do this :

  • You need a bootable USB disk formatted as FAT32
  • Disable secure boot

We now have the bootable USB disk, to disable secure boot, you need to enter the BIOS setting of the Surface Pro 2 like so :

  1. Shut down the SP2
  2. Hold volume up
  3. Press and release the power button to boot the SP2
  4. When the Surface logo appears, release the volume up button

You are now in the BIOS of the SP2, disable secure boot and reboot the device.

I’m not sure if you will experience this, when secure boot was disabled, the boot screen of my SP2 turned RED. You can re-enable secure boot after installing the OS.

Now to install the OS.

Turn off your SP2 (by pressing and holding the power button for 10 seconds, for example).

Boot from USB :

  1. Press and hold volume down button
  2. Press and release power button
  3. When you see the Surface logo, release the volume down button
  4. Your USB drive will start lighting up and the installation process will start

The installation footprint of a clean Windows 10 Insider Preview installation was 11GB, which is reasonable, I now have a lot more space on my disk to use thanks to a clean install! =)

Success on installing your new OS from a bootable USB drive on your SP2!

Finding Parent, Child, Children and Sibling controls in XAML for WinRT

A little while ago, I posted some solutions to common problems in developing apps for WinRT. Which I solved using Behaviors (Blend Behaviors SDK).

These approaches used a class called ControlHelper, while the functionality was sufficient, I was in need for something more thorough.

So, I’ve updated the ControlHelper to support the following functionality :

    • Find the Page of an element
    • Find the Parent based on a type of an element
    • Find the Parent based on a type and/or condition of an element
    • Find all the children based on a type and/or condition of an element
    • Find a sibling of an element, based on a type and/or condition

    Sourcecode for the ControlHelper

    Sample application on github

    controlHelperSample

WinRT Multiline TextBox

I’ve tried using a RichEditBox as an alternative for a multiline TextBox, since this is a very tedious task, I’m going back to the TextBox.

In short, to create a multiline TextBox, just apply this style :

<Style x:Key="MultilineTextBoxStyle" TargetType="TextBox">
<Setter Property="AcceptsReturn" Value="True" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
<Setter Property="Width" Value="Auto" />
</Style>

Behaviors for Windows Apps (Windows 10)

So with the newly released Windows 10 SDK we can start migrating our current Windows 8 / Windows 8.1 / Windows Phone 8.1 apps to the new Universal App Platform or simply UAP.

I was hoping there would be a port for the current Windows 8.1 Behaviors SDK (XAML) but alas, no such thing.

In anticipation for the Windows 10 team to deliver such a library, I’ve migrated the current Microsoft.Xaml.Interactivity.dll to a class library. Which you can use to migrate your current Windows 8.x codebase to Windows 10 UAP :

How does this work ?

Well, I’ve kept the interface and class names the same, so porting should be rather easy.
You will, however, need to change the xmlns declarations from xmlns:interactivity=”using:Microsoft.Xaml.Interactivity” to xmlns:interactivity=”using:Merken.Windev.BehaviorsForTen”.

Example xaml declaration:

<Page
    x:Class="Merken.Windev.BehaviorsForTenTestApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Merken.Windev.BehaviorsForTenTestApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:interactivity="using:Merken.Windev.BehaviorsForTen"
    xmlns:core="using:Merken.Windev.BehaviorsForTen.Core"
    xmlns:behaviors="using:Merken.Windev.BehaviorsForTenTestApp.Behaviors"
    xmlns:actions="using:Merken.Windev.BehaviorsForTenTestApp.Actions"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Content="Tap me!" Grid.Row="0">
            <interactivity:Interaction.Behaviors>
                <behaviors:ItemTappedBehavior>
                    <behaviors:ItemTappedBehavior.Actions>
                        <actions:ShowMessageDialogAction/>
                    </behaviors:ItemTappedBehavior.Actions>
                </behaviors:ItemTappedBehavior>
            </interactivity:Interaction.Behaviors>
        </Button>
        <Button Content="Invoke me!" Grid.Row="1">
            <interactivity:Interaction.Behaviors>
                <core:EventTriggerBehavior EventName="Click">
                    <core:InvokeCommandAction Command="{Binding ClickCommand}"/>
                </core:EventTriggerBehavior>
            </interactivity:Interaction.Behaviors>
        </Button>
        <TextBlock Grid.Row="2" Text="{Binding Clicked}"/>
    </Grid>
</Page>

Example custom behavior :

using Merken.Windev.BehaviorsForTen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace Merken.Windev.BehaviorsForTenTestApp.Behaviors
{
    public class ItemTappedBehavior : BehaviorBase<FrameworkElement>
    {
        protected override void ElementAttached()
        {
            base.ElementAttached();
            AssociatedElement.Tapped += AssociatedElementTapped;
        }

        protected override void ElementDetached()
        {
            AssociatedElement.Tapped += AssociatedElementTapped;
            base.ElementDetached();
        }

        private void AssociatedElementTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            foreach (IAction action in Actions)
                action.Execute(this, null);
        }

        public ActionCollection Actions
        {
            get { return (ActionCollection)GetValue(ActionsProperty); }
            set { SetValue(ActionsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Actions.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ActionsProperty =
            DependencyProperty.Register("Actions", typeof(ActionCollection), typeof(ItemTappedBehavior), new PropertyMetadata(new ActionCollection()));
    }
}

BehaviorBase is a abstract helper class which you can derive from, it provides the plumbing of a custom behavior, such as deriving from DependencyObject and associating the attached element.

The same goes for ActionBase.

It isn’t required to derive from these base classes, however it would speed up you development when creating new behaviors.

For your migrated behaviors, you can still use the IBehavior interface and provide the implementation yourself.

TL;DR
Just check out the sample application : https://github.com/merken/BehaviorsForTen/tree/master/Merken.Windows.BehaviorsForTenTestApp

Disclaimer
I haven’t ported the Microsoft.Xaml.Interactions.Core namespace, yet. So hold yer horses.

*EDIT*
I’ve ported the following classes from the core namespace :

  • DataTriggerBehavior
  • EventTriggerBehavior
  • InvokeCommandAction

Make sure to check out the example app : https://github.com/merken/BehaviorsForTen/tree/master/Merken.Windows.BehaviorsForTenTestApp

Cheers!

A decent ISupportIncrementalLoading example for Windows 8.1 (Phone, WinRT)

I’ve been looking for good example of ISupportIncrementalLoading and i’ve found most of the examples to be either incomplete or not suitable for an MVVM scenario.

You can find an example that supports the following functionality below :

  • Incrementally loading items via a service using MVVM
  • Supports clearing the incrementalcollection
  • Using the VirtualizedStackPanel as an ItemsPanel, to support virtualization
  • Having a footer for the listview, since footers don’t work when you’re using a VirtualizingStackPanel
  • The scrolled offset will remain in memory via the ISupportScrolling interface

An example of the solution :

ISupportIcrementalScrolling

The project can be found on GitHub : https://github.com/merken/ISupportIncrementalLoadingExample.git

IScrollable Interface

    public interface IScrollable
    {
        float VerticalOffset { get; set; }

        float HorizontalOffset { get; set; }

        float ZoomFactor { get; set; }
    }

ScrollableObservableCollection

    public class ScrollableObservableCollection<T> : ObservableCollection<T>, IScrollable
    {
        public ScrollableObservableCollection()
            : base() { }

        public ScrollableObservableCollection(IEnumerable<T> collection)
            : base(collection) { }

        private float verticalOffset = 1.0f;

        public float VerticalOffset { get { return verticalOffset; } set { verticalOffset = value; } }

        private float horizontalOffset = 0.0f;

        public float HorizontalOffset { get { return horizontalOffset; } set { horizontalOffset = value; } }

        private float zoomFactor = 1.0f;

        public float ZoomFactor { get { return zoomFactor; } set { zoomFactor = value; } }
    }

IIncrementalCollection interface

    public interface IIncrementalCollection
    {
        int ItemCount { get; }
        int IndexOfItem(object item);
    }

IIncrementalSource interface

    public interface IIncrementalSource<T>
    {
        bool HasMoreItemsFromServer { get; }

        Task<IEnumerable<T>> GetMoreItems(int pageIndex, int pageSize);

        void Reset();
    }

IncrementalCollection

    public class IncrementalCollection<T, I> : ObservableCollection<I>, IIncrementalCollection, IScrollable, ISupportIncrementalLoading, INotifyPropertyChanged
        where T : IIncrementalSource<I>
        where I : class
    {
        private T source;
        private int itemsPerPage;
        private int currentPage;
        private int itemCount = 0;

        public bool HasMoreItems
        {
            get;
            private set;
        }

        public int ItemCount
        {
            get { return itemCount; }
            private set { itemCount = value; RaisePropertyChanged(); }
        }

        public int IndexOfItem(object item)
        {
            var itemOfI = item as I;
            return this.IndexOf(itemOfI);
        }

        public event EventHandler<HasMoreItemsEventArgs> HasMoreItemsChanged;

        public IncrementalCollection()
        {
        }

        public IncrementalCollection(T source, int itemsPerPage = 20)
        {
            this.source = source;
            this.itemsPerPage = itemsPerPage;
            this.HasMoreItems = true;
        }

        public Windows.Foundation.IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            CoreDispatcher dispatcher = Window.Current.CoreWindow.Dispatcher;
            return AsyncInfo.Run(async code =>
            {
                uint resultCount = 0;
                bool checkMoreItems = source.HasMoreItemsFromServer;
                if (checkMoreItems)
                {
                    var result = await source.GetMoreItems(currentPage, itemsPerPage);
                    currentPage++;
                    if (result != null && result.Count() == 0)
                    {
                        ItemCount = 0;
                        HasMoreItems = false;
                        if (HasMoreItemsChanged != null)
                            HasMoreItemsChanged(this, new HasMoreItemsEventArgs { HasMoreItems = HasMoreItems });
                    }
                    else
                    {
                        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            HasMoreItems = source.HasMoreItemsFromServer;
                            resultCount = (uint)result.Count();
                            ItemCount += (int)resultCount;

                            foreach (I item in result)
                                this.Add(item);
                        });
                    }
                    return new LoadMoreItemsResult()
                    {
                        Count = resultCount
                    };
                }
                else
                {
                    HasMoreItems = false;
                    if (HasMoreItemsChanged != null)
                        HasMoreItemsChanged(this, new HasMoreItemsEventArgs { HasMoreItems = HasMoreItems });
                    return new LoadMoreItemsResult()
                    {
                        Count = 0
                    };
                }
            });
        }

        protected override void ClearItems()
        {
            this.currentPage = 0;
            this.HasMoreItems = true;
            this.ItemCount = 0;
            this.source.Reset();
            if (HasMoreItemsChanged != null)
                HasMoreItemsChanged(this, new HasMoreItemsEventArgs { HasMoreItems = this.HasMoreItems });
            base.ClearItems();
        }

        private float verticalOffset = 1.0f;

        public float VerticalOffset { get { return verticalOffset; } set { verticalOffset = value; } }

        private float horizontalOffset = 0.0f;

        public float HorizontalOffset { get { return horizontalOffset; } set { horizontalOffset = value; } }

        private float zoomFactor = 1.0f;

        public float ZoomFactor { get { return zoomFactor; } set { zoomFactor = value; } }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged([CallerMemberName] string caller = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(caller));
            }
        }
    }

FooterTemplateSelector

    public class FooterTemplateSelector : DataTemplateSelector
    {
        public DataTemplate Template { get; set; }

        public DataTemplate FooterTemplate { get; set; }

        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            DataTemplate template = Template;

            var listViewItem = container as ListViewItem;
            if (listViewItem != null)
            {
                var listView = ControlHelper.FindParent<ListViewBase>(listViewItem);
                if (listView != null)
                {
                    bool hasMoreItems = false;
                    if (listView.ItemsSource is ISupportIncrementalLoading)
                        hasMoreItems = (listView.ItemsSource as ISupportIncrementalLoading).HasMoreItems;
                    if (!hasMoreItems)
                    {
                        if (listView.ItemsSource is IIncrementalCollection)
                        {
                            var incrementalCollection = listView.ItemsSource as IIncrementalCollection;
                            if (incrementalCollection.IndexOfItem(listViewItem.DataContext) == incrementalCollection.ItemCount - 1)
                                template = FooterTemplate;
                        }
                    }
                }
            }
            return template;
        }
    }

FooSource

    public class FooSource : IIncrementalSource<Foo>
    {
        private readonly Func<int, int, Task<FooResponse>> getFoos;

        private bool hasMoreItemsFromServer = true;
        public bool HasMoreItemsFromServer { get { return hasMoreItemsFromServer; } private set { hasMoreItemsFromServer = value; } }

        public FooSource() //Default ctor
        {
        }

        public FooSource(Func<int, int, Task<FooResponse>> getFoos)
        {
            this.getFoos = getFoos;
        }
        
        public async Task<IEnumerable<Foo>> GetMoreItems(int pageIndex, int pageSize)
        {
            var fooResponse = await getFoos(pageIndex, pageSize);
            if (fooResponse != null)
            {
                //If you want this call to be fired only ONCE, set this bool to FALSE
                //HasMoreItemsFromServer = false;
                //Other wise the server will provide us with a bool if more items are available
                HasMoreItemsFromServer = fooResponse.HasMoreItems;
                return fooResponse.Foos;
            }
            return new List<Foo>();//Return empty foos
        }

        public void Reset()
        {
            HasMoreItemsFromServer = true;
        }
    }

Put Page navigationmode cache to disabled:

this.NavigationCacheMode = NavigationCacheMode.Disabled;

The MainViewModel class

    public class MainViewModel : BaseViewModel
    {
        private readonly FooService fooService;
        private FooSource fooSource;
        private GroupedFooSource groupedFooSource;

        private bool noMoreFoos;
        public bool NoMoreFoos
        {
            get
            {
                return noMoreFoos;
            }
            set
            {
                this.noMoreFoos = value;
                RaisePropertyChanged();
            }
        }

        private bool noMoreGroupedFoos;
        public bool NoMoreGroupedFoos
        {
            get
            {
                return noMoreGroupedFoos;
            }
            set
            {
                this.noMoreGroupedFoos = value;
                RaisePropertyChanged();
            }
        }

        private IncrementalCollection<FooSource, Foo> foos;

        public IncrementalCollection<FooSource, Foo> Foos
        {
            get { return foos; }
            set
            {
                foos = value;
                RaisePropertyChanged();
            }
        }

        private IncrementalCollection<GroupedFooSource, GroupModel<String, Foo>> groupedFoos;

        public IncrementalCollection<GroupedFooSource, GroupModel<String, Foo>> GroupedFoos
        {
            get { return groupedFoos; }
            set
            {
                groupedFoos = value;
                RaisePropertyChanged();
            }
        }

        private ScrollableObservableCollection<Foo> scrollableFoos;

        public ScrollableObservableCollection<Foo> ScrollableFoos
        {
            get { return scrollableFoos; }
            set
            {
                scrollableFoos = value;
                RaisePropertyChanged();
            }
        }

        public RelayCommand ClearCommand { get; set; }
        public RelayCommand AboutCommand { get; set; }

        public MainViewModel()
        {
            fooService = new FooService();
            ClearCommand = new RelayCommand(() =>
            {
                this.Foos.Clear();
                this.GroupedFoos.Clear();
            });

            AboutCommand = new RelayCommand(() =>
            {
                var navigationService = ServiceLocator.Current.GetInstance<NavigationService>();

                navigationService.Navigate(typeof(AboutPage), null);
            });
        }

        public override async void Initialize(object param)
        {
            if (!IsLoaded)
            {
                InitializeFooSource();
                InitializeGroupedFooSource();
                await InitializeScrollableFoosAsync();
                IsLoaded = true;
            }
        }

        private void InitializeFooSource()
        {
            NoMoreFoos = false;
            fooSource = new FooSource(async (currentPage, itemsPerPage) =>
            {
                FooResponse response = null;
                try
                {
                    IsLoading = true;
                    response = await fooService.GetFoos(currentPage, itemsPerPage);
                }
                catch (Exception ex)//Something completely unexpected happened, write a debug line to ensure persistence of the error
                {
                    //TODO ERROR HANDLING
                }
                finally
                {
                    IsLoading = false;//Hide the progressbar
                }
                return response;
            });

            this.Foos = new IncrementalCollection<FooSource, Foo>(fooSource);
            this.Foos.HasMoreItemsChanged += (s, hasm) =>
            {
                this.NoMoreFoos = !hasm.HasMoreItems;
            };
        }

        private void InitializeGroupedFooSource()
        {
            NoMoreGroupedFoos = false;
            groupedFooSource = new GroupedFooSource(async (currentPage, itemsPerPage) =>
            {
                GroupedFooResponse response = null;
                try
                {
                    IsLoading = true;
                    response = await fooService.GetGroupedFoos(currentPage, itemsPerPage);
                }
                catch (Exception ex)//Something completely unexpected happened, write a debug line to ensure persistence of the error
                {
                    //TODO ERROR HANDLING
                }
                finally
                {
                    IsLoading = false;//Hide the progressbar
                }
                return response;
            });

            this.GroupedFoos = new IncrementalCollection<GroupedFooSource, GroupModel<string, Foo>>(groupedFooSource);
            this.GroupedFoos.HasMoreItemsChanged += (s, hasm) =>
            {
                this.NoMoreGroupedFoos = !hasm.HasMoreItems;
            };
        }

        private async Task InitializeScrollableFoosAsync()
        {
            try
            {
                IsLoading = true;
                var response = await fooService.GetFoos(0, 999);
                ScrollableFoos = new ScrollableObservableCollection<Foo>(response.Foos);
            }
            catch (Exception ex)//Something completely unexpected happened, write a debug line to ensure persistence of the error
            {
                //TODO ERROR HANDLING
            }
        }
        public override void GoBack()
        {
            var navigationService = ServiceLocator.Current.GetInstance<NavigationService>();
            navigationService.GoBack();
        }
    }

Take a look at the full solution here (rename to .zip to unpack) :
ISupportIncrementalLoadingExample

Full screen Flyout on WinRT Phone 8.1

Flyouts in WinRT are a way for you to add additional information to FrameworkElements in a modal way.

They can be used for various reasons :

  • Showing feedback when an element gets focus, or any event takes place
  • To replace the ComboBox control, by adding a ListView to select an item
  • To replace the MessageDialog control so you can add a custom interface

Now there are these drawbacks on using the Flyout :

  • Appbar of the page does not automatically hides when showing a Flyout in Full Placement
  • Flyout does not close when an item is selected
  • Nested listviews are not scrollable inside the Flyout

What we will achieve :

FullFlyoutBehavior

How this is setup:

  • Give the root element the name “layoutRoot”
  • Create two behaviors (FlyoutFullPageBehavior and AppBarFlyoutBehavior)
  • Add a reference to the behaviors namespace in your page
  • Implement the XAML snippet below
                        <Button.Flyout>
                            <Flyout Placement="Full">
                                <i:Interaction.Behaviors>
                                    <behaviors:FlyoutFullPageBehavior Parent="{Binding ElementName=layoutRoot}" />
                                    <behaviors:AppBarFlyoutBehavior Parent="{Binding ElementName=layoutRoot}" />
                                </i:Interaction.Behaviors>
                                <!-- Flyout Content here -->
                            </Flyout>
                        </Button.Flyout>

AppBarFlyoutBehavior.cs

public class AppBarFlyoutBehavior : DependencyObject, IBehavior
    {
        private Flyout element = null;

        public DependencyObject AssociatedObject
        {
            get { return element; }
        }

        public FrameworkElement Parent
        {
            get { return GetValue(ParentProperty) as FrameworkElement; }
            set { SetValue(ParentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for EmptyDataTemplate.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ParentProperty =
            DependencyProperty.Register("Parent", typeof(FrameworkElement), typeof(AppBarFlyoutBehavior), new PropertyMetadata(null, ParentPropertyChanged));

        private static void ParentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = (AppBarFlyoutBehavior)d;
            behavior.Parent = (FrameworkElement)e.NewValue;
        }

        public void Attach(DependencyObject associatedObject)
        {
            if (associatedObject as Flyout == null)
                throw new NotSupportedException("The associated object must be of type Flyout");
            element = associatedObject as Flyout;
            element.Opened += FlyoutOpened;
            element.Closed += FlyoutClosed;
        }

        private void FlyoutOpened(object sender, object e)
        {
            ShowAppBar(false);
        }

        private void FlyoutClosed(object sender, object e)
        {
            ShowAppBar(true);
        }

        private void ShowAppBar(bool show)
        {
            if (Parent != null)
            {
                var page = ControlHelper.GetParentPage(Parent);
                if (page != null && page.BottomAppBar != null)
                {
                    if (show)
                        page.BottomAppBar.Visibility = Visibility.Visible;
                    else
                        page.BottomAppBar.Visibility = Visibility.Collapsed;
                }
            }
        }

        public void Detach()
        {
            element.Opened -= FlyoutOpened;
            element.Closed -= FlyoutClosed;
        }
    }

FlyoutFullPageBehavior.cs

public class FlyoutFullPageBehavior : DependencyObject, IBehavior
    {
        private Flyout element = null;
        private double correction = 26;

        public DependencyObject AssociatedObject
        {
            get { return element; }
        }

        public FrameworkElement Parent
        {
            get { return GetValue(ParentProperty) as FrameworkElement; }
            set { SetValue(ParentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for EmptyDataTemplate.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ParentProperty =
            DependencyProperty.Register("Parent", typeof(FrameworkElement), typeof(FlyoutFullPageBehavior), new PropertyMetadata(null, ParentPropertyChanged));

        private static void ParentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = (FlyoutFullPageBehavior)d;
            behavior.Parent = (FrameworkElement)e.NewValue;
        }

        public void Attach(DependencyObject associatedObject)
        {
            if (associatedObject as Flyout == null)
                throw new NotSupportedException("The associated object must be of type Flyout");
            element = associatedObject as Flyout;
            element.Opened += FlyoutOpened;
        }

        private void FlyoutOpened(object sender, object e)
        {
            if (element.Placement == FlyoutPlacementMode.Full)
            {
                Style flyoutPresenterStyle = Application.Current.Resources["FlyoutFullPageBehaviorStyle"] as Style;
                if (flyoutPresenterStyle == null)
                    flyoutPresenterStyle = new Style(typeof(FlyoutPresenter));
                var scrollSetter = new Setter(ScrollViewer.VerticalScrollModeProperty, ScrollMode.Disabled);
                if (flyoutPresenterStyle.Setters.Contains(scrollSetter))
                    flyoutPresenterStyle.Setters.Add(scrollSetter);
                element.FlyoutPresenterStyle = flyoutPresenterStyle;

                var content = element.Content as FrameworkElement;
                var page = ControlHelper.GetParentPage(Parent);
                if (page != null)
                {
                    page.SizeChanged += PageSizeChanged;

                    content.HorizontalAlignment = HorizontalAlignment.Stretch;
                    content.VerticalAlignment = VerticalAlignment.Stretch;
                    AppyHeightToFlyoutContent(element, page.ActualHeight, correction);
                }
            }
        }

        private void AppyHeightToFlyoutContent(Flyout flyout, double height, double correction)
        {
            var content = flyout.Content as FrameworkElement;
            if (content != null)
                content.Height = height - correction;
        }

        private void PageSizeChanged(object sender, SizeChangedEventArgs e)
        {
            var page = sender as Page;
            AppyHeightToFlyoutContent(element, page.ActualHeight, correction);
        }

        public void Detach()
        {
            element.Opened -= FlyoutOpened;

            var page = ControlHelper.GetParentPage(Parent);
            if (page != null)
            {
                page.SizeChanged -= PageSizeChanged;
            }
        }
    }

The flyout can be styled using the following XAML style

    <Style x:Key="FlyoutFullPageBehaviorStyle" TargetType="FlyoutPresenter">
        <Setter Property="Foreground" Value="Red" />
        <Setter Property="Background" Value="Green" />
    </Style>

Using this setup, you’ll be now able to show full page flyouts as if they where pop-ups. The appbar will become hidden when the flyout is visible.

Lets say we want to hide the flyout after an event has happened, a selection event in a listview, for example.

Then we could use the following behavior to close the flyout upon the click event of a listview.

Consider the following flyout for a button :

                    <Button>
                        <Button.Flyout>
                            <Flyout Placement="Full">
                                <i:Interaction.Behaviors>
                                    <behaviors:FlyoutFullPageBehavior Parent="{Binding ElementName=layoutRoot}" />
                                    <behaviors:AppBarFlyoutBehavior Parent="{Binding ElementName=layoutRoot}" />
                                </i:Interaction.Behaviors>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto" />
                                        <RowDefinition Height="*" />
                                    </Grid.RowDefinitions>
                                    <TextBlock Margin="20,12,0,0"
                                               Text="Select an item below :" />
                                    <ListView Grid.Row="1"
                                              IsItemClickEnabled="True"
                                              ItemsSource="{Binding Items,
                                                                    Mode=OneWay}"
                                              SelectedItem="{Binding SelectedItem,
                                                                     Mode=TwoWay}">
                                        <i:Interaction.Behaviors>
                                            <behaviors:FlyoutListViewItemClickBehavior ListItemClickedCommand="{Binding ItemSelectedCommand}" />
                                        </i:Interaction.Behaviors>
                                        <ListView.ItemContainerStyle>
                                            <Style TargetType="ListViewItem">
                                                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                                            </Style>
                                        </ListView.ItemContainerStyle>
                                    </ListView>
                                </Grid>
                            </Flyout>
                        </Button.Flyout>
                    </Button>

BehaviorBase.cs

 public abstract class BehaviorBase<T> : DependencyObject, IBehavior where T : FrameworkElement
    {
        private T element;

        /// <summary
        /// !Important!
        /// Whenever you define Dependency Properties on Behaviors (or any DependencyObject for that matter), you need to set a private static function to act on PropertyMetadata changed.
        /// Since this is static, this can be executed multiple times from DependencyObjects that are not part of the main UI thread anymore
        /// So whenever you want to change something on the UI thread or push changes of bindingexpressions to the source, you need to surround it with an if-check:
        /// if(IsActive){
        /// //your UI and bindingexpression code here
        /// }
        /// </summary>
        private bool isActive = false;

        public bool IsActive
        {
            get
            {
                return isActive;
            }
            set
            {
                isActive = value;
            }
        }

        public T AssociatedElement { get { return element; } }

        public DependencyObject AssociatedObject { get { return element; } }

        public void Attach(DependencyObject associatedObject)
        {
            if (associatedObject as T == null)
                throw new NotSupportedException("The associated object must be of type " + typeof(T).Name);
            element = associatedObject as T;
            ElementAttached();
        }

        protected virtual void ElementAttached()
        {
            element.Loaded += ElementLoaded;
            isActive = true;
        }

        protected virtual void ElementLoaded(object sender, RoutedEventArgs e)
        {
            var page = ControlHelper.GetParentPage(element);
            if (page != null && page.NavigationCacheMode == NavigationCacheMode.Disabled)//Subcribe to the unloading event to handle state
                page.Unloaded += PageUnloaded;
        }

        private void PageUnloaded(object sender, RoutedEventArgs e)
        {
            this.Detach();
        }

        public void Detach()
        {
            ElementDetached();
            isActive = false;
        }

        protected virtual void ElementDetached()
        {
            var page = ControlHelper.GetParentPage(element);
            if (page != null && page.NavigationCacheMode == NavigationCacheMode.Disabled)//Subcribe to the unloading event to handle state
                page.Unloaded -= PageUnloaded;
            element.Loaded -= ElementLoaded;
        }
    }

ControlHelper.cs

public static class ControlHelper
    {
        public static Page GetParentPage(FrameworkElement elem)
        {
            var parent = elem.Parent;
            var parentPage = (parent as Page);
            while (parentPage == null && parent != null)
            {
                parent = (parent as FrameworkElement).Parent;
                parentPage = (parent as Page);
            }
            return parentPage;
        }

        public static T FindParent<T>(DependencyObject element) where T : FrameworkElement
        {
            FrameworkElement parent = VisualTreeHelper.GetParent(element) as FrameworkElement;

            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                    return correctlyTyped;
                else
                    return FindParent<T>(parent);
            }

            return null;
        }

        public static T FindChild<T>(FrameworkElement element) where T : FrameworkElement
        {
            int childCount = VisualTreeHelper.GetChildrenCount(element);
            for (int c = 0; c < childCount; c++)
            {
                FrameworkElement child = VisualTreeHelper.GetChild(element, c) as FrameworkElement;
                if (child != null)
                {
                    T correctlyTyped = child as T;
                    if (correctlyTyped != null)
                        return correctlyTyped;
                    else
                        return FindChild<T>(child);
                }
            }
            return null;
        }
    }

FlyoutListViewItemClickBehavior.cs

public class FlyoutListViewItemClickBehavior : BehaviorBase<ListViewBase>
    {
        public event EventHandler ItemClicked;

        protected override void ElementAttached()
        {
            base.ElementAttached();
            if (!AssociatedElement.IsItemClickEnabled)
                throw new NotSupportedException("Please set IsItemClickEnabled to true on the ListView!");
            AssociatedElement.ItemClick += listView_ItemClick;
        }

        protected override void ElementDetached()
        {
            base.ElementDetached();
            AssociatedElement.ItemClick -= listView_ItemClick;
        }

        private void listView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var parentFlyout = ControlHelper.FindParent<FlyoutPresenter>(AssociatedElement);
            if (parentFlyout != null)
            {
                if (parentFlyout.Parent is Popup)
                {
                    Popup popUp = parentFlyout.Parent as Popup;
                    AssociatedElement.SelectedItem = e.ClickedItem;//Trigger the SelectedItem binding
                    popUp.IsOpen = false;//close the popup
                    if (ListItemClickedCommand != null)
                        ListItemClickedCommand.Execute(e.ClickedItem);
                    if (ItemClicked != null)
                        ItemClicked(e.ClickedItem, EventArgs.Empty);
                }
            }
        }

        public ICommand ListItemClickedCommand
        {
            get
            {
                return (ICommand)base.GetValue(FlyoutListViewItemClickBehavior.ListItemClickedCommandProperty);
            }
            set
            {
                base.SetValue(FlyoutListViewItemClickBehavior.ListItemClickedCommandProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ListItemClickedCommandProperty =
            DependencyProperty.Register("ListItemClickedCommand", typeof(ICommand), typeof(FlyoutListViewItemClickBehavior), new PropertyMetadata(null, OnListItemClickedCommandPropertyChanged));

        private static void OnListItemClickedCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = (FlyoutListViewItemClickBehavior)d;
            if (behavior.IsActive)
                behavior.ListItemClickedCommand = (ICommand)e.NewValue;
        }
    }
}

Source code (rename to .zip to unpack) :
FlyoutApp

Async await IQueryable

Usage :

                var user = (await db.WishlistUsers.Where(u => u.ID == wishlistUser.ID).ExecuteAsync()).FirstOrDefault();
                if (user == null)
                    throw new ArgumentException("User not found...");

Source :

using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using System.Threading.Tasks;

namespace Linqy
{
    public static class AsynchronousQueryExecutor
    {
        public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other,
                                                                            Func<T, TKey> getKey)
        {
            return from item in items
                   join otherItem in other on getKey(item)
                   equals getKey(otherItem) into tempItems
                   from temp in tempItems.DefaultIfEmpty()
                   where ReferenceEquals(null, temp) || temp.Equals(default(T))
                   select item;

        }

        public static Task<IEnumerable<T>> ExecuteAsync<T>(this IEnumerable<T> query)
        {
            TaskCompletionSource<IEnumerable<T>> tcs = new TaskCompletionSource<IEnumerable<T>>();
            Call<T>(query,
                (result) =>
                {
                    tcs.SetResult(result);
                },
                (exception) =>
                {
                    tcs.SetException(exception);
                });
            return tcs.Task;
        }

        private static void Call<T>(IEnumerable<T> query, Action<IEnumerable<T>> callback, Action<Exception> errorCallback)
        {
            Func<IEnumerable<T>, IEnumerable<T>> func =
                new Func<IEnumerable<T>, IEnumerable<T>>(InnerEnumerate<T>);
            IEnumerable<T> result = null;
            IAsyncResult ar = func.BeginInvoke(
                                query,
                                new AsyncCallback(delegate(IAsyncResult arr)
                                {
                                    try
                                    {
                                        result = ((Func<IEnumerable<T>, IEnumerable<T>>)((AsyncResult)arr).AsyncDelegate).EndInvoke(arr);
                                    }
                                    catch (Exception ex)
                                    {
                                        if (errorCallback != null)
                                        {
                                            errorCallback(ex);
                                        }
                                        return;
                                    }
                                    //errors from inside here are the callbacks problem
                                    //I think it would be confusing to report them
                                    callback(result);
                                }),
                                null);
        }

        private static IEnumerable<T> InnerEnumerate<T>(IEnumerable<T> query)
        {
            foreach (var item in query) //the method hangs here while the query executes
            {
                yield return item;
            }
        }
    }
}