0 Comments

Overview of UWP Apps Platforms

With UWP apps it has become easier then ever to write a single app that will run natively on all Windows 10 devices be it a phone, tablet, PC, Xbox et. al. Now we don’t just want our apps to be able to run on a device we want them to shine while they are running. In this blog post we will look at the basics on how to adopt to different screen sizes within your UWP app.

 

The devices and screen sizes

UWP runs on many different platforms some might not even come with a screen by default e.g. Internet of Things (IoT) devices or others that require a unique UI such as HoloLens which should be available for a few lucky developers later this year. Now while those platforms are very interesting in certain scenarios a wide array of apps will most probably be developed for mobile devices such as phones, tablets and phablets aka BAPHs (Big a** Phones). The unique thing about the UWPs in comparison to Android and iOS apps is that you apps will not only run on mobile devices but on desktop machines, laptops and even larger screens such as the new Surface Hub.

Windows 10 Devices
Now write once run everywhere and look like crap is easy to do. But the great benefit of creating a UWP app is that you can adopt to the different screen sizes and even adopt to different user input such as touch vs mouse and keyboard. But before we dive into the details of how we can write responsive UIs with XAML lets have a look at some basic layout rules.

Devices and screen sizes

A general split up of the devices can be made as follows.

CategoryScreen sizeWidth in Effective PixelsInputs
Phone4” to 6”340+Touch & Voice
Phablet6+” to 7”720+Touch & Voice
Tablet7” to 13.3”1024+Toch, Stylus, External keyboard*, Mouse*, Voice*
PCs and Laptops13” and greater1024+Mouse, Keyboard, Touch*, Gamepads
Surface Hub Devices55” and 84”1024+Touch, Pen, Voice, Keyboard, remote Touchpad

*: occasionally

Basic layout guides

Since UWP apps are built from the ground up to run on all kinds of different devices i.e. form factors the platform comes with many helpers that make life easier to design for multiple platforms. One basic concept are effective pixels. Effective pixels differ from actual physical pixels so 24 effective pixels on a phone will scale up to a larger physical appearance on a larger screen. The scaling of effective to physical pixels is all done by the framework and does not require any special attendance by the developer i.e. designer.

Image showing the diferent scale factors accroding to the device.

Note: Often small screens do have very large Dots Per Inch (DPI), this is also handled by the platform so even if you are running on a small device with a cheap display i.e. low DPI the text will still be readable as clearly as on a higher end display with more pixels i.e. a higher DPI.

The scaling is based on multiple of fours (4), so when defining layouts make sure they are a multiple of four e.g. 16. This will ensure that the scaling will not lead to strange effects. When using icons, rather than using images try to use a font (for example the new Segoe MDL2 Assets) that provides the icon you are looking for (or close enough). Though Windows 10 does provide a mechanism that chooses between different resolutions of an image according to the screen size, a font will always scale without any further effort.

Implementing responsive layouts that adapt to the available screen space

When working with different resolutions there are multiple layout adjustments that can be performed to improve general User Experience (UX) and – Interaction. UWP offer a variety of ways to adjust the layout of an app according to the available screen space.

  1. Changing layout of elements on a page according to form factor and available screen space
  2. Reflow e.g. adding text columns when the screen size increases
  3. Reveal information/functionality depending on the device and it’s resolution
  4. Replace elements such as navigation bars with fly out menus to accommodate smaller screen estate
  5. Change screen flow e.g. of master detail sites

So lets dive into how we can change the layout of UI elements according to the screen space.

Responsive Layout

ResponsiveDesign

One new feature of UWP apps is the possibility to adapt the layout of the controls according the available screen size i.e. the effective pixels width of the app windows. This lets the UI adapt to different screen sizes e.g. phones and tablets but also lets the UI adapt to the size a Window has on a desktop.

Lets assume you have the following screen flow and layout in your app:

Shows app running with fewer than 720 effective pixels.

The basic Layout of the app looks as follows:

