Speeding up Android Emulator using Windows Hyper-V – Tricks to make it work

image01.pngThe Android emulator is so very slow compared to the Apple iOS Simulator. But with recent changes in, the Android emulator is now a bit faster, though not as fast as Apple still.

Here’s all the lessons I learned with getting Android’s Emulator to run as fast as possible.

I assume you have installed Visual Studio 2019

Step 1: Enable Hyper-V  in your Bios

Look for “VT-X” or other “Virtualization” related terms. Often under “Security”:

0D3Zh.png

Step 2: Install Hyper-V on your Windows 10 PC

Search for “Add/Remove Windows Features” in the Start Menu. Add Hyper-V

enable-hyper-v-features.jpg

Step 3: Open the Android Device Manger in Visual Studio and “Factory Reset” your devices

2019-04-09 08_43_08-Android Device Manager.png

GOTCHA! Step 4: Edit your devices and make sure that the hw.gpu.mode is set to host. This will ensure that your PC’s GPU will do the heavy lifting.

2019-04-09 08_43_47-Hyper_81.png

Problems?

Make sure that your machine has Hyper V successfully installed. To do so, open a CMD prompt and type systeminfo. You should see this if all is well:

 

 

 

Advertisements

Debugging Xamarin Forms 3.6 and up

download.jpgWhen your app fails, is it your app, or is there a bug in Xamarin Forms? How to know? In this post I’ll show you how to run Xamarin Forms in debug mode so that exceptions are caught and displayed deep inside Xamarin Forms.

In my previous post I showed you how to debug Xamarin Forms 3.5 and below. 3.6 and above are very different (and easier).

Let’s get to it!

GOTCHA: Make sure you have all the UWP components from the Visual Studio installer or you’ll get errors building. When in doubt, just add it all.

2019-04-02 09_08_19-Window.png

GOTCHA: Delete any Xamarin Forms github repro you have.

Step 1: Create a folder to contain the GitHub source code. I use e:\GitHub

Step 2: Open the GitHub Windows Client and clone  Xamarin Forms Git Hub Repro . Switch to version 3.6

2019-04-02 09_06_16-Window.png

The code is now in e:\GitHub\Xamarin Forms

Step 3: With notepad, create this batch file  e:\GitHub\Build Xamarin NuGet.bat

e:\
cd E:\GitHub\Xamarin.Forms

PowerShell.exe -Command “& ‘Build XF By Batch file.ps1′”
PAUSE

Step 4: With notepad, create this ps1 file e:\GitHub\Build XF By Batch file.ps1

Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force

cd E:\GitHub\Xamarin.Forms
./Build.ps1 -Target NugetPack

Step 5: Double click Build Xamarin NuGet.bat to build

GOTCHA: It can take 6-10 minutes to build. Really. Coffee time….

2019-04-02 09_12_32-Window.png

Now we have the NuGet packages for Xamarin Forms on our machine.

In Visual Studio, add this Nuget repository , then upgrade your projects to the new Xamarin Forms build (Prerelease Nuget)

GOTCHA: Don’t forget to check the “Include Prerelease” checkbox.

2019-04-02 09_15_42-Window.png

GOTCHA: Update project by project, not the whole solution at once. I often get NuGet errors on the solution.

GOTCHA: Delete all bin/obj folder, restart Visual Studio then rebuild.

All done! Now you can debug into Xamarin Forms.

 

 

 

Xamarin.Forms ListView Scrolling Up/Down Detection

download.pngI have a FAB on my page and wanted it to fade when the ListView was scrolled down, and fade back when scrolling up. Here’s an easy way to do it.

I assume you have a image or button on your form called fabCreateButton.

Wire up the OnDisappearing event in your ListView to this in your code behind:

private int _lastItemAppearedIdx = 0;
private bool _lastDirectionWasUp = false;
 
