Xbox UWP – Unable to Activate Windows Store App – Error 0x8004090a

Building and deploying UWP apps on Xbox is frustrating – every time I come back to it I get caught out by things that should just work. The one that always seems to get me is that you have to be signed in on the Xbox. This used to not be a problem because Visual … Continue reading “Xbox UWP – Unable to Activate Windows Store App – Error 0x8004090a”


Unhelpful ‘Unable to activate Windows Store app’ Error

Building and deploying UWP apps on Xbox is frustrating – every time I come back to it I get caught out by things that should just work. The one that always seems to get me is that you have to be signed in on the Xbox. This used to not be a problem because Visual Studio used to recognise this issue and provide you a nice reminder – I think it was in the Output window but can’t be sure for certain.

I just attempted to debug an app on the Xbox from the latest version of Visual Studio (both preview and stable) and got the following completely unhelpful error message:

Unable to activate Windows Store app 'XXX.YYYYYYYY_ZZZZZZZZApp'. The activation request failed with error 'Operation not supported. Unknown error: 0x8004090a'.

After rebuilding, cleaning the solution, restarting the Xbox and a variety of other things, I remembered to check that a user was signed in on the Xbox. Sure enough it wasn’t and sure enough, signing in, fixed the activation error.

If you come across this error, make sure you’re signed into an account on the Xbox!!!

Don’t Judge XAML Based On Lines of Code

For those following the on-going discussion around the future of XAML and specifically the use of XAML in DotNetMaui/Xamarin.Forms, this post is a follow on from two great posts discussing the options that are, or will be, available for Xamarin.Forms developers as we move forward with DotNetMaui: Mobile Blazor Bindings – Getting Started + Why … Continue reading “Don’t Judge XAML Based On Lines of Code”

For those following the on-going discussion around the future of XAML and specifically the use of XAML in DotNetMaui/Xamarin.Forms, this post is a follow on from two great posts discussing the options that are, or will be, available for Xamarin.Forms developers as we move forward with DotNetMaui:

I’ve already discussed why I feel that DotNetMaui will extend Xamarin.Forms to be an inclusive platform for developers wanting to build cross platform applications. Recent additions to Xamarin.Forms, such as C# markup, coupled with the features outlined on the DotNetMaui roadmap, suggest that the path forward will be full of options for developers.

This bring me to the point of this post, which is to discuss XAML both in the context of DotNetMaui/Xamarin.Forms but also in the context of UWP/WinUI/Uno. To do this I’m going to re-visit the scenario discussed by Dylan and Vincent and look at some alternatives that might make XAML a bit more appealing

Xamarin.Forms Visual States

When I initial read through Dylan’s post and reviewed the XAML I was initially shocked at how hard it was to read and in fact it took me a while to realise why it looked so chaotic and hard to follow. It came down to a couple of things:

  • Changing XAML attribute values based on data triggers at various points in the XAML
  • The lack of Visual States
  • Using MultiTrigger to change attribute values based on multiple data values.

Just so that I’m clear, I’m not saying that the code was poorly written; I’m just observing why I found it hard to read. Let me present an alternative XAML for the page and discuss how it makes the code a little more readable.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:XamlFlags"
    x:Class="XamlFlags.MainPage"
    x:Name="Page">
    <ContentPage.BindingContext>
        <local:MainPageViewModel />
    </ContentPage.BindingContext>
    <StackLayout
        BindableLayout.ItemsSource="{Binding Options}">
        <BindableLayout.ItemTemplate>
            <DataTemplate>
                <Frame
                    CornerRadius="4"
                    Padding="0">
                    <StackLayout
                        Orientation="Horizontal"
                        Padding="5"
                        BackgroundColor="White">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState
                    x:Name="IsEnabledAndSelected">
                    <VisualState.StateTriggers>
                        <StateTrigger
                            IsActive="{Binding Selected}" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter
                            Property="BackgroundColor"
                            Value="DarkBlue" />
                        <Setter
                            Property="IsVisible"
                            Value="False"
                            TargetName="OptionsSelectedLabel" />
                        <Setter
                            Property="Label.TextColor"
                            Value="White"
                            TargetName="OptionsValueLabel" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState
                    x:Name="IsNotEnabled">
                    <VisualState.StateTriggers>
                        <StateTrigger
                            IsActive="{Binding IsNotEnabled}" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter
                            Property="IsEnabled"
                            Value="false" />
                        <Setter
                            Property="BackgroundColor"
                            Value="DarkGray" />
                        <Setter
                            Property="Label.TextColor"
                            Value="LightGray"
                            TargetName="OptionsValueLabel" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
                        <Button
                            Text="Select"
                            Command="{Binding BindingContext.SelectTypeCommand, Source={x:Reference Page}}"
                            CommandParameter="{Binding .}" />
                        <Label
                            Text="✓"
                            TextColor="White"
                            x:Name="OptionsSelectedLabel"
                            FontSize="12"
                            HorizontalOptions="EndAndExpand"
                            VerticalOptions="Center"
                            IsVisible="false" />
                        <Label
                            Text="{Binding Value}"
                            TextColor="Black"
                            x:Name="OptionsValueLabel"
                            HorizontalOptions="EndAndExpand"
                            VerticalOptions="Center" />
                    </StackLayout>
                </Frame>
            </DataTemplate>
        </BindableLayout.ItemTemplate>
    </StackLayout>
</ContentPage>

On initial inspection you might be looking at this XAML wondering whether it’s improved the readability. However, if you collapse the VisualStateManager.VisualStateGroups node in the editor, the code immediately looks much more readable, as shown in the following image.

We can clearly make out that the interface is made up of a stack of items with each row being made up off a Button and two Label elements. The default state is for the row to have a White background and for the ✓ Label to be hidden (IsVisible set to false).

Now, let’s look at the contents of the VisualStateManager.VisualStateGroups. In this case it defines a single VisualStateGroup in which I’ve included two VisualState elements. If we consider each row it can be in one of three states:

  • Enabled and Not Selected – This is the default state where the item hasn’t been selected (IsEnabled = true, IsSelected = false).
  • Enabled and Selected – This is the state where the item has been selected by the user clicking the Select button (IsEnabled = true, IsSelected = true).
  • Is Not Enabled – When an item in the list is selected, other items may be set to disabled (IsEnabled = false, IsSelected = false).

Even though there are only two VisualStates defined in the XAML, there are in fact three visual states because there is the default state. Each of the VisualState uses a StateTrigger to determine whether the visual state is active or not. Rather than attempting to data bind to two different properties on the underlying data model, I’ve explicitly created single properties that reflect whether the state is active or not. The default state is both the initial state of each row, as well as the state that is returned to if neither of the defined VisualStates are active (ie the StateTrigger IsActive is set to true).

One of the benefits of using visual states is that you can set multiple properties, on one or more different elements, essentially grouping all the changes required for a particular visual states. This eliminates the need to have data triggers littered through the XAML used to define the layout for the page. In this scenario each of the VisualState elements has multiple Setters defining the background colour, the foreground (text) colour and in the case of the IsEnabledAndSelected state, the visibility of the ✓ Label.

As I pointed out earlier, for me, this makes the XAML easier to read. I know other developers prefer to have the data triggers local to where the attributes being changed are in the XAML. This approach has some advantages, particularly where you only have a small number of changes in a large XAML document.

Before we move on from discussing Xamarin.Forms I would point out that the VisualStateManager is a relatively new addition and specifically the ability to use TargetName to target different elements from a single VisualState. I would encourage revisiting your XAML to see whether using the VisualStateManager will simplify your code. Alternatively, you may want to consider breaking your code up into different controls that will help encapsulate things like visual states whilst reducing the complexity of the XAML on each page. We’ll talk more about using UserControls in the context of UWP shortly but the same concept can be used for Xamarin.Forms as well.

UWP / WindowsUI / Uno

The XAML used by the Universal Windows Platform (ie UWP) provides a couple of alternatives when it comes to defining the desired layout. In this section we’re going to consider three options: Optimised, UserControl and ContainerStyle (Code is available on GitHub)

Optimised for Lines of Code

In this approach the goal was simply to reduce the number of lines of code. I’m not going to spend much time on this because I fundamentally think measuring the quality of a technology based on the number of lines of code is just ridiculous. The following image shows the resulting 41 lines of XAML – of course this is also contingent on my Visual Studio settings where the first attribute is on the same line as the element; other developers have different options set, so will see different numbers of lines.

I will comment on a couple of things:

  • Unlike the Xamarin.Forms approach that uses a horizontal StackLayout, this XAML uses a Grid which clearly defines three columns. I prefer this approach as it clearly defines the sizing option for each column. Using a StackLayout with different HorizontalOptions isn’t as clear in my opinion.
  • This code uses x:Bind instead of the usual Binding syntax. This allows for code to be generated during compilation that enforces type checking and results in better performance as it reduces the reliance on reflection.
  • Rather than using converters this code uses static methods defined on the page to convert property values (in some cases multiple properties) into the required attribute value. In practice I would not recommend doing this as it embeds logic in your XAML layout

UserControl with Visual States

In the previous section we optimised the XAML by interleaving logic into our XAML layout. This is a practice that I actively try to avoid when defining the XAML for a page or control. I try to ensure the XAML I create is as declarative as possible, which means avoiding calling methods as part of binding expressions. I’d even go so far as to say that you should avoid using converters unless they are simple type converters (the most obvious one being for bool to Visibility conversion). I advocate for all logic to be encapsulated in either the ViewModel (if UI relate logic) or in the Model (if business logic), thus making it testable and ensuring a clean separation from the way that it’s presented (i.e. the View).

Let’s look at how we can keep our XAML clean of logic by following a similar approach to what we did earlier for Xamarin.Forms. What’s interesting about UWP is that if you attempt to follow the same strategy of defining visual states within the DataTemplate you’ll find that it doesn’t work. Instead you either need to define the visual states within a UserControl, or you have to apply the visual states in the ItemContainerStyle.

We’ll start with defining a UserControl which will include the layout for each item in the list, along with the different visual states. Rather than just show you the code, let’s jump into Blend and use the visual designer to build the desired layout. Rather than boring you with creating the project and adding things like the MainViewModel, I’m just going to focus on creating the UserControl.

From Solution Explorer, right-click on the project or a sub-folder and select Add, New Item.