<RelativePanel>
    <Rectangle x:Name="Image" Width="80" Height="80" Fill="Gray" Margin="8"></Rectangle>
    <Rectangle x:Name="TextLine1" Height="16" Width="200" Fill="Gray" RelativePanel.RightOf="Image" RelativePanel.Below="" Margin="8,8,8,4"/>
    <Rectangle x:Name="TextLine2" Height="16" Width="200" Fill="Gray" RelativePanel.RightOf="Image" RelativePanel.Below="TextLine1" RelativePanel.AlignLeftWith="TextLine1" Margin="8,8,8,4"/>
    <Rectangle x:Name="TextLine3" Height="16" Width="168" Fill="Gray" RelativePanel.RightOf="Image" RelativePanel.Below="TextLine2" RelativePanel.AlignLeftWith="TextLine1" Margin="8,8,32,4"></Rectangle>
</RelativePanel>

Note: that rendering the items in a RelativePanel allows the elements within i.e. the Rectangle to align themselves relative to one another. This is a new layout feature available in Windows 10 UWP apps which previously had to be done with a Grid or StackPanel. The benefit of using relative layouts is when we focus on how we might want to realign the content for a different screen(size).

For instance when displayed on a tablet you might not just want to show a small image next to the text but go with a banner. Using a VisualStateManagerone can easily define trigger points for the minimal window Width and  if the trigger fires adopt the layout of the predefined layout:

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup>
        <VisualState x:Name="wideView">
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="720" />
            </VisualState.StateTriggers>
            <VisualState.Setters>
                <Setter Target="Image.(Width)" Value="720"/>
                <Setter Target="TextLine1.(Width)" Value="720"/>
                <Setter Target="TextLine2.(Width)" Value="720"/>
                <Setter Target="TextLine3.(Width)" Value="600"/>
                <Setter Target="TextLine1.(RelativePanel.Below)" Value="Image"/>
                <Setter Target="TextLine1.(RelativePanel.AlignLeftWith)" Value="Image"/>
            </VisualState.Setters>
        </VisualState>
        <VisualState x:Name="narrowView">
            <VisualState.Setters>
                <!-- Adjust view for narrow view -->
            </VisualState.Setters>
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="0" />
            </VisualState.StateTriggers>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

The name of the Target matches the x:Name given to the controls. The page will now re-render if the app has more then 720 effective pixels:

Shows app running with more than 720 effective pixels.

The page will also adjust when resizing the window on a Windows 10 desktop machine which allows the user to have multiple applications open at once with them seamlessly adapting to new windows sizes.

Conclusion

In this post we saw that Universal Windows Platform Apps not only run on multiple devices but that the platform provides the developers and designers with the necessary tooling of creating a great User Experience no matter the screen size and resolution without having to create multiple page layouts from the ground up and having to somehow figure out the size of the screen itself.

You can find the entire project on GitHub.

0 Comments

See how you can offer cross platform APIs based on C# that you can consume in Universal Windows Platform Apps (UWP), Xamarin.iOS, Xamarin.Android, Xamarin.Forms, ASP.Net and even your classic .Net WPF app. In my last post I showed how one can use platform specific libraries and code in a Portable Class Library with dependency injection. This approach is great when you are developing your own app but it gets somewhat quirky, when you want to offer a library to fellow co-workers/developers, as you force them to setup your own library through dependency injection. But there is of course another way that allows you to encapsulate your implementation details neatly while still providing platform specific features to your PCL code.

The library in this blog post will provide the OS version for a UWP, Xamarin.iOS and Xamarin.Android app.

Setting up the library

The library consists of four projects:

  • OSVersion.Core
  • OSVersion.UWP
  • OSVersion.Droid
  • OSVersion.iOS

One thing which is a bit special about all the projects is that all of their Default Namespace and the Assembly name all have the same name.

NamespaceBinaryName

In each project we implement the SystemInformationHandler.cs class, on the PCL we simply implement a stub:

public class SystemInformationHandler
{
    #region Implementation of ISystemInformationHandler

    public static string OSVersion => "Gnabber";

    #endregion
}

For the other platforms such as UWP we implement the calls to the UWP specific APIs:

public class SystemInformationHandler
{
    public static string OSVersion
    {
        get { return OsVersionString(); }
    }

    private static string OsVersionString()
    {
        string sv = AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
        ulong v = ulong.Parse(sv);
        ulong v1 = (v & 0xFFFF000000000000L) >> 48;
        ulong v2 = (v & 0x0000FFFF00000000L) >> 32;
        ulong v3 = (v & 0x00000000FFFF0000L) >> 16;
        ulong v4 = (v & 0x000000000000FFFFL);

        return $"Windows {v1}.{v2}.{v3}.{v4}";
    }
}