private void ListView_OnItemDisappearing(object sender, ItemVisibilityEventArgs e)
{
    if (e.Item is AddressBookItem item)
    {
        var currentIdx = Model.Items.IndexOf(item);
        if (currentIdx > _lastItemAppearedIdx)
        {
            if (_lastDirectionWasUp == falsefabCreateButton.FadeTo(.3, 250, Easing.Linear);
            _lastDirectionWasUp = true;
        }
        else
        {
            if (_lastDirectionWasUp == truefabCreateButton.FadeTo(1, 250, Easing.Linear);
            _lastDirectionWasUp = false;
        }
        _lastItemAppearedIdx = currentIdx;
    }
}

 

animation.gif

Debugging Xamarin.Forms from GitHub

download.png

This is for version 3.4.0 and under, see below for 3.5.0 changes

Sometimes strange things happen in your app, it could be that a problem deep in Xamarin.Forms is the cause. Here’s a very condensed, simple way to have your App point to the Xamarin.Forms code so that errors can be caught and causes more easily determined.

Note: Breaking changes in 3.5.0, see below

This is heavily based on the guide at Xamarin, but simplified and condensed into a path I found that works.

For Windows – Visual Studio 2017/2019

Get the Code:

Install the GitHub Desktop application.

GOTCHA: If you’ve tried before delete any repo and start fresh.

Run it and choose the opportunity to Clone a repository from a Url. Enter the URL https://github.com/xamarin/Xamarin.Forms . I put my repos into E:\GitHub

2019-02-06 14_04_12-GitHub Desktop.png

Build the Code in Visual Studio

Turn off Resharper if you have it, it’ll slow you down really badly. You can re-enable it later.

Go to your repo, in my case E:\GitHub and open Xamarin.Forms.sln

Switch to the version branch you want to debug, like 3.4.0

When it loads in Visual Studio, Switch to Any CPU, then Build the Solution. This can take 5 minutes!!  You will see errors probably. You should be able to ignore them.

GOTCHA!! It must be Any CPU

2019-02-06 14_05_50-Maximizer - Microsoft Visual Studio  (Administrator).png

Close Visual Studio

Build the NuGet

Add a System Environment variable to where you have NuGet.exe. I put mine in e:\GitHub\

GOTCHA!! Add a \ to the end of the folder

2019-02-06 14_09_51-New System Variable.png

Open a Command Prompt and go to the main folder in the repo. In my case E:\GitHub\Xamarin.Forms

Run the batch file .create-nuget.bat all

GOTCHA – Did you forget the all parameter?

2019-02-06 14_12_20-Command Prompt.png

When done, there will be a new file named something like Xamarin.Forms.9.9.0.nupkg in the .nuspec folder

2019-02-06 14_14_10-.nuspec.png

Copy this file to a new Folder which will serve as your NuGet folder. I use E:\NuGetServer

2019-02-06 14_15_12-NuGetServer.png

Open your app, then add a new Nuget server pointing to that folder.

2019-02-06 14_15_53-Options.png

Now update your Xamarin Forms Package to point to your NuGet folder. Notice the version is 9.9.0.

2019-02-06 14_17_03-Maximizer - Microsoft Visual Studio  (Administrator).png

GOTCHA!! Manually delete all bin and obj folders and restart Visual Studio. I’ve had strange things happen when I switch Xamarin Forms versions if I don’t.

Run your app!

Now when there is an error, Visual Studio will step into the Xamarin.Forms code

Changes for version 3.5.0 onwards

Switching to Cake and powershell

Go to the Xamarin.Forms folder in Powershell, then allow for all scripts to be run with this:
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force

Then you can run the Build PowerShell:
./Build.ps1 -Target NugetPack 

 

The Growth of #Xamarin – An independent metric

download.pngI’ve been using #Xamarin for iPhone and Android app since it was pronounced “Monotouch”. I may have been one of the first commercial users. It’s a great platform, but is it growing? Here’s an interesting and independent metric.

My Xamarin blog’s visitors trend is below. I don’t advertise, I just write articles on things I find interesting. Then let Google and the internet decide if it’s of value.

Note: I wrote this at the start of Feb, 2019 hence the low last value.

Screen Shot 2019-02-03 at 12.07.36 PM.png

Xamarin.Forms: Coach Marks

2019-01-17 11_27_56-coach marks - Google Search.pngA Coach Mark is an overlay which helps teach a new user about a feature. This post will show you how to do it easily in Xamarin.Forms

Here’s the way the screen will look. You could replace the Text with an image, and a “Close” button is a good idea as well.

Image-1.jpg

Step 1:

Here’s a ContentView:


 
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
             xmlns:gestures="clr-namespace:MR.Gestures;assembly=MR.Gestures"
             x:Class="Max.Views.Common.CoachMarksView">
	<ContentView.Content>
		<gestures:Grid Tapped="Grid_OnTapped">
			<ContentView>
			<Frame
			       BackgroundColor="#000000"
			       Opacity="0.6"
			       Padding="0"
				   Margin="0"
			       HorizontalOptions="FillAndExpand"
			       IsVisible="true" 
			       VerticalOptions="FillAndExpand"  CornerRadius="0" />
			</ContentView>
			<Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"  >
				<Grid.RowDefinitions>
					<RowDefinition Height="Auto"></RowDefinition>
					<RowDefinition Height="*"></RowDefinition>
					<RowDefinition></RowDefinition>
				</Grid.RowDefinitions>
 
				<ffimageloading:CachedImage Grid.Row="0" x:Name="Image" CacheDuration="0" FadeAnimationEnabled="True"></ffimageloading:CachedImage>
			</Grid>
		</gestures:Grid>
	</ContentView.Content>
</ContentView>

Step 2: The Bindings

	public partial class CoachMarksView : ContentView
	{
		public CoachMarksView ()
		{
			InitializeComponent ();
		}
 
		public string CoachImageUrl
		{
			get { return (string)GetValue(CoachImageUrlProperty); }
			set { SetValue(CoachImageUrlProperty, value); }
		}
 
		public static readonly BindableProperty CoachImageUrlProperty =
			BindableProperty.Create(nameof(CoachImageUrl), typeof(string), typeof(CoachMarksView),
				propertyChanged: (bindable, oldValue, newValue) => ((CoachMarksView)bindable).PopulateCoachImageUrl());
 
 
		public EnumCoachMarkPosition CoachImagePosition
		{
			get { return (EnumCoachMarkPosition)GetValue(CoachImagePositionProperty); }  
			set { SetValue(CoachImagePositionProperty, value); }
		}
 
		public static readonly BindableProperty CoachImagePositionProperty =
			BindableProperty.Create(nameof(CoachImagePosition), typeof(EnumCoachMarkPosition), typeof(CoachMarksView),
				propertyChanged: (bindable, oldValue, newValue) => ((CoachMarksView)bindable).PopulateCoachImageUrl());
 
 
 
 
 
		void PopulateCoachImageUrl()
		{
			if(CoachImageUrl.HasValue()) this.Image.Source = CoachImageUrl;
 
			switch (CoachImagePosition)
			{
				case EnumCoachMarkPosition.TopRight:
					Image.HorizontalOptions=LayoutOptions.End;
					Image.VerticalOptions=LayoutOptions.Start;
					break;
				case EnumCoachMarkPosition.TopLeft:
					Image.HorizontalOptions=LayoutOptions.Start;
					Image.VerticalOptions=LayoutOptions.Start;
					break;
				case EnumCoachMarkPosition.BottomRight:
					Image.HorizontalOptions=LayoutOptions.End;
					Image.VerticalOptions=LayoutOptions.End;
					break;
				case EnumCoachMarkPosition.BottomLeft:
					Image.HorizontalOptions=LayoutOptions.Start;
					Image.VerticalOptions=LayoutOptions.End;
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}
 
		}
 
		private void Grid_OnTapped(object sender, TapEventArgs e)
		{
			this.IsVisible = false;
		 
		}
	}

 

Xamarin: Search As You Type with Delay

download.jpgI have an Entry Textbox that searches as the user types. I don’t want the search on every letter, but rather wait 0.5 seconds between typing then search on what the current Query Text is. So as the user types the Query builds a string. That string is searched on every 0.5 seconds, not after every keystroke.

Let’s say the user types CANADA, here’s what happens:

C {WAIT}
CA {WAIT}
CAN  {Search}
CANA {WAIT}
CANAD {WAIT}
CANADA {SEARCH}

Here how:

In your XAML put a SearchBar with a Command (Behaviors):

<SearchBar Text="{Binding Query}" Placeholder="Search Address Book">
   <SearchBar.Behaviors>
      <behaviors:EventHandlerBehavior EventName="TextChanged">
	 <behaviors:InvokeCommandAction Command="{Binding RefreshCommand}" />
      </behaviors:EventHandlerBehavior>
    </SearchBar.Behaviors>
</SearchBar>

When the user types we store the Text in the Model’s Query property and call the RefreshCommand in the model for changes. This is a common way to do searches.

Here’s the magic you need to put into your Model (thanks to SO)

public ICommand RefreshCommand => 
       new Command(async () => { 
     await DelayedQueryForKeyboardTypingSearches().ConfigureAwait(false); });
private CancellationTokenSource throttleCts = new CancellationTokenSource();
/// <summary>
/// Runs in a background thread, checks for new Query and runs current one
/// </summary>
private async Task DelayedQueryForKeyboardTypingSearches()
{
  try
   {
     Interlocked.Exchange(ref this.throttleCts, new CancellationTokenSource()).Cancel();
      await Task.Delay(TimeSpan.FromMilliseconds(500), this.throttleCts.Token)
	.ContinueWith(async task => await Refresh()  , 
                  CancellationToken.None, 
                  TaskContinuationOptions.OnlyOnRanToCompletion, 
                  TaskScheduler.FromCurrentSynchronizationContext());
	}
	catch  
	{
		//Ignore any Threading errors
	}
    }
}