From the Add New Item dialog, select User Control, give it a name (eg OptionItemControl) and click Add. This should give you a new design surface that we can start adding controls to.

Using the Assets tool window, double-click on the Button and then twice on the TextBlock. Alternatively you can drag these controls onto the design surface.

If you look at the XAML you’ll notice that Blend has added some default attributes to each of the controls that you added. Normally my recommendation would be to tidy up whatever XAML Blend creates, as you go, to ensure your XAML remains clean and does exactly what you want. If you’re not that familiar with XAML, reviewing the XAML that Blend generates is a great way to learn about features that you might not be aware of.

If we look at the design surface we can see that the three controls we added are incorrectly located on the design surface – we’re after a single row with three cells that should hold the “select” Button, a check mark TextBlock and the option value TextBlock.

Let’s go ahead and create the cells in the Grid by defining three columns. We can do this using the design by hovering the mouse near the top of the design surface. The cursor should change to include a small + sign and if you click with the mouse a new column break will be added. You can then use the designer to specify how the column widths are defined. In this case we want the first column to be Auto and the other two columns to be * (just *, so you may have remove any numeric value added by Blend eg 101* should be changed to just *)

Next we want to reposition the two TextBlock into the appropriate column. You can do this by simply dragging them using the mouse. As you drag and hover over each cell in the Grid you’ll see alignment and positioning lines appear in red.

After positioning the TextBlock into the correct column you will want to tidy up the XAML – Blend has an annoying habit of adding Margins and other layout attributes that are typically unnecessary. You can clean up these excess attributes by right-clicking the control and selecting Layout, Reset All.

The next thing to do is to replace the default Text value for the TextBlock from “TextBlock” to something more meaningful. Rather than having to locate the Text property in the properties tool window, you can simply double-click the TextBlock and type directly on the designer. You can do the same thing with the Button control to change the Content to “Select”.

According to the design we’re aiming to achieve we need to change the default (i.e. Enabled but not Selected) Background to White. Use the colour picker in the Properties tool window to do this. This of course will override the theming and thus break support for dark and light themes, but that’s a topic for another day.

Unfortunately setting the Background to White means we can no longer see the three controls, since their default text colour is currently also White. This can be fixed easily by selecting all three controls in the Objects and Timelines tool window.

From the Properties tool window, update the Foreground colour to Black.

You’ll also need to adjust the BorderBrush on the Button. After doing this the layout should be similar to the following.

And the XAML for this is quite tidy.

What’s missing are the visual states for when the option is selected and when it’s disabled. We’ll add two VisualStates to the UserControl via the States window. Normally I advocate for creating a third VisualState that represents the default state – this is so that in code you can use the VisualStateManager GoToState method to return to the default layout. However, we’re going to be using state triggers to transition between states, so a third VisualState is not required – when none of the state triggers are set to active, the UserControl will return to the default state.

By clicking on a VisualState in the States tool window we can put Blend into state editing mode. This is highlighted by both the red dot alongside the VisualState, as well as the red border around the design surface. Any changes you make whilst this highlighting is visible will be recorded against the corresponding VisualState.

I’m not going to go through setting all the properties for each VisualState but essentially we need to update the Background colour on the Grid, the Foreground colour on the TextBlock and Button, and the Visibility on the checkmark TextBlock. For the checkmark TextBlock, you’ll need to switch the default Visibility to Collapsed – we had it visible whilst designing the layout but it’s default state is actually to be hidden (i.e. Collapsed).

As part of defining the VisualStates you may have noticed that the controls in the Objects and Timeline tool window were all given default names like grid, button, textBlock and textBlock1. I would encourage you to give these more meaningful names by double-clicking on them in the Objects and Timeline tool window and typing a new name.

Currently we have completed the design of the UserControl, including the three different states it can be in. However, we haven’t wired it up to any data. If we were to use this UserControl as it is, it would simply show a list of “Option 1”. So that we can wire up some data, let’s add an instance of the OptionViewModel as a design time DataContext for the UserControl (note the use of the d: prefix to indicate design time only).

Select the TextBlock that should show the OptionViewModel Value property. Click on the small square to the right of the Text property in the Properties tool window and select Create Data Binding.

Since we’ve set up an instance of the OptionViewModel as a design time DataContext, Blend is able to offer suggestions for the Path attribute. Select the Value property and click Ok.

At this point you’ll be wondering why the TextBlock that you just setup data binding for as disappeared from the designer. Well, the good news is that the TextBlock is still there, it just has zero width because the Value property on the OptionViewModel is returning null. This is easily fixed by specifying the Value property on the OptionViewModel specified in the design time DataContext.

Ok, we’re almost there. We have our layout, our Visual States and our data. We still need to be able to trigger then changing of states. For this we’re going to use a state trigger. Click the “Edit Adaptive Triggers” button next to the VisualState.

From the Dropdown at the bottom of the screen select <Other Type…>

In our project we have a trigger called DualBooleanDataTrigger which will allow us to trigger a VisualState based on the value of two different bool properties.

Unfortunately this is about as far as the data trigger design experience can take us. Luckily the XAML for the DualBooleanDataTrigger isn’t that complex. As you can see from this image, we need to data bind the DataValue and SecondDataValue attributes to the IsEnabled and IsSelected properties on the OptionViewModel and then we need to specify the value for each of these properties that we want the VisualState to be active for. In this case we want both the IsEnabled and IsSelected properties to be True for this state to be active.

The last thing we need to do is to wire up the Button to a method that will set the OptionViewModel to be selected. For this, we’re going to use x:Bind so that we can bind directly to a method on the OptionViewModel. In order to do this, we need to expose the the OptionViewModel as a property on the UserControl.

In the MainPage (i.e. where we’re defining the ItemsControl) we need to include an instance of the OptionItemControl in the DataTemplate. In order for x:Bind to work we need to make sure we set the ViewModel to be the current DataContext of the DataTemplate (i.e. binding path of . which can be omitted in this scenario).

We then need to specify the Click attribute on the Button.

After completing this we’re done! But let’s take a look at what’s been generated. Well, the good news is that we’ve created the entire user experience without having to write much XAML at all. The bad news is that Blend does a terrible job of generating optimized XAML. Take for example the following snippet where you can see that each Setter is spread over 5 lines.

In contrast, when I tidy these up, each Setter takes only 2 lines and that’s only because I have Visual Studio and Blend set to put attributes on new lines.

As you can see from this walk through, you can use a separate UserControl to easily design the layout for the three states required in this design.

ListView ItemsContainerStyle

The third option I wanted to briefly discuss (because there’s plenty of room for an entire discussion on this topic) is to override the ItemsContainerStyle for a ListView in order to define the VisualStates for the items in the list. Let’s back up for a second and explain a few things.

The scenario that we’re addressing is a common enough scenario where items in a list are selected. In this case the individual item tracks whether it’s selected (and in fact whether it’s enabled). This approach is actually at odds with the way a number of controls work. Take for example the ListView or GridView which are used to represent a list, or grid, of selectable items. Theses controls have built in styles that represent how each ListViewItem will look in various states. These states include (not an exhaustive list) Selected, Pressed, Enabled and Disabled. Further more, these control separate the appearance of each item (specified using the ItemTemplate) from the behaviour when the user interacts with the items (specified in the ControlTemplate used to define the ListViewItem Template nested in the ItemsContainerStyle). Both the ItemTemplate and ItemsContainerStyle are editable using the visual designer, allowing you to customise the appearance of the item and how it changes when the item is selected or enabled/disabled.

For example in Blend we can right-click on a ListView and select Edit Additional Templates, Edit Generated Item Container (ItemContainerStyle) and then either Edit Current, Edit Copy or Create Empty. I would suggest starting by selecting Edit Copy, which will give you a default style that you can customise, rather than starting from scratch.

In the following image you can see how I’ve defined different VisualStates for the ListViewItem to control the appearance for the three states the item can be in. You can also see all the other states that are available by default on the ListViewItem.

At this point you might be asking why, since the ListViewItem already has a Selected and a Disabled state, don’t I just use these. Well, the issue we have is that the Background and Foreground properties have three different colours based on the combination of two different properties (IsEnabled and IsSelected). This means we need to define states that are in the same group that respond to changes in both these properties. This is not how the built in VisualStates are defined. The Selected and Disabled states are in different VisualStateGroups – if we were to use these to control the same properties, we’ll end up with random and chaotic changes in the appearance.

VisualStates in different VisualStateGroups should not control the same property.

This is an important rule and one that’s easily forgotten or broken. If you ever see unusual behaviour relating to visual states, make sure you check this rule.

I’m not going to delve further into how to use the ItemsContainerStyle in this post but feel free to check out the source code. You’ll notice that this is very verbose coming in at around 130 lines, and this is using a much simplified ItemsContainerStyle. Unfortunately due to the complexity of the built in styles, the ItemsContainerStyle is a large style, mainly because the Template for the ListViewItem is so large. Don’t let this put you off considering using this approach because it does mean that you can reuse the style across various lists that may have different content.

Summary

Wow, sorry this ended up being quite a long post but hopefully you’ll find it useful and get some insight on the various XAML based options available to you. Don’t forget that all the options presented for UWP are able to be taken cross platform using the Uno Platform.

In summary, yes, XAML is verbose but it does come with options. If you spend time maintaining your XAML you’ll find that it is easy to understand and you can leverage the designer support in Blend and Visual Studio along the way.