So in the end we have implemented the generic class in the PCL and specific classes for each platform we target to support. Now lets see how we can consume this library in an app.

Consuming the library

The app will exist of the usual cross platform mobile app setup which means we will have usual suspects covering Windows, Android and iOS with a Portable Class Library aka Core to share the reusable code.

NativePclProjectOverview

In the core we have our business logic code and view models (I’m a huge fan of the MVVM Light library, to find out more just view my mvvm light posts). In the NativePcl.Core project we have a service OsVersionService.cs for returning the version number:

public class OsVersionService : IOsVersionService
{
    public string GetVersion()
    {
        return SystemInformationHandler.OSVersion;
    }
}

Reference the OSVersion.Core library as binary – DO NOT reference it as project or you will be facing compile errors in one of the next steps. Don’t ask me how I know Winking smile

Because all our assemblies of the OSVersion library will be compiled to assemblies with the same name we can’t just simply reference the project file but have to add the binary i.e. the compiled version of the library. If you are looking at the sample from GitHub, make sure to compile the solution under release build as the OSVersion is referenced via binary in the release output folder of the projects.

The method invokes the OSVersion property in the OSVersion library - leaving out the specific project e.g. UWP intent fully here. On the clients for example the Android app we have a single screen showing the version number defined in the MainView.xaml:

<Page
    x:Class="NativePcl.UWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:NativePcl.UWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="{Binding OSVersion}" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource TitleTextBlockStyle}"></TextBlock>
    </Grid>
</Page>

And the corresponding code behind or as we are using view models MainViewModel.cs:

public class MainViewModel : ViewModelBase
{
    private readonly IOsVersionService _osVersionService;

    public MainViewModel(IOsVersionService osVersionService)
    {
        if (osVersionService == null) throw new ArgumentNullException(nameof(osVersionService));
        _osVersionService = osVersionService;
    }

    public string OSVersion => _osVersionService.GetVersion();
}

If we now run the app we will get the follow output:

coreVersion

Now this is the output we defined in the OSVersion.Core, if we now reference the binary of the OSVersion.UWP in the NativePcl.UWP project things get really interesting. Instead of receiving an error because we are adding two assemblies with the same name the compiler will prefer the platform specific library over the PCL implementation. And even though we never invoke the library directly from our NativePcl.UWP app the OS version returned now is returned from the platform specific i.e. OSVersion.UWP implementation of the GetVersion() method resulting in the following output:

uwpVersion

Now while this approach allows for writing platform independent logic in the PCL and calling platform specific implementations during runtime it is somewhat tedious as it requires that the developer will reference the correct version of the library. And all of them have the same name which is just calling for some frustrated minutes to happen due to referencing the wrong version of the library. Luckily there is a technique that allows to use the approach described above without burdening the developer consuming the library of referencing the binaries correctly. By wrapping the library in a NuGet package consuming the library is as simple as adding the package to all of your projects and the NuGet package manager will just like the build engine prefer to link the platform specific binary over the PCL library to the project. So instead of having to choose which binary to add the developer can now simply add the identical NuGet package to all of the projects and it will just work.

Conclusion

In this post you saw how to create APIs that can be consumed in the PCL and still provide platform specific functionality. For all of this to work we had to set the namespace and assembly of the projects to identical names. On the consumer one can either simply add a NuGet package containing all of the implementations i.e. PCL, UWP, Android and iOS or add the binaries of the corresponding API compilation to the app implementation e.g. OSVersion.Coreto NativePcl.Core.

This approach allows you to create APIs which can be reused across multiple platforms providing the same method definitions across the platforms.

You can find the sample on GitHub. (make sure to compile it first as a release build)

2 Comments

3856456237_f05ebd2602_o

The Portable Class Library (PCL) allows developers to share C#, F# and VB code across multiple devices, platforms and runtime environments such as .Net, Xamarin or Windows Store Apps. In this previous post you can see how you can write portable business logic and integrate it with all the various platforms. But what if you actually want to use something the other way round say the GPS position, file system etc.. What then? This is exactly his post we will look at the following topics:

  • Using Interface Segregation and Dependency Inversion to our favor
    • Interface in the PCL
    • Implementation on the Platform
  • Injecting the implementation at runtime into the PCL
  • Making the resolution of dependencies a breeze with MVVM Light

So lets get to it!

Using Dependency Injection to our favor

Remember SOLID? Well it turns out the last letter stand exactly for the pattern we will be using to solve our “How will I be able to use a platform specific feature cross platform “. The PCL code is platform independent and therefore can be used across multiple platforms, so we want to put near to all of our business logic into a PCL. Further by accessing concrete class implementations via interfaces we can define an Interface in the PCL and create it’s concrete implementation in a platform specific project.

PCLDIOverview

Dependency Injection in action

For example lets say we want to display the current OS version for each platform, this is a very platform specific feature. To access such a information in the PLC we first define an Interface in the PCL that describes the contract the implementation has to implement:

public interface ISystemInformationHandler
{
    string OSVersion { get; }
}

In the concrete platforms we can then inherit the interface and implement the handler which calls the platform specific API (bellow you see the Android implementation):

internal class SystemInformationHandler:ISystemInformationHandler
{
    #region Implementation of ISystemInformationHandler

    //public string OSVersion => System.Environment.OSVersion.ToString();
    public string OSVersion => $"Android {Android.OS.Build.VERSION.SdkInt} {Android.OS.Build.VERSION.Release}";

    #endregion
}

Now in the PCL we can have a class for example a view model that requires the handler to display the information.

public class MainViewModel : ViewModelBase
{
    private readonly ISystemInformationHandler _systemInformationHandler;

    public MainViewModel(ISystemInformationHandler systemInformationHandler)
    {
        if (systemInformationHandler == null) throw new ArgumentNullException(nameof(systemInformationHandler));
        _systemInformationHandler = systemInformationHandler;
    }

    public string OSVersion => _systemInformationHandler.OSVersion;
}

The view model requires as a parameter argument an instance of the IOSVersionHandler interface. So when we create an instance of the MainViewModel in the platform project, we can simply create an instance of interface and pass it into the view model when we create it.

var mainViewModel = new MainViewModel(new SystemInformationHandler());

And receive the following output for e.g. Android:

 

Cross platform Dependency resolution with MVVM Lights

Now resolving all of these dependencies by hand can get very tedious over time. You might have noticed that I’m using MVVM Light which comes with a lightweight Dependency Injection Container called Simple IoC. Lets see how we can use this component to further streamline our cross platform development efforts.

Note:for an introduction to MVVM Light please refer to this blog post for AndroidoriOSto get you started with the basics.

In the PCL we have the ViewModelLocator.cs which defines all of the instances used, but without the platform specific resolution.

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {
            // Create design time view services and models
            SimpleIoc.Default.Register<ISystemInformationHandler, SystemInformationHandlerStub>();
        }

        SimpleIoc.Default.Register<MainViewModel>();
    }

    public MainViewModel Main
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }
}

On each platform we now extend the Locator and register the platform specific classes i.e. resolution for interfaces.

internal class Locator : ViewModelLocator
{
    private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
    public static Locator Instance => _locator.Value;

    private Locator()
    {
        SimpleIoc.Default.Register<ISystemInformationHandler, SystemInformationHandler>();
    }
}

Now we can simply request an instance of the view model (MVVM Light per default only creates one instance for each registered class) and use it. In Android this would look something like this in the MainActivity.cs:

[Activity(Label = "PclDISample.Droid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    #region UI Controls

    private TextView OSVersion => FindViewById<TextView>(Resource.Id.OSVersion);

    #endregion

    private MainViewModel VM => Locator.Instance.Main;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        OSVersion.Text = VM.OSVersion;

        var mainViewModel = new MainViewModel(new SystemInformationHandler());
    }
}

In Windows 10 we can simply set the Datacontext accordingly in XAML:

<Page
    x:Class="PclDISample.UWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PclDISample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="{Binding OSVersion}" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource TitleTextBlockStyle}"></TextBlock>
    </Grid>
</Page>

As you can see once all is registered with the simple Inversion of Control Container (IoC) of MVVM Light all of the dependency resolution will be performed automatically. If a dependency is missing, an exception will be thrown at runtime (not during compilation), so make sure to test all your views, user controls et al that they load correctly.