I don’t believe that looking at the number of lines of XAML (or C# code) is productive. What is useful is to look at the options that are available and the easy with which you can achieve the desired outcome.

Building Messages in Blend for Visual Studio

The other day Martin Zikmond tweeted about a messaging sample app he’d built using the Uno Platform, allowing the same app to run on iOS, Android, Windows, MacOS and Web. Whilst the concept was simple enough, the point was that there was almost no platform specific code and yet the app works and looks virtually … Continue reading “Building Messages in Blend for Visual Studio”

The other day Martin Zikmond tweeted about a messaging sample app he’d built using the Uno Platform, allowing the same app to run on iOS, Android, Windows, MacOS and Web. Whilst the concept was simple enough, the point was that there was almost no platform specific code and yet the app works and looks virtually the same on every platform.

Following my previous post where I did a walk through of some of the Blend for Visual Studio features I use, I thought I’d take the challenge to see how much of Martin’s app I could build using the designer in Blend. The good news is that you can get a long way; The bad news is that there are some features, such as ThemeResources, that seem to cause some issues with the designer – we’ll see this towards the end of the post.

New Project

Ok, so this is pretty self explanatory but Blend has a similar New Project experience to what you see in Visual Studio. Start by searching for the type of project you want to build. So that the designer works, we’re going to select a Blank App (Universal Windows). Once we’ve completed the design work we can copy the files across into our Uno project

Note: At the moment there’s no support for Shared Projects, which the default Uno solution is setup to use. If you follow my post on using multi-targeting with Uno you can use the designer if you load the Windows solution filter.

Give your project a name and location you want it saved.

At this point I typically make sure the application runs and that I’ve upgraded various NuGet packages. Next I’m going to copy in a bunch of the code files from Martin’s project that is available on GitHub. This includes the ViewModels, the SampleData and a couple of Assets.

In the code behind for the MainPage (MainPage.xaml.cs) I’ve added a ViewModel property that returns an instance of the MainViewModel. This will be used to provide both runtime and design time data.

Now let’s get to the designer. From the Assets tool window, search for “split” and drag the SplitView onto the design surface. The SplitView has a Pane, the collapsable panel that shows/hides when you tab the burger menu, and a main Content area. In Martin’s app the list of conversations is in the Pane, whilst the Messages for the selected conversation appear in the Content area.

I wanted to reuse the same color resources that Martin has, so I copied the contents of the App.xaml across to my project – It would be awesome if Microsoft could add back support for managing project resources, which was previously a feature of Blend but got lost in the update to the designer a couple of years ago.

Back to the designer and focus on the SplitView. From the Properties tool window locate the PaneBackground property. Select the Color Resources tab (yeh, Editor and Color Resources are a tab, not that it’s very obvious) and select the NavPaneBackgroundColor (this comes from the resources we added to App.xaml). Whilst we’re here, set the BackgroundSource property to HostBackdrop and TintOpacity to 50%. Check out the docs on Acrylic material for more information on using Windows specific brushes. This is one point where Martin has provided a different background for Windows versus the other platforms – check out the source code to see how he’s done this using platform namespaces.

When you launch the app on Windows you can see the effect of setting the Acrylic background on the pane of the splitview (left side of this image).

Next we’re going to set the Padding on the Grid located inside the Pane, which will inset the list of conversations away from the edge. Rather than just setting the Padding, which can be done using the Properties tool window, I’m going to convert this into a reusable resource. Click the square to the right of the property to display the context menu, then select Convert to New Resource.

Give the resource a name and specify where you want the resource to be saved.

In this case I’m going to go ahead and create a new Resource dictionary by clicking the New… button. Since we’ll use this resource dictionary for styles, templates and other resources, I’ve named it accordingly. When you click the Add button, not only does this resource dictionary get added to your project, it is also wired up as a merge dictionary in App.xaml.

Next we’re going to add a ListView to the Pane to display the list of conversations. Again from the Assets window, drag the ListView across onto the Pane in the designer.

Unfortunately there’s no designer support for working with x:Bind. However, you will get intellisense in the XAML editor to let you know what properties are available for binding to.

Despite setting the ItemsSource property, the ListView still remains empty on the designer – as I mentioned, no designer support for x:Bind. However, with the recently introduced design time data everywhere support that’s been added, you can take advantage of regular data binding at design time.

Firstly, we’ll add an instance of the MainViewModel as design time resource. Note that this is the same as adding normal resources, just with the “d:” prefix. However, be aware that setting attributes at design time will override any runtime values whilst in the designer. This normally isn’t an issue but when specifying resources, it will only pick up the design time resources, rather than attempting to combine the resource dictionaries.

<Grid>
    <d:Grid.Resources>
        <MainViewModel x:Key="DesignViewModel" />
    </d:Grid.Resources>

Note that the XAML editor is able to assist with applying namespaces etc. After adding the MainViewModel resource I get a prompt helping me to setup and use the namespace.

Next, set the ItemsSource property on the ListView, again using the design time prefix (i.e. d:ItemsSource=”{Binding Conversations}” ). Now we should start to see items appear in the ListView.

Let’s go ahead and create a data template for determining how each item will appear. Right-click on the ListView and select Edit Additional Templates, Edit Generated Items (ItemTemplate), followed by Create Empty. Give the DataTemplate a name and specify where you want to save it.

Rather than going through each element in the item template, I’m going to add the DataTemplate from Martin’s code. However, even after adding this data template, there’s no items appearing in the ListView. Again, this is because there’s no designer support for x:Bind. Luckily we can do the same trick, this time for each property we want to data bind. in this example we’re using the design time data binding for the Text property on the TextBlock

Ok, so now we’re starting to look good.

However, notice how the time is appearing at different positions for each item in the list. This is because the list item isn’t spanning the full width of the ListView. I’ve never understood why this is the default behaviour but it dates back as long as I can remember. Luckily there’s an easy fix, which is to set the HorizontalContentAlignment on the ListView to Stretch. However, this needs to be done on the ItemContainerStyle for the ListView. Right-click on the ListView, Edit Additional Templates and then this time select Edit Generated Item Container (ItemContainerStyle), followed by Create Empty.

Give the template a name and location for saving.

From the Properties tool window, search for “horizon” and change the HorizontalContentAlignment to Stretch (far right icon).

Now, the list of conversations is looking much better.

In the main Content area, lets start by creating three rows to host the header, messages and input TextBox. Using the mouse, you can draw the grid rows, and then use the designer to define the height for the rows. The first and third row should both be set to Auto, with the second row set to *.

Let’s add the input TextBox at the bottom of the screen. Click on the chevrons on the left edge of the design to expand out the Assets flyout. Search for textbox and double-click on the TextBox to add it to the designer.

Next, right-click on the newly created TextBox and select Layout, Reset All.

Depending on where the TextBox was added, you’ll probably have to set the Grid.Row to 2 in order for it to appear in the third row. Whilst in the Properties tool window, let’s set the CornerRadius to 12 and the Margin to 20 – again, I would typically extract these to resources so they can be reused across the app (similar to CSS classes if you’re more familiar with styling for the web).

At this point I’m going to grab the rest of the XAML for the Content area from Martin’s source code, rather than walking you through adding each of the controls. There was one exception to this – in Martin’s code he has used an ItemTemplateSelector to switch between two different item templates based on whether the message is from the current user or not. I’m going to take a different approach, so I’ve replaced the ItemTemplateSelector with just a single ItemTemplate. The resulting messages list looks like the following, where it’s no longer possible to distinguish who sent which message.

To fix this issue we’re going to use converters that take a bool value and determine what value to return. The first converter returns a HorizontalAlignment, either Left or Right, depending on the input value. I’ve set it to return Stretch if the input value isn’t a bool, effectively making it the default value.

Next we’re going to make use of this converter in the item template. Here we’ve selected the Border element and are about to click the Create Data Binding menu item.

In the Create Data Binding window, we select the IsFrom property, and then at the bottom of the window, select the BoolHorizontalAlignmentConverter.

If you run the app at this point you’ll see that the messages are aligned left and right according to who sent the message but there’s no difference in style. We can do the same process but this time for setting the Style of different elements in the template; this time using a BoolStyleConverter.

The difference with the BoolStyleConverter is that it needs a TrueStyle and FalseStyle to be defined. For example for the Border we can create two styles and then an instance of the BoolStyleConverter.

And the same for the TextBlock style

And then we apply these to the item template.

And voila, we have a similar layout to what Martin had

Ok, so just in conclusion there’s a couple of points:

  • Firstly, in the style for the Border and TextBlock it’s referencing a ThemeResource to set color. This is important so that you get support for light/dark mode. However, it also seems to break the designer support, resulting in no messages appearing on the screen. I think the resolution might be that the Styles themselves have to be defined as ThemeResources.
  • Secondly, you might be asking why I chose to use converters instead of an ItemTemplateSelector. The answer is that there isn’t any right or wrong answer, I just wanted to demonstrate a different way to appear the problem. In some cases the ItemTemplateSelector is preferred, particularly if there are massive differences between the templates. In this case, I would probably go with converters because you have a single ItemTemplate, so any changes you make will affect both From and To messages, without you having to remember to update both templates.

Hopefully you’ve seen how you can take advantage of Blend for Visual Studio to start building cross-platform experiences; start with Windows (UWP) and apply it to iOS, Android, MacOS and Web using the Uno Platform

Improving Developer Experience with Multi-Targeted Visual Studio Projects

In my previous post on using multi-targeted cross platform projects I showed how you can add additional target frameworks to allow the addition of platform specific code to a library. One of the downsides of this approach (versus perhaps using a shared project) is that the library gets built once for every target framework that’s … Continue reading “Improving Developer Experience with Multi-Targeted Visual Studio Projects”

In my previous post on using multi-targeted cross platform projects I showed how you can add additional target frameworks to allow the addition of platform specific code to a library. One of the downsides of this approach (versus perhaps using a shared project) is that the library gets built once for every target framework that’s specified. In this post I’m going to show you how you can use the combination of a simple script and Solution Filters to optimise both the time it takes to load your solution in Visual Studio and the time it takes to compile your application.

Firstly, we’re going to adjust the Core project so that we can adjust which target frameworks are include based on a solution property called TargetsToBuild. If this is set to All, we’ll simply use the TargetFrameworks we defined in the previous post (i.e. .NET Standard, iOS, Android and Windows (UAP) when building on Windows). However, if TargetsToBuild is not equal to All, we’ll set the TargetFrameworks to be just the specific target framework that we’re interested in.

<Project Sdk="MSBuild.Sdk.Extras">
	<PropertyGroup Condition=" '$(TargetsToBuild)' == 'All' ">
		<TargetFrameworks>netstandard2.0;xamarinios10;monoandroid10.0;</TargetFrameworks>
		<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">uap10.0.16299;$(TargetFrameworks)</TargetFrameworks>
	</PropertyGroup>

	<PropertyGroup Condition=" '$(TargetsToBuild)' != 'All' ">
		<TargetFrameworks Condition=" '$(TargetsToBuild)' == 'Android' ">monoandroid10.0;</TargetFrameworks>
		<TargetFrameworks Condition=" '$(TargetsToBuild)' == 'Windows' ">uap10.0.16299</TargetFrameworks>
		<TargetFrameworks Condition=" '$(TargetsToBuild)' == 'iOS' ">xamarinios10</TargetFrameworks>
	</PropertyGroup>

Note: I quite often will include netstandard2.0 in all of the TargetFrameworks to make sure the .NET Standard 2.0 build doesn’t break as we’re changing the Core library. This is a personal choice and you’ll definitely get better performance out of not having it build every time.

Ok, so the question is, where does TargetsToBuild get set. For this, we’re going to include a file called Directory.build.props in the solution folder. You can think of this as a file where you can define properties and include items and references across the entire solution. In this case, we’re going to set the contents to the following.

<Project>
  <PropertyGroup>
    <TargetsToBuildDeveloperOverride>All</TargetsToBuildDeveloperOverride>                   
  </PropertyGroup>

  <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
    <TargetsToBuild>$(TargetsToBuildDeveloperOverride)</TargetsToBuild> 
  </PropertyGroup>

  <PropertyGroup Condition=" '$(Configuration)' != 'Debug' ">
    <TargetsToBuild>All</TargetsToBuild>
  </PropertyGroup>
</Project>

There’s two parts to this:

  • Firstly, if the Configuration is not set to Debug, the TargetsToBuild is always set to All. This is never modified, and is a fail safe to ensure all target frameworks are built when doing a Release build.
  • Secondly, the TargetsToBuild is set to the value held by TargetsToBuildDeveloperOverride when the Configuration is Debug. This variable is currently set to All.

The property TargetsToBuildDeveloperOverride essentially has four possible values: All, Android, iOS and Windows. Changing this value will adjust the target frameworks for the Core project. I would recommend restarting Visual Studio as the support for dynamically switching target frameworks in any given session isn’t there yet and doesn’t work 100% reliably.

The next piece to the puzzle is to use Solution Filters to limit which projects are loaded. By limiting which projects are loaded, your solution will load quicker and will also build faster (depending on what your build configuration settings are). To create a Solution Filter, simply unload the projects you don’t want loaded, then right-click on the solution node in Solution Explorer and click Save as Solution Filter. I’ve created the following solution filters:

  • MultiTargetSample.all.slnf: All projects are loaded
  • MultiTargetSample.Android.slnf: Core and Android head project loaded
  • MultiTargetSample.iOS.slnf: Core and iOS head project loaded
  • MultiTargetSample.Windows.slnf: Core and Windows head project loaded

The solution filter file, SLNF, is just a JSON file that lists which projects should be loaded. For example the MultiTargetSample.Windows.slnf file is as follows:

{
  "solution": {
    "path": "MultiTargetSample.sln",
    "projects": [
      "MultiTarget.Core\\MultiTarget.Core.csproj",
      "MultiTarget.Windows\\MultiTarget.Windows.csproj"
    ]
  }
}

The last piece of the puzzle is to combine the solution filters with the TargetsToBuildDeveloperOverride property. For example, if we want to be working on the Android application, we want to set the TargetsToBuildDeveloperOverride property to Android and then load the MultiTargetSample.Android.slnf solution filter. This is easily done using a couple of simple batch script.

Firstly, a generic script (LaunchVS.bat) that takes a parameter (the platform) and adjusts the TargetsToBuildDeveloperOverride property and then launches the appropriate solution filter.

powershell -Command "(gc Directory.build.props) -replace '[a-zA-Z]*', '%~1 ' | Out-File -encoding ASCII Directory.build.props"
start MultiTargetSample.%~1.slnf

Then, we have a script for each platform (eg LaunchVS.Windows.bat) which simply has the following command

LaunchVS.bat Windows

When you double-click on LaunchVS.Windows.bat in File Explorer, Visual Studio is launched with only the Core and Windows projects loaded. The Core library will only build the UAP target framework. This significantly improves both the solution load time and the build time, making working with MultiTargeted projects much easier.

Important: You might think that this isn’t important when you’re first starting out but I would highly recommend adding this to your solution from the get-go. It will save you hours of time both now and when your solution grows. Visual Studio does not handle large solutions with projects that have many target frameworks. Applying these changes will ensure Visual Studio continues to operate properly

Look iOS Developer, No Mac Required – Build an iOS Application using Xamarin and Visual Studio for Windows without using a Mac

If you’re a die-hard Windows user, like me, you’ll be excited to know that you can now build iOS application using Xamarin (and Xamarin.Forms) and Visual Studio, without having to buy or use a Mac. That’s right for development, you no longer need to invest, or carry around, a Mac. In this post I’ll walk you through how to enable this feature.

If you’re a die-hard Windows user, like me, you’ll be excited to know that you can now build iOS application using Xamarin (and Xamarin.Forms) and Visual Studio, without having to buy or use a Mac. That’s right for development, you no longer need to invest, or carry around, a Mac. In this post I’ll walk you through how to enable this feature.

I’m working in the latest preview of Visual Studio 2019 and as of now, to use Xamarin Hot Restart (the feature that powers the no Mac development experience), you need to check the Enable Xamarin Hot Restart option under Preview Features in the Tools, Options dialog.

After enabling Xamarin Hot Restart, make sure you restart Visual Studio. Next, set your iOS project to be the startup project by right-clicking the iOS project in Solution Explorer, followed by the Set as Startup Project menu item.

Make sure in the toolbar the option next to the play button says Local Device. Click the play button, which will kick off the Setup Hot Restart experience.

There are a couple of steps to jump through the first time you want to use Hot Restart. Make sure you follow the instructions to avoid having to redo steps.

The first step in the process it to Download iTunes – make sure you click the Download iTunes button. Do NOT install iTunes from the Microsoft Store. If you’ve done this previously, make sure you uninstall it, and then install it by clicking the Download iTunes button.

Clicking the Download iTunes button will open your default browser but it will attempt to immediately download the file – make sure you check out the downloads so you can launch the file once it’s downloaded.

Step through the iTunes installer.

Once iTunes is installed the Setup Hot Restart process will detect the presence of iTunes (note that it will not detect iTunes if you’re installed it from the Microsoft Store).

Next, make sure you have an iOS device plugged in and that you’ve clicked the Trust option on the device when prompted to trust the connected computer. The Setup Hot Restart process should detect the attached device.

Next, sign into your Apple Developer account.

And select the Development Team you want to use for provisioning.

After completing the Setup Hot Restart process you should see that the build process will continue and that in the Output window you’ll see the iPA being created and subsequently pushed to the device.

When prompted, you’ll need to launch the installed application on the iOS device – this manual step is required in order for Visual Studio to attach the debugger.

And there you have it – you now have an iOS application being debugged using Visual Studio on an actual device with no Mac required!!!

Solved: Unable to Run Windows (UWP) Application from Visual Studio 2019

Over the last 24hrs I’ve had to setup a new dev machine from scratch. After installing all the bits and pieces I need to test out to make sure I can build and deploy apps to Android, iOS and Windows. After creating a new Xamarin.Forms application I set the UWP head project to be the … Continue reading “Solved: Unable to Run Windows (UWP) Application from Visual Studio 2019”

Over the last 24hrs I’ve had to setup a new dev machine from scratch. After installing all the bits and pieces I need to test out to make sure I can build and deploy apps to Android, iOS and Windows. After creating a new Xamarin.Forms application I set the UWP head project to be the startup project and hit run….. and waited….. and waited….. and waited.

After seemingly forever there was an error that appeared in the bottom status bar. Not in the Output window, and actually the build was still going. It reads “Failed to download package ‘runtime.win10-x64.Microsoft.Net.Native.SharedLibrary.2.1.8’ from ‘https://api.nuget.org/v3-flatcontainer/runtime.win10-x64.microsoft.net.native.sharedlibrary/2.1.8/runtime…..”

I’m sure that there are going to be readers out there that will answer this by saying – download nuget and run a manual restore; or call dotnet restore from the package manager. But seriously??? why am I having to do this??? Why it Visual Studio so broken that I can just run the UWP head project of a new Xamarin.Forms application.

I went into manage nuget packages and upgraded the Microsoft.NETCore.UniversalWindowsPlatform package.

After a 20minute wait, it eventually upgraded the package. There after I was able to build and run my UWP application.

Ironically I complained about this back in August last year (the previous time I had to setup a replacement device).

Amazing that in all that time, Microsoft can’t work out how to make new installed, new project, run…. just work, like it should.

Running Android Device Tests for Xamarin.Essentials on Windows

As a developer working with Xamarin or Xamarin.Forms you should be aware of the Xamarin.Essentials package that Microsoft have been developing that “provides developers with cross-platform APIs for their mobile applications”. If you haven’t taken the time to look through the source code, it’s well worth cloning the repository and taking a look. Not only … Continue reading “Running Android Device Tests for Xamarin.Essentials on Windows”

As a developer working with Xamarin or Xamarin.Forms you should be aware of the Xamarin.Essentials package that Microsoft have been developing that “provides developers with cross-platform APIs for their mobile applications”. If you haven’t taken the time to look through the source code, it’s well worth cloning the repository and taking a look. Not only is this a great example of how to do multi-targeting, they’ve also taken the time to invest in device specific tests. In this post we’re going to look at how to run the device tests for Android in the same way that it’s run as part of the Azure Pipelines build script.

The first thing to do is of course clone a copy of the repository and then launch the solution in Visual Studio – before we try to run the device tests we’d better make sure everything is able to be built and run. Unless you’ve been using the same machine for a long time, you’re unlikely to have all the difference MonoAndroid SDKs installed. When you take a look at the Dependencies for Xamarin.Essentials in the Solution Explorer window it’s likely to look similar to what mine did.

The good news is that if you force a build, some of these are likely to go away. For example I actually did have 8.0 and 8.1 installed, so after the build they were resolved and the warning indicators disappeared. Unfortunately, the bad news is that I still had a couple of missing versions.

Luckily this is easily resolved using the Android SDK Manager (launch this from Tools > Android > Android SDK Manager from within Visual Studio), where you can install the missing SDK Platforms.

You’ll need to accept the license terms.

Installing the missing Android SDKs should resolve the Android dependencies. If you’re still seeing a warning for the UAP dependency, you need to verify that you’ve got the Windows SDK v 10.0.16299 installed.

The build process for Xamarin.Essentials is driven from the azure-pipeline.yml file in the root of the repository. This YAML file defines various jobs, one of which is the devicetests_android, which as the name suggests, runs the device tests. Actually this job invokes build.sh, specifying the test-android-emu target. The build.sh is actually just a proxy for running build.cake.

I wanted to run the device tests on Windows, so I’m going to be invoking build.ps1, which is the Powershell equivalent for invoking build.cake. The following command invokes Powershell, passes the build.ps1 as the Powershell script to invoke, and then I’ve included the other parameters that were specified in the azure-pipeline.yml.

powershell -f build.ps1 --target=test-android-emu --settings_skipverification=true --verbosity=diagnostic

Note: You need to invoke this command from the DeviceTests folder.

Unfortunately, simply running the Powershell script from a command prompt isn’t sufficient. There are a few steps you’ll need to jump through in order to get the script to run correctly. Without making any changes, if you run the Powershell script you’ll most likely see an error similar to the following image.

Whilst the error is highlighted in red, the actual cause of the error is in light grey font and indicates that JAVA_HOME hasn’t been defined. Easily fixed by using the set command (make sure the path to the JDK matches where it is on your computer).

set JAVA_HOME=C:\Program Files\Android\Jdk\microsoft_dist_openjdk_1.8.0.25

Also, whilst we’re setting environment variables, check that ANDROID_HOME and ANDROID_SDK_ROOT are set to the root folder of the Android SDK installation (typically C:\Program Files (x86)\Android\android-sdk on Windows if installed via Visual Studio installer)

Suggestion: You’ll find that invoking the Powershell script can be quite time consuming because Xamarin.Essentials has to be built (once for each supported platform) and then the emulator needs to be created and launched. To accelerate this process, after running the script the first time, you can temporarily disable the build by commenting out the “.IsDependentOn("Build-Android")” line in the build.cake file.

Now, when you run the Powershell script, you’re likely to see a different error. Again, it’s not the highlighted error that contains the useful information. Looking a few lines earlier you can see that there is an error relating the system image that the script attempts to use.

Again, fixing this issue is relatively easy. You just need to pick one of the existing system images (listed alongside the error) and use it to set the ANDROID_EMU_TARGET variable.

set ANDROID_EMU_TARGET=system-images;android-29;google_apis_playstore;x86

The next error you’ll see is at the point where the script attempts to launch the emulator. It will fail, indicating that it can’t find the file specified.

It would appear that the build script, build.cake, attempts to call “emulator.bat”. However, this file doesn’t exist. Instead, there is an emulator.exe – we just need to adjust the build.cake to use .exe instead of .bat when locating the emulator command.

Unfortunately there’s also an issue with the search logic, resulting in using a copy of emulator.exe that doesn’t work. After making the above change to .exe, you’ll see that it attempts to launch the emulator but comes up with an error “PANIC: Missing emulator engine program for ‘x86’ CPU”.

Again, this issue is easily fixed with a small change to build.exe to get it to search for the emulator.exe in the correct folder. In the following code, we’ve adjusted the search logic to look in only the emulator folder on Windows.

if (ANDROID_HOME != null) {
        var andHome = new DirectoryPath(ANDROID_HOME);
        if (DirectoryExists(andHome)) {
            if(IsRunningOnWindows()){
                emulatorPath = MakeAbsolute(andHome.Combine("emulator").CombineWithFilePath("emulator" + emulatorExt)).FullPath;
                if (!FileExists(emulatorPath))
                    emulatorPath = "emulator" + emulatorExt;
            }
            else{
                emulatorPath = MakeAbsolute(andHome.Combine("tools").CombineWithFilePath("emulator" + emulatorExt)).FullPath;
                if (!FileExists(emulatorPath))
                    emulatorPath = MakeAbsolute(andHome.Combine("emulator").CombineWithFilePath("emulator" + emulatorExt)).FullPath;
                if (!FileExists(emulatorPath))
                    emulatorPath = "emulator" + emulatorExt;
            }
        }
    }

Finally, when you run the script now, it will run through without error. However, you will see a Windows Security Alert requesting a rule be added to the firewall. You’ll need to click the Allow access button in order for the emulator to talk back to the build script – it uses a TCP listener to retrieve the results from the device tests.

After granting permissions, you should see the following output – if you want more details on the device test output, there’s an xml file that is returned which has the full details of the test execution.

One last comment: If you have the emulator running when you run the device test script, you’ll find that it generates an error at the end of running the script. When the script attempts to launch the emulator, emulator.exe will detect the running emulator and will exit immediately. At the end of the script it attempts to terminate the emulator.exe process – since this process has already ended, it throws and error. You can ignore this error as the device tests will still have executed correctly.

Optimising Multi-Targeting with Visual Studio Solution Filters

Over time Visual Studio has progressively improved support for solutions that have a large number of projects. MvvmCross used to be over 200 projects to handle each of the target platforms it supports. With the introduction of multi-targeted projects the number of projects dropped significantly to around 50 projects. For example, the core MvvmCross project … Continue reading “Optimising Multi-Targeting with Visual Studio Solution Filters”

Over time Visual Studio has progressively improved support for solutions that have a large number of projects. MvvmCross used to be over 200 projects to handle each of the target platforms it supports. With the introduction of multi-targeted projects the number of projects dropped significantly to around 50 projects. For example, the core MvvmCross project has 10 target framework monikers (TFM), instead of having a separate project for each framework. However, the decrease in load time (due to fewer projects) was offset by an increase in build time. Rebuilding the MvvmCross project triggers a build for each TFM, so the project is built 10 times. In this post, I’ll walk through a couple of techniques we use to reduce the build time when working with MvvmCross.

Whilst MvvmCross supports a wide range of target platforms, the reality is that when I’m making changes to MvvmCross I’ll be doing most of the work against one platform. For example being on Windows I might pick Android or Windows and use either the Playground or Playground.Forms sample apps to run up and test my changes. Since I’m working with only one platform at any given time, I don’t need every target framework to be built every time I make a change. Unfortunately there’s no way in Visual Studio to tell it not to build every target framework.

Conditional Target Frameworks

To get around the limitations of Visual Studio we’ve introduced some conditional logic into the project files that determine which TFMs are built. If we look at the top of the MvvmCross.csproj file we can see that there are a number of TFM lists.

<Project Sdk="MSBuild.Sdk.Extras">
  <PropertyGroup Condition=" '$(TargetsToBuild)' == 'All' ">
    <TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">netstandard2.0;net461;Xamarin.iOS10;Xamarin.Mac20;Xamarin.TVOS10;Xamarin.WatchOS10;MonoAndroid90;tizen40;netcoreapp2.1;uap10.0.16299</TargetFrameworks>
    <TargetFrameworks Condition=" '$(OS)' != 'Windows_NT' ">netstandard2.0;net461;Xamarin.iOS10;Xamarin.Mac20;Xamarin.TVOS10;Xamarin.WatchOS10;MonoAndroid90;tizen40;netcoreapp2.1</TargetFrameworks>
  </PropertyGroup>

  <PropertyGroup Condition=" '$(TargetsToBuild)' != 'All' ">
    <TargetFrameworks Condition=" '$(TargetsToBuild)' == 'Android' ">netstandard2.0;MonoAndroid90;</TargetFrameworks>
    <TargetFrameworks Condition=" '$(TargetsToBuild)' == 'Uap' ">netstandard2.0;uap10.0.16299</TargetFrameworks>
    <TargetFrameworks Condition=" '$(TargetsToBuild)' == 'iOS' ">netstandard2.0;Xamarin.iOS10</TargetFrameworks>
  </PropertyGroup>

In the Directory.build.props file for MvvmCross, which we’ll come to in a minute, we’ve defined a property called TargetsToBuild. If this is set to ‘All’, we set the TargetFrameworks property to include all the TFMs (except when the OS isn’t Windows_NT where we leave out Uap). However, if the TargetsToBuild is something different we restrict the TargetFrameworks property to the appropriate TFM (eg MonoAndroid90 when the TargetsToBuild is ‘Android’). We also include netstandard2.0 to help ensure developers don’t accidentally include platform specific code in files that are used by all platforms.

I mentioned that we define the TargetsToBuild in the Directory.build.props file. Currently what you’ll find in the Directory.build.props file in the MvvmCross repository is something that looks like the following:

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
  <TargetsToBuild>All</TargetsToBuild> 
  <!--<TargetsToBuild>Android</TargetsToBuild>-->
  <!--<TargetsToBuild>Uap</TargetsToBuild>--> 
  <!--<TargetsToBuild>iOS</TargetsToBuild>--> 
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' != 'Debug' ">
  <TargetsToBuild>All</TargetsToBuild>
</PropertyGroup>

The first PropertyGroup, which is used when the build Configuration is set to Debug, allows the developer to switch TargetsToBuild by simply commenting and uncommenting the different values. For example to switch to Android I simply comment out the line with ‘All’ in it and uncomment the ‘Android’ line. Note that you have to restart Visual Studio for this change to take effect.

Solution Filters (.slnf)

Using the TargetsToBuild property works really well and significantly cuts down on the build time when doing development with MvvmCross. However, whenever I step in to work on MvvmCross I find it frustrating that Visual Studio has to load all 50+ projects when I’m not going to use them all. I’ve noticed recently that a couple of OSS projects such as Platform.Uno and Allan Richie’s Shiny have started to include solution filter files (.slnf). Solution Filter files make it easy to open a solution with only a subset of projects loaded.

There’s plenty of documentation on how to create a solution filter file, so I’m not going to cover that here. However, for MvvmCross it makes sense to have different solution filters for work with each platform. In my PR I’ve created filters for All, Android, iOS and Uap, which match the different TargetsToBuild options (the reason for this will become evident shortly).

Launch Automation

I was looking around for a way to combine solution filtering with the conditional logic for TFMs. Unfortunately there’s currently no mechanism for linking them. What this means is that developers wanting to work for particular platform have to first set the TargetsToBuild in the Directory.build.props, and then open the solution using the appropriate filter file.

I figured that if I can’t link the solution filter with a specific list of TFMs, the least I could do was to automate the process of setting the TargetsToBuild and launching the solution. For this I created a series of .bat files (yeh, old school I know): LaunchVS.All.bat, LaunchVS.Android.bat, LaunchVS.iOS.bat and LaunchVS.Uap.bat. Each of these platform specific launch files invokes “LaunchVS.bat XXX” where XXX is the corresponding platform (eg “LaunchVS.bat Android”).

The LaunchVS batch file does two things:

  • Invokes a powershell command that does a find and replace to update a property, TargetsToBuildDeveloperOverride, in the Directory.build.props file.
  • Launches Visual Studio by starting the corresponding solution filter file. Hence the reason why the names of the filter files needed to match the platforms options for TargetsToBuild.
powershell -Command "(gc Directory.build.props) -replace '<TargetsToBuildDeveloperOverride>[a-zA-Z]*</TargetsToBuildDeveloperOverride>', '<TargetsToBuildDeveloperOverride>%~1</TargetsToBuildDeveloperOverride> ' | Out-File -encoding ASCII Directory.build.props"
start MvvmCross.%~1.slnf

At this point you might be wondering why we’re updating the TargetsToBuildDeveloperOverride property instead of TargetsToBuild. The reason for this is that if we simply did a find-and-replace using the TargetsToBuild property it would replace both the value used for the Debug configuration but also the other configurations. It’s important that we don’t modify the Release configuration by accidentally changing the TFMs, since this could then accidentally be committed to the repository. To avoid this problem I created the TargetsToBuildDeveloperOverride property which is only used to set the TargetsToBuild property for the Debug configuration.

<PropertyGroup>
  <TargetsToBuildDeveloperOverride>Uap</TargetsToBuildDeveloperOverride>          
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
  <TargetsToBuild>$(TargetsToBuildDeveloperOverride)</TargetsToBuild> 
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' != 'Debug' ">
  <TargetsToBuild>All</TargetsToBuild>
</PropertyGroup>

With these changes, all a developer has to do when working with a particular platform is to double-click the appropriate .bat file. The Directory.build.props will be updated and the corresponding .slnf file will be launched. If the updated Directory.build.props does accidentally get committed to the MvvmCross repository it won’t affect the Release build configuration. The LaunchVS batch file is clever enough to switch from one platform to another without the developer having to undo changes to the Directory.build.props file.

Hopefully in this post you’ve seen one option for switching TFMs and making it easier for developers to work with a multi-targeted solution. If you use multi-targeting in your application or library, it’s work considering adding filtering and conditional TFMs to make development easier.

OT: Change Project Options in Visual Studio 2019 to Make Build Output Useful

OT: Change Project Options in Visual Studio 2019 to Make Build Output Useful

There are two things that I find somewhat frustrating about Visual Studio 2019; that is until I spent a minute or two adjusting the behaviour of Visual Studio when I build my projects:

Build Progress Window

This is by far the biggest wasted feature ever added to Visual Studio – This annoying window pops up by default when building a project and has NOTHING useful to say, other than a progress bar across the bottom indicating some sort of percentage through the build. The following window shows the build progress of MvvmCross. However, it’s completely incorrect as not all 47 projects are set to build. In fact what I asked it to build probably has around 10 projects.

Why does this window even exist? Is there some other project type where there is more information displayed in the big white void? 

image

Error List Window

The following image shows the Error List window after a successful  build. What the? I’m sorry but is it really so hard to show just the errors from the most recent build? And perhaps order them in a somewhat meaningful way? In the end I always end up going to the Output window, looking at the first build error encountered and fixing that – pretty much the fastest and most reliable way to get a broken build to work again.

image

Options

The great thing about Visual Studio is that there are a ton of options. In this case I can adjust a couple of options under the Projects and Solutions node to limit my expose to these two redundant windows.

– Uncheck the “Always show Error List if build finishes with errors” – since as we’ve seen the Error List window isn’t the greatest at working out whether the build was successful or not.

– Check the “Show Output window when build starts” – this will effectively hide the Build Progress window.

image

Deploying ASP.NET Core 3 to Linux Azure App Service with Docker

Deploying ASP.NET Core 3 to Linux Azure App Service with Docker

In my earlier post I covered creating and debugging an ASP.NET Core service using Docker Desktop. I’m going to build on that and look at how you then push the service into an Azure App Service. Normally I’d simply use the publish option that would allow me to push the service directly into an Azure App Service – this would run the service in much the same way as it runs locally if I was debugging on IISExpress. However, since I’m debugging via a docker container I figured it’d be great to push to Azure in a way that it continues to run in a container. Actually the reason I explored this in the first place was that I’ve been experimenting with GRPC and currently this doesn’t seem to be able to be supported on a regular Azure App Service. I figured if I could run my code in a container there would be less restrictions so I would be able to get GRPC to work (this is work in progress still).

What I did notice in Visual Studio is that when I right-clicked on my ASP.NET Core project and selected Publish, one of the options I saw was to Create new App Service for Containers.

image

Clicking Publish started the wizard to allow me to create the appropriate resources in Azure.

image

Clicking Create will trigger the creation of the selected Azure resources and then proceed to publish the application.

Note: My initial attempt to published failed with an error

“The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.”

Turns out I didn’t have Docker Desktop running (I have so many apps like Slack, Teams, Skype etc that run in background that I force quit most of them each day to try to retain some semblance of a reasonable battery life on my laptop).

Once I realised that I needed to start Docker Desktop, the publish process kicked off and I saw the Docker deployment console appear with quite a detailed breakdown of the upload status – seriously why can’t Visual Studio’s build progress window be this useful. I really need to hand it to the Docker team as their uploading was super resilient. I started off uploading off our standard wifi connection which is based on an ADSL connection, so minimal upload bandwidth. I got impatient so switched mid-upload across to my mobile hotspot – after a second or two delay, the upload retried and continued without missing a beat.

image

Once publishing has completed, the Azure App Service should be all setup and ready to go with your code already published. You can use the Site URL in the publish information pane to launch the service for testing. Since my application was a web api, I’ve appended the /api/values so that I get a valid response from the Get request.

image

One of the thing that continue to amaze me about Visual Studio is the ability to create and publish new projects to Azure. Of course, for production apps, you wouldn’t follow this process at all but it does make spinning up end to end prototype applications a walk in the park.

Shell in v4 of Xamarin.Forms and Visual Studio 2019

Shell in v4 of Xamarin.Forms and Visual Studio 2019

Back in late 2018 I did a post on getting started with Shell where I did a “File-New-Project” with Xamarin.Forms Shell. In this post I’m going to do a quick update to that post looking at creating a new Shell application with Visual Studio 2019, and then upgrading to the preview of Xamarin.Forms Shell v4.

As all great projects start, let’s get going with the Create a new project dialog. Search for Xamarin and select the Mobile App (Xamarin.Forms) template.

image

Give some basic project information

image

Select Shell as the application template.

Note: The Windows (UWP) option has come back (removed in the initial release of Visual Studio 2019) when creating Xamarin.Forms applications. However, since Shell isn’t supported by UWP at the moment, the Windows (UWP) option is currently disabled.

image

And there you have it a new Xamarin.Forms application that you can build and run, that leverages Shell.

image

And looks a little like this with bottom tabs and an ADD button in the navigation bar.

image

But let’s see what v4 is going to give us. Select “Include prerelease” and update to the latest packages.

image

Xamarin.Forms Shell v4

One addition that is more of a cosmetic improvement is the naming of ShellItem and ShellSection – I think the initial intent of these were that they should be somewhat abstracted for the actual UI implementation. However, as Shell has matured, the reality is that ShellItem maps to an item that appears in the flyout and an ShellSection maps to a tab…..

Wow, hold on, what are these things ShellItem, ShellSection and ShellContent? If you haven’t been following what the Xamarin.Forms team have been working on then Shell might come as a bit of a surprise. However, as nearly every app developer will admit, one of the most painfully tedious parts of building an application is create and linking all the pages of the application so that the user can navigate between them. The cognitive load of how to do master-details or tabs even in Xamarin.Forms makes it hard for developers to get started. What Shell aims to achieve is to provide a declarative way for you to define how your application is structured.

Essentially Shell represents a hierarchy of navigation elements:

– Shell – this is represents the application as a whole

– ShellItem – these are the first level pages of the application. Currently if there are multiple ShellItems defined, they’ll automatically appear in a Flyout.

– ShellSection – a page can be broken into sections which essentially map to bottom tabs. If a ShellItem only has one ShellSection, no tabs will show.

– ShellContent – this is the actual page content that will be displayed within the bottom tabs. If a ShellSection has multiple ShellContent, tabs will appear at the top of the tab giving you a tab-sandwich display.

In v4, to make it easier for developers to clearly see what was going on, additional classes, FlyoutItem and Tab were added that sub-class ShellItem and ShellSection respectively. The following example layouts use the new element names – if you’re still on v3.6 of Xamarin.Forms you will need to stick with ShellItem and ShellSection.

Some examples:

Single Page Application

image

Notes:

For a single ShellContent there’s no need to include a Tab element, simply nest it directly under the FlyoutItem.

– The FlyoutBehavior attribute can be used to hide/show the flyout on different pages in the application, or (as in this case) across the whole application. Use Shell.FlyoutBehavior on individual FlyoutItem elements to hide the flyout on those pages.

<Shell … FlyoutBehavior=”Disabled”>
     <FlyoutItem … >
         <ShellContent … />
     </FlyoutItem>
</Shell>

Two Page Application With Flyout

image

<Shell …>
     <FlyoutItem Title=”Home” … >
         <ShellContent … />
     </FlyoutItem>
     <FlyoutItem Title=”Single Page” … >
         <ShellContent … />
     </FlyoutItem>
</Shell>

Looking at the different combination of FlyoutItem, Tab and ShellContent we can get different page behaviours:

Bottom Tabs

image

<FlyoutItem Title=”Bottom Tabs” … >
     <Tab Title=”Home” >
         <ShellContent … />
     </Tab>
     <Tab Title=”Activity” … >
         <ShellContent … />
     </Tab>
</FlyoutItem>

Top Tabs

image

<FlyoutItem Title=”Top Tabs” … >
     <Tab Title=”Activity” … >
         <ShellContent Title=”Shared” … />
         <ShellContent Title=”Notifications” … />
     </Tab>
</FlyoutItem>

Tab Sandwich

image

<FlyoutItem Title=”Tab Sandwich” … >
     <Tab Title=”Activity” … >
         <ShellContent Title=”Shared” … />
         <ShellContent Title=”Notifications” … />
     </Tab>
     <Tab Title=”Updates” … >
         <ShellContent Title=”Updates” … />
         <ShellContent Title=”Home” … />
     </Tab>
</FlyoutItem>

As you will have briefly seen, it’s possible to rapidly stand up the basics of an application using a combination of flyouts and tabs to structure your application. In this post we’ve referenced the preview of the next version of Xamarin.Forms Shell, so you can expect that some of the features, particularly around navigation are subject to change in the coming months.

Debugging ASP.NET Core with Visual Studio and Docker Desktop

Debugging ASP.NET Core with Visual Studio and Docker Desktop

With Visual Studio 2019 hot off the press I’ve been experimenting with a few of the new project templates and the improvements that have been made in Visual Studio. In this post I’m going to cover how to solve a particularly annoying problem I encountered when attempting to run and debug an ASP.NET Core 3 application from within Visual Studio, hosted within a Docker image. I’ll walk through the whole process of creating the new project and the issue I ran into when first attempting to debug the application.

When you launch Visual Studio 2019, or go to create a new project, you’ll see the Create a new project dialog. We’re going to select the ASP.NET Core Web Application template.

image

Next we need to provide the standard project information such as name and location.

image

The next stage is to provide more information about how the template should be configured. Here we’re selecting the API template from the left of the screen, and checking both the https and the Enable Docker Support.

Note: At this point if you haven’t already downloaded and installed Docker Desktop, do it now. It’s a half Gb or so download, so not small, and may take a while based on your network bandwidth.

image

After creating the template, you’ll see that there are a number of options available to us in order to run the application. We’re going to proceed with the Docker option.

image

If you haven’t already, make sure you have launched Docker Desktop, otherwise you’ll see the following warning in Visual Studio when you attempt to run the application.

image

Unless you’ve previously setup Docker Desktop you’ll most likely see the following error. Essentially you need to award Docker Desktop access to a drive in order to create images etc.

image

Right-click the Docker icon in the tray and select Settings

image

Under Shared Drives tab, check the local drives you want to make available to Docker Desktop.

image

When you click Apply you’ll be prompt to authenticate. It will detect the credentials of the current user, which for me is an Azure Active Directory user.

image

Important: Unfortunately after providing my password and clicking OK, Docker Desktop decides that it will uncheck the drive that I had selected. This seems to be a common issue, raised by a couple of different people online. Anyhow, the following steps demonstrate how to setup a different account and using it to allow Docker Desktop to access the drive. Whilst a bit hacky, this does seem to be the only work around for this issue.

To setup a new account launch Settings, click Other users and then click the + button under Other users.

image

When prompted to enter email or phone number, instead click the “I don’t have this persons’ sign-in information” option.

image

Next, click the “Add a user without a Microsoft account” option

image

When prompted, enter username, password and some security questions. Next you need to change this user to be an administrator, so expand out the account under Other users and click Change account type.

image

Change Account type to Administrator

image

Return now to Docker Desktop and enter the new account as part of setting up the shared drive. You shouldn’t see any further issues within the Docker Desktop application.

image

Attempting to run the application from within Visual Studio again reveals an error, this time complaining it doesn’t have authority to crLeate or adjust folders (including creating files). 

image

Locate the folder indicated in the error message, right-click on the folder and select Properties. From the Security tab, click Edit.

image

Add the local account you just created and make sure it’s assigned all permissions.

image

You may need to repeat this process for 2 or 3 folders that Docker Desktop requires access to, and in some case assigning permissions can take a minute or two. Once done, your application will be launched from within a Docker image, with the Visual Studio debugger attached.

Visual State Manager Tooling in Xamarin.Forms With BuildIt.States

Visual State Manager Tooling in Xamarin.Forms With BuildIt.States

Back in the days of Silverlight/Windows Phone Microsoft launched a tool called Expression Blend that allowed developers and designer to work in harmony with developers doing their thing (ie write code) in Visual Studio and designers creating the user experience in XAML using Expression Blend. Fast forward a few years and Expression Blend has been rebadged to Blend for Visual Studio and most of the features of Blend have now been migrated to Visual Studio. With the demise of Windows Phone and the lack of developer interest in building for just Windows, Blend is now a tool that most developers have all but forgotten. So, why am I bringing this up now? Well, one of the features I missed from Blend is the ability to have design time data that allows you to build out the entire user interface, with the design time data being replace by real data when the application is run. Whilst there have been some attempts at providing a design time experience for Xamain/Xamarin.Forms, the reality is that it comes no where close to what Blend was able to do in its heyday.

If we look at other platforms, such as React Native, there has been a shift away from design time experience, across to an interactive runtime experience. By this I mean the ability to adjust layout and logic of the application whilst it’s running, which relies on the platform being able to hot-reload both layout and logic of the application. There are some third party tools for Xamarin.Forms that partially enable this functionality.

One of the challenges I found when working with Visual States is that you often need to get the application to a certain point, or follow a particular sequence of steps in order to get a specific Visual State to appear. Take the example I provided in my previous post on page states where I provided DataLoaded and DataFailedToLoad states – in the example the appearance of these states was completely random, so you might have to click the button a couple of times in order to get the state to appear. Luckily, the BuildIt.Forms library has a slightly-hidden feature that allows you to manually switch between states. I say it’s slightly-hidden because if you connect your Visual States to a StateManager in your ViewModels (shown in either this post or this post) you’ll see this feature automatically. In the example I covered in my previous post I needed to add the following line to the end of the MainPage constructor:

public MainPage()
{
     InitializeComponent();
    var groups = VisualStateManager.GetVisualStateGroups(this);
}

Now, when I run the application I see a small dot appear in the bottom left of the screen.

image

Clicking on the dot reveals a flyout that allows you to switch states:

App14UWP20190317125937

Note that this is only shown when the Visual Studio debugger is attached so will not impact the way your application works in release mode.

Updated Uno Visual Studio Extension

Updated Uno Visual Studio Extension

I just noticed that the Uno Visual Studio Extension has been updated, so I figured I’d give it a go in Visual Studio 2019. After installing the extension I used the new startup dialog on Visual Studio to “Create a new project”. I searched Uno but Cross-Platform or any of the target platforms would show you the templates.

image

After selecting the Cross-Platform App (Uno Platform) template I had to enter a few details before hitting Create

image

Seconds later I had a brand new solution with five projects giving me the ability to target iOS, Android and Wasm all from the code I write in a UWP app.

image

Selecting the Wasm project I set it as the startup project and hit F5 to run. After a few minutes of building (the first build is slow as it downloads packages etc) it launched Chrome with my fancy Hello World project running.

image

Note: Small confession that I had to run the project twice because the first time failed without error. On second attempt it ran successfully. However, it’s been a bit hit and miss in terms of getting it to run. I added “<MonoRuntimeDebuggerEnabled>true</MonoRuntimeDebuggerEnabled>” to the csproj file and that seems to have got it to run more reliably.

Adding Content

I wanted to add some content to my page but figured I’d start off slow – how about a couple of labels and a button:

<Page
     x_Class=”FirstUnoProject.MainPage”
    

    
    
    

    
     mc_Ignorable=”d”>
   <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”>
     <StackPanel>
       <TextBlock Text=”Hello, world !” Margin=”20″ FontSize=”30″ />
       <TextBlock Text=”Hello, world !” Margin=”20″ FontSize=”30″ />
       <TextBlock Text=”Hello, world !” Margin=”20″ FontSize=”30″ />
       <Button Content=”Press Me!” Click=”IveBeenPressed” />
     </StackPanel>
   </Grid>
</Page>

and a bit of code behind:

public async void IveBeenPressed(object sender, RoutedEventArgs e)
{
     await new MessageDialog(“I’ve been Pressed!”, “Pressed”).ShowAsync();
}

Now tell me you don’t expect this to work on the web, right? Sure enough works a treat.

image

It’d be great if the message box had “Pressed” as the title instead of “localhost:5210 says” but I’m still mind blown that this still works?

One thing to be aware of is that I’ve had some mixed experiences with Wasm as the resoluts seem to vary depending on which combination of Uno packages are referenced. This is definitely a work in progress but I feel that this is probably in line with where WebAssembly support is at across the board.

Unboxing Xamarin.Forms Shell in Visual Studio 2019

Unboxing Xamarin.Forms Shell in Visual Studio 2019

In my previous post, Unboxing Visual Studio 2019 for Xamarin.Forms, I covered creating a new Xamarin.Forms project in Visual Studio 2019. The Xamarin.Forms project template hasn’t really changed much and the default application you get is the same as what we were seeing in the most recent updates for Visual Studio 2017. However, there are some big updates coming down the line for Xamarin.Forms developers, not the least is Shell, which is covered in the introductory post.

I’m going to take Shell for a bit of a spin, and to do so, I’m going to use the new project templates that are available for download – These will only install into Visual Studio 2019, so if you want to try them out, you’ll first need to install Visual Studio 2019

image

An hours or so later…

image

After installing the new templates I went about creating a new project

image

It seems that the new templates must have completely replaced the previous templates – not a great start, considering I’m likely to want to be able to create a non-shell based Xamarin.Forms application.

image

Ummm…. Where’s the UWP support? Seriously, as if UWP wasn’t failing hard enough as it is, the fact that there doesn’t appear to be UWP support in the initial Shell release it a bid depressing.

After that the new project screens all look familiar, so the next thing we’re looking at is the default solution structure.

image

My first comment (as usual) is that the view models are stuck in the same project as all the UI elements – I consider this to be incredibly bad practice as it means you end up with a mess of dependencies and it’s way to easy to break the separation of concerns between view and view models. Having said that, this is a getting started templates, so I guess if they’d added another project it would probably alienate other developers who prefer to have everything in a single project.

The great thing is that I can select either iOS or Android as my startup project and hit run – a minute or two later after the emulator has started up the app has been deployed and is running.

Side Note: This post actually took me a couple of sessions because I got interrupted and it took a couple of days for me to get back to it. When I did, I accidentally opened the XamShell app I’d created in Visual Studio 2017, where it builds and runs without issue. Of course I don’t have the Shell templates.

Here are a couple of screenshots from the running app – Firstly I love that they’re replaced the Xamarin logo added to the new project, as shown in the splashscreen. Note that this is not actually a splashscreen and that in fact they’re setting the background on the main activitiy. There’s so debate about whether this is best practice, or whether it’s still good to use a splashscreen to improve the perceived boot time of the app.

image

This is the master-details template, so we get things like the burger menu. The main screen includes a basic list and an add button in the navigation bar – pretty stock look and feel.

image

The about page is a little more interesting but again nothing mind-blowing.

image

If we look in the main XamShell project we notice that in addition to the usual App.xaml, which is required for Xamarin Forms, there is now also an AppShell.xaml. At this point I did in fact switch back to Visual Studio 2019 because opening AppShell.xaml in VS2017 seemed to be a bit of a broken experience.

Opening AppShell.xaml the first thing I noticed is that styles have been setup and a combination of implicit and explicit styles defined – yes!!! this is great to see in a template. Next I noticed that two pages have been defined: Browse and About – this confused me as there are actually 4 pages included in the project. On checking the code, it appears that the other pages are dynamically created as needed. The introductory documentation on Shell provides a good overview of the key elements that make up the Shell hierarchy.

My initially impressions are that this is going to be great for jump starting basic mobile applications. I’m interested to see how far this can be taken and how it can handle more complex navigation patterns and applications. I’ll explore further the various aspects of Shell but I’d encourage all Xamarin Forms developers to give Shell a chance – let’s see whether this can be made into something amazing by providing constructive feedback to the XF team.

———-

Contact Built to Roam for more information on building cross-platform applications

———-

Unboxing Visual Studio 2019 for Xamarin.Forms

Unboxing Visual Studio 2019 for Xamarin.Forms

I’ve just installed the preview for Visual Studio 2019 and wanted to share the experience of creating a new Xamarin.Forms application.

Firstly, the startup screen. Whilst I’m disappointed not to have the news feed, the new startup screen gives you a quick launching pad for whatever it is you want do in VS2019.

image

Let’s go with “Create a new project”. The search/filtering works well to quickly find the right project template

image

Now let’s provide some generic project information.

image

Ah and now we’re back to a familiar dialog for creating Xamarin.Forms applications. Hooray!!! there’s no option to use a shared library any more – good riddance. As you’ll see we get a .NET Standard 2.0 project where our XF pages and other logic will go.

image

And now we have the usual solution structure for an out of the box XF application containing the project that’ll house the pages (ie VS2019XFProject) and then head projects for iOS, Android and UWP.

image

Let’s hit run and check out the newly created project – notice I picked the Master-Detail template early so we get a basic layout with a hamburger button in top left.

image

And that’s it. BTW the chrome around the edge of the coding window seems to be progressively shrinking with each progressive release of Visual Studio. Eventually it’ll be carved back to what Visual Studio Code offers.

———-

Contact Built to Roam for more information on building cross-platform applications

———-

Android Emulator Exception after updating to Visual Studio 15.9 preview 3

Android Emulator Exception after updating to Visual Studio 15.9 preview 3

I noticed earlier this evening that there was an update available for Visual Studio 15.9. Normally I wait a few days to update as I’m not in any particular hurry but I noticed in the blog post and release notes that work had been done on the Android build and execution. I also remembered that I hadn’t updated Visual Studio or my emulator images since updating my Surface Book 2 to the latest Windows update – it contains a fix for the awful performance of the Android emulator running on Windows hypervisor. Anyhow, the upshot is that I updated Visual Studio to the latest preview….

I decided to drop my existing emulator images and create new ones. Unfortunately this was a bad idea as I was then unable to start the new emulator images. When I attempted to start the emulator I would get an error stating “The requested operation requires elevation. (Exception from HRESULT: 0x800702E4)”.

image

Turns out I’m not the only person seeing this, as someone had already reported this issue.

It also turns out that there’s a simple solution…. close the Android Device Manager and just hit Run from within Visual Studio. Turns out that this causes the emulator image to boot, deploy and run the application. And all the updates seem to do the trick, debugging is back to an acceptable speed.

Debugging Not Working for .NET Standard library in UWP Application

Debugging Not Working for .NET Standard library in UWP Application

I was attempting to debug some code in a .NET Standard library that was being referenced from a Xamarin.Forms base UWP application. Unfortunately, it didn’t matter where I set the breakpoint in the library, they were never hit. Initially I thought that this was related to it being a multi-targeted project but it turns out this same issue applies to a regular .NET Standard library.

The only hint I had was when the application was running there was a yellow warning triangle on my breakpoint which a pretty unhelpful, yet accurate, message.

image

Now you’d have thought that since this project was included in the same solution as the application, that it was being built by Visual Studio as part of building and running the application, that you wouldn’t have to do anything special to get step through debugging to work. This is not the case – it appears that debug symbols can’t be loaded – huh! I mean seriously, we expect better.

I had also recently installed the first preview of Visual Studio 2017 15.9 so I thought that might be the issue but no, even opening it in 15.8 still showed the same issue.

So it turns out that there is an issue with the default build configuration – open project properties for the .NET Standard library and click on Advanced under the Build tab

image

The default “Debugging information” value of Portable is what the issue is. Change this to Full or Pdb-only

image

Doing this will set the debugging settings for the currently selected target framework and platform. For example for my project it generated:

<PropertyGroup Condition=”‘$(Configuration)|$(TargetFramework)|$(Platform)’==’Debug|netstandard2.0|AnyCPU'”>
   <DebugType>pdbonly</DebugType>
   <DebugSymbols>true</DebugSymbols>
</PropertyGroup>

I simplified this so that it would always use these debugging settings when doing a Debug build

<PropertyGroup Condition=”‘$(Configuration)’==’Debug'”>
   <DebugType>pdbonly</DebugType>
   <DebugSymbols>true</DebugSymbols>
</PropertyGroup>

And there you have it – step through debugging should now work. I’m not sure why it’s so hard for Visual Studio to either use this option by default, or at least provide a useful warning that directs the developer to either documentation, or actually switches the setting automatically.

Xamarin Development with Visual Studio 2017 Version 15.5

Xamarin Development with Visual Studio 2017 Version 15.5

Normally I don’t bother posting anything about the progressive updates that roll out for Visual Studio 2017 but version 15.5 adds a bunch of new features that are set to make app development using Xamarin just that little bit nicer. Pierce has a great post covering a lot of the relevant updates – https://blog.xamarin.com/whats-new-visual-studio-2017-version-15-5/ 

Over the last 6-12 months the debugging experience for Xamarin applications on both iOS and Android has got significantly better. I posted recently about my discovery that the Google Android emulator was actually quite good (https://nicksnettravels.builttoroam.com/post/2017/10/11/Hey-who-moved-my…-Visual-Studio-Emulator-for-Android.aspx), and whilst the build and deploy process is still painfully slow on Android, it’s definitely getting better. Now with Live XAML Previewing supported in the emulator, at least the iteration whilst making UI changes will be quicker.

I’ve also been using the remote iOS simulator – particularly at home where I use a remote build server that is on the other side of the room, it’s painful to have to deploy to a real device. I have seen some issues where debugging with the remote iOS simulator seems to just lock up but I think that was only an issue in the preview of VS mixed with the latest Windows Insider build (unfortunately neither team seems to care much about stability with their preview builds Sad smile).

Whilst I’m talking about doing iOS development, the other significant improvement in 15.5 is the messaging regarding connecting to the Mac build agent. In the past this has been limited to success/fail; if you wanted any more details you really had to go hunting in the log files (usually it ended up being a result of a mis-match of SDK versions between the build agent machine and the machine with VS installed). The dialog for connecting to the Mac build agent has a nice progress information pane at the bottom that shows what step the connection manager is at and reports any issues – nice work MS, this is really, really useful!

Ok, I can’t end this post without pointing to the fact that Microsoft has finally worked out how to get the elephant out of the corner of the room, and by this I mean the support for PCLs v’s .NET Standard for new projects. Prior to this release if you created a new Xamarin project it would create a PCL for your shared code (and yes, I’m ignoring the Shared Project option, cause this should never be selected), and it was rather painful to have to upgrade it to .NET Standard (see https://nicksnettravels.builttoroam.com/post/2017/08/26/Getting-Started-Xamarin-Forms-with-NET-Standard.aspx if you’re still on an older version of Visual Studio). Now when you create a new Xamarin project you get a .NET Standard library and you can pick which target platform(s) you want to target (I would encourage you to pick all, unless you have a particular reason not to!).

Grab the latest version of Visual Studio 2017 and get coding!

Hey, who moved my… Visual Studio Emulator for Android?

Hey, who moved my… Visual Studio Emulator for Android?

A while ago, in response to a common frustration from Xamarin developers, Microsoft released the Visual Studio Emulator for Android and it even made it into the Visual Studio installer:

image

As a long-serving Windows Phone developer I embraced this decision as the emulator was based on Hyper-V which meant that it played nicely with the Windows Phone emulators – I could now do cross platform development, even when I didn’t have real devices with me. Unfortunately, Microsoft have indicated that the emulator is no longer going to receive updates, so anyone wanting to dev/test on more recent builds of Android are out of luck. This was really frustrating as the emulator was both quick (relative to the out of the box emulators from Google – historically) and didn’t require another emulator sub-system (as it worked on Hyper-V).

Recently, Microsoft have actively discounted Windows Phone, making it very hard to justify any developer resources on building for Windows Phone…. it also makes me question the value proposition of UWP over WPF, but that’s a topic for a different post. The upshot is that there is no longer a reason for me to have the Windows 10 Mobile emulators installed, which means I have no need for Hyper-V, which means I can use any one of the great Android emulators out there that don’t play nice wiht Hyper-V.

What’s really cool is that Microsoft have included the Google Android Emulator in the Visual Studio installer. You need to make sure that both the Google Android Emulator and the Intel Hardware Accelerated Execution Manager are installed.

image

After installing the Google emulator you can launch your application on the emulator the same way you would to a real device – it appears in the devices dropdown. You can also access the different emulator images via the Android Emulator Manager.

image

Whilst the Android Emulator Manager is not a great looking dialog, it does allow you to customise and launch the different emulators.

image

I was so surprised when I launched the updated emulator. I was expecting an old, slow, crappy looking emulator but was surprised with an updated emulator shell with all the features that I’d come to expect from an emulator.

image

I’m a convert – Whilst I’ll still use a real device for most development work, having a good emulator is critical for those times when I don’t have a device with me. Cudos to Microsoft for firstly pushing Google to build a better developer experience and secondly making the Visual Studio installer so simple to install the emulator.

Sidenote: I did have to update one component from the Android SDK. Make sure you read the build output window in Visual Studio if you are running into issues as it pointed me to an out of date component.