Conclusion

In this post you saw how you can use Dependency Injection to provide platform specific features to cross platform code located in the PCL without creating any circular dependency errors. By using interfaces in the PCL and injecting the concrete implementations during runtime we can create thin wrappers that provide platform specific features through a generic defined interface. Finally we saw how we can use MVVM Light to create a more manageable and more manageable dependency resolution with the Simple IoC Locator.

You can find the complete sample on GitHub.

Big thanks to Laurent Bugnion the creator the MVVM Light.

1 Comments

These days if you can write code with C# you can write code for Windows, Linux and OSX, your code can run on Desktop, Server, Mobile or Embedded Devices. So C# runs pretty much everywhere which if you are a C# developer is a great thing! Smile Only little hiccup, even though C# is a standardised language, there are multiple runtimes existing today on which C# runs. This may lead to the assumption of having to rewrite code for every runtime. As the standard .Net C# library can not be reused on a Silverlight runtime, or the new Windows RT runtime, or I think you get the message. But fear not – thanks to the Portable Class Library (PCL) one is able to write code that can be reused over multiple platforms.

Portable Class Libraries

When adding a Portable Class Library (PCL) you will have to choose which platforms you want to use the platform on. The supported platforms have an impact in the functionality the PCL provides without adding any additional libraries (usually via NuGet). You can find a list  of libraries supported by each platform on MSDN.

For this post we will want to reuse our code on the following platforms:

  • Universal Windows App (Windows 10)
  • Classic desktop WPF app
  • iOS (with Xamarin)
  • Android (with Xamarin)

To keep things simple the logic in the app will be creating a list of people. We will even be able to share our view models from the PCL so the only overhead we will be having when creating the app is the actual UI code and wiring up the view models to the actual views. Now in this setup the timesaving's might seem marginal but think about your standard business app and the savings will start to up add up quickly in a major way.

Creating a PCL

Adding the platform specific projects is pretty straight forward. Simply add the corresponding project template to the solution when adding a new project, so I’ll leave it at that and go over to adding a PCL. When adding the PCL a dialog will be opened offering to choose the platforms that shall be supported i.e. can consume the PCL.

Showing Add Portable Class Library Visual Studio dialog with .Net Framework 4.6, Windows Universal 10.0, Xamarin.Android and Xamarin.iOS selected

The iOS and Android option will show up after installing the Xamarin tool chain.

With the platforms chosen we can now start implementing the “business logic” which in our case is a simple generator that we invoke, called PersonService.cs:

public class PersonService
{
    public async Task<IEnumerable<Person>> GetPeople(int count = 42)
    {
        var people = new List<Person>(count);
        // In case of large counts lets be safe and not run this on the UI thread
        await Task.Run(() =>
        {
            for (int i = 0; i < count; ++i)
            {
                people.Add(new Person{FirstName = NameGenerator.GenRandomFirstName(), LastName = NameGenerator.GenRandomLastName()});
            }
        });

        return people;
    }
}

To present our data to the UI we will use the MVVM pattern.

Adding MVVM Light

When using MVVM in a project (which is like always for me Winking smile) I prefer using MVVM Light. MVVM Light can be added by simply installing a NuGet package:

PM> Install-Package MvvmLightLibs

As we will access the view models from the platforms make sure to add the MVVM Light libraries also to the platform specific code bases.

Now we can add the view model MainViewModel.cs that will hold the list of people we will display.

public class MainViewModel:ViewModelBase
{
    private readonly IPersonService _personService;

    public MainViewModel(IPersonService personService)
    {
        if (personService == null) throw new ArgumentNullException(nameof(personService));
        _personService = personService;
        if (IsInDesignMode)
        {
            People = new ObservableCollection<Person> {new Person{FirstName = "Doctor Who"}, new Person {FirstName = "Rose", LastName = "Tyler"}, new Person {FirstName = "River", LastName = "Song"} };
        }
        else
        {
            People = new ObservableCollection<Person>();
        }
    }

    public ObservableCollection<Person> People { get; set; }

    public async Task InitAsync()
    {
        var people = await _personService.GetPeople();
        People.Clear();
        foreach (var person in people)
        {
            People.Add(person);
        }
    }
}

Next we still need to configure the ViewModelLocator.cs, which allows us to easily manage dependencies.

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<IPersonService, PersonService>();
        SimpleIoc.Default.Register<MainViewModel>();
    }

    public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
}

So now we have all of our cross platform code setup. Let’s get it running on our desired targets.

The platforms

On the platforms we can simple reference the PCL like any other library we might use and access the features. On our platforms we will have to do the following steps:

  1. Create the UI
  2. Hook up theViewModelLocator.cs
  3. Wire up the view model to the view

Let’s do these steps for the Universal Windows App.

Universal Windows App (UWA)

For the view we will simply add a ListView to the MainPage.xaml:

<Page
    x:Class="PclSample.UWA.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PclSample.UWA"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    DataContext="..."
    mc:Ignorable="d">

    <ListView ItemsSource="{Binding People}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text="{Binding LastName}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Page>

Under Windows (this is also true for WPF) MVVM Light really integrates really nicely. The Locator we can simply add to the App.xaml:

<Application
    x:Class="PclSample.UWA.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PclSample.UWA"
    RequestedTheme="Light">
    <Application.Resources>
        <vm:ViewModelLocator x:Key="Locator" xmlns:vm="using:PclSample.Core" />
        <ResourceDictionary />
    </Application.Resources>
</Application>

This allows us to access properties from the ViewModelLocator.cs class within our view(s) i.e. MainPage.xaml. So the next step would be wiring up the view model to the views DataContext, which will populate the view:

<Page
    x:Class="PclSample.UWA.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PclSample.UWA"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    DataContext="{Binding Source={StaticResource Locator}, Path=MainViewModel}"
    mc:Ignorable="d">

    ...
</Page>

Now all is set and we can enjoy the view of our light weight UWA.

Screenshot of the UWA running in the Windows 10 Mobile Emulator

Windows Presentation Foundation (WPF)

Following the same steps as in the UWA in a WPF app will lead to the same result.

Shows sample app running in as a WPF desktop application

So we can reuse all of our business logic from one Microsoft client development model to an other one. Isn’t that just great? Smile But wait there is more. We can take the C# code outside of the Microsoft Ecosystem. With for example Xamarin we can reuse our C# code on iOS and Android.

iOS

Under iOS the UI is usually created in a designer (similar to Windows Forms) so there is not much code to show. We add the ListView equivalent from iOS a UITableView to a page and give it a name, in this sample PeopleTableView.

Showing iOS Designer and where the name of the UITableView is set.

Setting up the ViewModelLocator.cs is not quite as elegant when we leave the Microsoft platforms but then again it is done just as easily. In the AppDelegate.cs which is the start up point of every iOS app we simply create an Instance of the ViewModelLocator.cs and store it in a property. The property then can be accessed throughout the iOS app. The Wiring up of the view model is done in the ViewController.cs which is linked to the view that we setup earlier:

public partial class ViewController : UIViewController
{
    ObservableTableViewController<Person> _tableViewController;

    public ViewController (IntPtr handle) : base (handle)
    {
    }

    private MainViewModel Vm => Application.Locator.MainViewModel;

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        _tableViewController = Vm.People.GetController(CreatePersonCell, BindPersonCell);
        _tableViewController.TableView = PeopleTableView;
    }

    public override async void ViewWillAppear (bool animated)
    {
        base.ViewWillAppear (animated);
        await Vm.InitAsync();
    }

    public override void DidReceiveMemoryWarning ()
    {
        base.DidReceiveMemoryWarning ();
        // Release any cached data, images, etc that aren't in use.
    }

    UITableViewCell CreatePersonCell (Foundation.NSString reuseId)
    {
        var cell = new UITableViewCell(UITableViewCellStyle.Default, null);
        return cell;
    }

    void BindPersonCell (UITableViewCell cell, Person person, Foundation.NSIndexPath path)
    {
        cell.TextLabel.Text = person.FullName;
    }
}

Now all that is left to do for us is again fire up the iOS Simulator to verify all is correct and there we have it, the same C# code we used for our WPF and UWA apps is now running under iOS:

iphone

Android

What we did under iOS we can also replicate under Android. Though not part of the Microsoft eco system the model should be more familiar if you have written WPF, Modern Apps (and all the other fancy names they had i.e. Universal Apps). Under Resources/Layouts there is the main.axml which is a (Application) XML file we can edit to tell the Android OS how to render the UI. Sounds a bit like XAML right? And the concepts do overlap in some parts too. Adding a ListView to the XML and set the id of the element which will allow us to access it later on:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/PeopleListView" />
</LinearLayout>

Again we will have to setup the locator. Under Android there is no fixed setup point, so we will use a static class Locator.cs and property which we will access from the Android app:

internal static class Locator
{
    private static readonly Lazy<ViewModelLocator> _locator = new Lazy<ViewModelLocator>(() => new ViewModelLocator());
    public static ViewModelLocator Instance => _locator.Value;
}

Wiring up the view model is done in the MainActivity.cs, which you can think of as the code behind/ViewController equivalent. I wrote about this binding in more detail in a former blog post which you can find here.

[Activity(Label = "PclSample.Droid", MainLauncher = true, Icon = "@drawable/icon")]
internal class MainActivity : Activity
{
    protected override async void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        await Vm.InitAsync();

        // Get our button from the layout resource,
        // and attach an event to it
        PeopleListView.Adapter = Vm.People.GetAdapter(GetPersonView);
    }

    public ListView PeopleListView => FindViewById<ListView>(Resource.Id.PeopleListView);

    private MainViewModel Vm => Locator.Instance.MainViewModel;

    private View GetPersonView(int position, Person person, View convertView)
    {
        View view = convertView ?? LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);

        view.FindViewById<TextView>(Android.Resource.Id.Text1).Text = person.FullName;

        return view;
    }
}

Note that the id we previously set allows us to retrieve the UI control.

At this point we can start up the Android Emulator and just to have mentioned it Visual Studio 2015 provides a great Android Emulator – way better then the stock emulator! And once again we can see the app is running reusing the C# code we tucked away in our PCL.

Shows app running in the Android Emulator

Conclusions

In this blog post we saw how one can share C# code with a Portable Class Library (PCL). The PCL can be included in all major C# stacks .Net, UWP, Silverlight, Xamarin etc. and though the capabilities in the PCL are more limited then a standard .Net library it does allow to share code from a legacy WPF/Win Forms app to a mobile application.

PCLs can be extended by installing further NuGet packages such as storage, network access and many more. The PCL has been around for a couple of years now and has proven itself to be a valuable component when writing cross platform applications.

The entire sample can be found on GitHub.

0 Comments

title_thumb2

On the 6. October 2015 Microsoft introduced it’s new devices all destined to run Windows 10.

The first Device was the HoloLenswhich was demoed with a immersive game experience showing how HoloLens can integrate the furniture of your living room in the game. Plus the HoloLens should start to be available next year for developers for 3000$, so far only US availability has been announced, but my hopes are still high that it will reach Europe and other countries outside of the US soon after that.

band2_thumb

After the HoloLens the new Microsoft Band 2 was introduced. The specs of the band leaked before the event and they seem to be have quite spot on. The new band has a curved display, looks sleeker and has an additional 11th sensor (a barometer) which allows it to track elevation/steps. The band is focused on sport and tracking the users physical activities. The data is stored in the Microsoft health service which allows the user to analyse all of his activities i.e. golf, sleep, running and many more. The Data is stored as usually done with these services in the cloud and not on the devices of the user.

Further Microsoft partnered up with quite a few companies to ensure the band will have apps that provide the user with additional apps and notifications right at your wrist.

Windows Mobile

Lumia-950_thumb2

With the Lumia 950 and 950 XL Microsoft finally has introduced two flagship phones which has been overdue and long awaited. Since the Lumia Icon/930 and Lumia 1520 which they are replacing have been on the market for years(!). The new Lumias keep true to their heritage of providing great Cameras (20MP incl. image stabilization), great displays and the obligate bump in battery size. Further the following specs stick out:

  • Expandable storage via SD-Card
  • 3 GB RAM
  • Snapdragon 808 processors
    • 6-Cores
    • 8-Cores XL
  • USB-C connector

The new USB-C connector allows an ease of use and greater bandwidth but there is more, with the new phones Microsoft introduces Continuum. With an additional accessory called a Microsoft Display Dock you can plug in your phone to a monitor, keyboard and mouse allowing you to control desktop applications such as Word, PowerPoint etc.. The apps that can be used will be based on the Universal Windows Platform (UWP) which allows developers to adopt for different screen sizes. So when the app provides resolutions for phone and desktop factors the same phone app will be displayed differently and allow the user to harness the full power of a desktop setup such as using a mouse and a real keyboard.

While connected to the Microsoft Display Dock the phone will still be available as a phone, meaning you can make calls, write and receive texts etc.. So it isn’t just simply projecting the screen of the phone to another display but it actually will bring up a (limited) Windows 10 desktop experience which I see some very interesting scenarios arising and allows you to use the phone as a PC! Smile

While the Lumia 950 und Lumia 950 XL are high end phones Microsoft also introduced the new Lumia 550 which will provide a cheaper alternative without the Continuum though but still providing quite some bang for the buck.

Surface Pro 4

sp4_thumb4

The Surface Pro 4 is the expected update of the Surface Pro 3. While keeping the dimensions of the SP3 the SP4 comes with the latest Intel chipset, up to 16 GB RAM and 1 TB hard drive. These specs are a great bump and will allow to run Virtual Machines easily from your SP4. Keeping the dimensions will mean that all the external hardware accessories for the SP3 will work with a SP4 and vice versa. If you are the proud owner of a SP3 and have a dock. You will be able to simple reuse the dock for the SP4. All the hardware released for the SP4 also works for the SP3.

While keeping the overall dimensions the SP4 comes with a greater resolution which comes to the cost of the bezel. The screen now comes at 12.3 inches and sports 2736 x 1824 resolution which results in a really high res display at 267 pixels per inch (ppi).

Type cover

The new type cover comes with a full keyboard layout, 40% larger track pad and there will even be versions with a biometric finger reader. Real world testing will prove how much better it is overall but a full size keyboard layout surely sounds lovely.

Pen

The pen has been overhauled slightly. The backend tip now not only is the OneNote button but also serves again as rubber as it was the case with the SP1 & 2 pens. The pen tip can be interchanged which will allow artistic and design folks to choose individual brushes simply by changing the tip and sport the physical feel.

pen_thumb1

Another great plus is that the pen now attaches magnetically to the Surface, so no more after thought latches needed. I really like this additional feat as I never grew warm to the latch (in my case still in the original packaging…).

Docking Station

surface_dock_thumb3

The new docking station no longer requires you to place the Surface Pro into it. It is an elegant little box that you can attach via the power connector. The new Docking Station provides gigabit Ethernet, two display ports, four USB 3.0 ports, audio out and of course power to the Surface Pro 4 and can be used with the Surface Pro 3.

 

(One more thing) Surface Book

The biggest surprise (very positive surprise) is the Surface Book. Other then the SP4 it comes with a Keyboard dock that can be removed at the push of a button. The design looks very sleek and though it does not close fully it resembles pretty much a laptop. In the keyboard half of the Surface Book are additional batteries and a custom made NVidia graphics card. So it has no problems stemming graphically intensive work such as 3D design or games.

surfacebook_thumb2

Being able to remove the tablet results in a light weight and really thin tablet (the USB, Power and display ports are all in the keyboard part). The tablet has the form factor of an A4 paper so it should give you known dimensions and with a pen will allow you to get a great note, drawing, etc. paper.

All accessories from the SP4 are compatible with the Surface Book. But you will not be able to stick it into a SP3 docking station. But it will go nicely with the new SP4 docking station which is less bulky and just as clean.

The take away

Microsoft gave an awesome presentation and highlighted a lot of great features that they usually just seemed to forget to bring forward to the crowd. During the great presentation they highlighted the future with HoloLens, the next step for Windows Phone which will be renamed to Windows Mobile with Windows 10 and the great line up of Surface hardware.

With the new hardware I am sure the surface will continue to grow and expand in a market that is looking how to integrate tablets for the workforce which requires additional input compared to a candy crush app.

The phone hardware finally serves again the users that do want to spend some money for a device and brings some great power user features to the I-want-to-get-stuff-done minded people out there.

I personally can’t wait to get my hands on the new hardware and give it a run especially the phones continuum mode and the new Surface Book are looking very nice and I already fear the impact on my bank account Winking smile