Creating a Simple Typescript Polymorphism Logger

java-polymorphism-featured-image-1280x720.pngIf you are coming from a Java or C# background you are familiar with the idea that an object that implements an IAnimal interface can be a Dog or Cat. That’s Polymorphism.

In this Typescript tutorial, I’ll show you how to use this, simply, to have your app write out to the console a log or error message.

First, let’s define our object to be a function that expects a message and returns nothing.

let logger: (message: string) => void;

Now let’s create that “Dog and Cat” implementation. One to output errors and one for messages.

Notice how the interface of the functions matches the logger we defined above:

function error(message: string): void {
  console.error(message);
}

function log(message: string): void {
  console.log(message);
}

We can now assign the logger to be a log or error function depending on the input. If the age is more than 5 then we log, else we error out.

let age: number = 5;
if (age>5) {
   logger = log; 
} else {
   logger = error;
}

logger(`${age} was the age`);

In the console of the browser we see:

2019-10-18 15_12_52-https___localhost_44351.png

Advertisements

Use Typescript to QA your Javascript in Visual Studio

images.pngIf you haven’t yet made the plunge into Typescript, and you should, here’s a way to leverage the Typescript engine to QA your Javascript code.

Open your Visual Studio 2019 Asp.Net project and go to your folder where your Javascript files are located.

2019-10-18 14_01_34-Window.png

Add a new file called tsconfig.json and enter this as the contents:

{
  "compileOnSave": true,
  "compilerOptions": {
    "strictNullChecks": true,
    "strict": true,
    "noEmitOnError": true,
    "noImplicitAny": true,
    "esModuleInterop": true
  }
}

Rename one of the file by changing the .js extension to .ts

2019-10-18 14_05_08-Window.png

Note: Visual Studio may suggest you add a NuGet Typescript package, that’s fine todo, it’s harmless.

In my bad.ts file I have some Javascript that has a bug. The variable is defined after it is used. Javascript is fine with that, but when you rename the file to .ts, then the TypeScript engine will kick in and show you a red squiggly:

2019-10-18 14_07_02-Window.png

Hovering over it will show the error:

2019-10-18 14_08_03-Window.png

Fix the problem, verify no more squiggles and then rename the file to .js

I hope you move to Typescript, but if you can’t, then you can at least use the Typescript engine to verify your Javascript.

 

 

 

 

Xamarin: Using Telerik TabView with Data Trigger Colors

Xamarin TelerikThe Telerik TabView for Xamarin is a great tool to hold and alter the content of several pages. One of the downsides is that the styles offered are a bit limited. I wanted to change the Text color fo the Tab Header Text to be white or off-white depending on the selected state.

No problem as Xamarin as Data Triggers that can change the property of an item depending on the value of data.

Step 1: Add a custom TabViewItem header

<telerikPrimitives:TabViewItem.Header>
	<telerikPrimitives:TabViewHeaderItem>
	   <telerikPrimitives:TabViewHeaderItem.Content>
                <Label Text="SAVED SEARCHES" />
           </telerikPrimitives:TabViewHeaderItem.Content>
	 </telerikPrimitives:TabViewHeaderItem>
</telerikPrimitives:TabViewItem.Header>

In the above, we now have a label for the header. the next step is to add Data Triggers to that Label so that when IsSelected is changed, the Data Trigger will change the Label’s color

Step 2: Attach a Data Trigger to the Label

<Label Text="SAVED SEARCHES">
  <Label.Triggers>
     <DataTrigger TargetType="Label" Binding="{TemplateBinding IsSelected}" Value="True">
	 <Setter Property="TextColor" Value="White"></Setter>
     </DataTrigger>
     <DataTrigger TargetType="Label" Binding="{TemplateBinding IsSelected}" Value="False">
         <Setter Property="TextColor" Value="#aaffffff"></Setter>
     </DataTrigger>
</Label.Triggers>

A Data Trigger is like a sentence. you can read it like this:

WHEN the IsSelected IS true THEN change the TEXTCOLOR to white.

WHEN the IsSelected IS faflseTHEN change the TEXTCOLOR to off-white.

Here’s the result with several tabs:

2019-10-18 11_31_18-iPhone 11 iOS 13.1.png

.Net C# Getting a rich DateTime Duration object to represent 2 dates

2019-07-26 14_34_23-0638616_PE699035_S5.JPG (600×600).pngOften I need to find the duration between two dates, but with more metadata to better explain the duration, but also to be Linq compliant.

First, let’s create a class which will be the container for our metadata and will help us render more human-readable durations:

public enum EnumDurationKind
{
    NotSet,
    Minute,
    Hour,
    Day,
    
}
public class Duration
{
    public EnumDurationKind Kind { getset; } = EnumDurationKind.NotSet;
    public int Amount { getset; }
 
    public override string ToString()
    {
        var x = ""; 
        switch (Kind)
        {
            case EnumDurationKind.Minute:
                x = "m";
                break;
            case EnumDurationKind.Hour:
                x = "h";
                break;
            case EnumDurationKind.Day:
                x = "d";
                break;
        }
 
        if (x.IsNullOrEmpty() && Amount == 0) return "";
 
        return $"{Amount}{x}";
    }
}

Now, an extension method to pull out the metadata:

public static Duration GetDurationBetweenTwoDates(this DateTime startDateDateTime endDate)
        {
            Duration result = new Duration();
                DateTime from = startDate;
                DateTime to = endDate;
 
                TimeSpan total = to - from;
                var mins = Convert.ToInt32(Math.Round(total.TotalMinutes,0));
                var hours = Convert.ToInt32(Math.Round(total.TotalHours, 0));
                var days = Convert.ToInt32(Math.Round(total.TotalDays, 0));
 
                //Special case for hours, like 100
                if (mins > 0 && mins % 60 != 0)
                {
                    result.Amount = mins;
                    result.Kind = EnumDurationKind.Minute;
                }
 
                //Special case for hours, like 26
                if (result.Kind == EnumDurationKind.NotSet && hours > 0 && hours % 24 != 0)
                {
                    result.Amount = hours;
                    result.Kind = EnumDurationKind.Hour;
                }
 
                if (result.Kind==EnumDurationKind.NotSet && days > 0)
                {
                    result.Amount = days;
                    result.Kind = EnumDurationKind.Day;
                }
 
                if (result.Kind == EnumDurationKind.NotSet && hours > 0)
                {
                    result.Amount = hours;
                    result.Kind = EnumDurationKind.Hour;
                }
 
                if (result.Kind == EnumDurationKind.NotSet && mins > 0)
                {
                    result.Amount = mins;
                    result.Kind = EnumDurationKind.Minute;
                }
 

            return result;
        }

And finally, a test (one of many) to show it:

[Test]
public void Min_60()
{
    DateTime d = DateTime.Now;
    var duration = d.GetDurationBetweenTwoDates(d.AddMinutes(60));
    Assert.IsTrue(duration.Kind == EnumDurationKind.Hour);
    Assert.IsTrue(duration.Amount == 1);
}

 

Xamarin styles: Tips on managing XAML files

2019-07-26 10_11_57-artboard_2_1x.png (400×300).pngXamarin offers a wide range of style options to help you make your app consistent, and easy to change. Here are a few tips on how to manage a lot of style settings.

Let’s first create a xaml file with some simple styles. Create a new file in your main project called ThemeFonts.xaml. In this example, I create references for Font Awesome Pro fonts.

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                    x:Class="App.Themes.ThemeFonts">
 
    <OnPlatform x:Key="FontAwesomeLightFontFamily" x:TypeArguments="x:String"
                Android="fa-light-300.ttf#Font Awesome 5 Pro Light"
                iOS="FontAwesome5Pro-Light"/>
 
    <OnPlatform x:Key="FontAwesomeSolidFontFamily" x:TypeArguments="x:String"
                Android="fa-solid-900.ttf#Font Awesome 5 Pro Solid"
                iOS="FontAwesome5Pro-Solid" />
 
    <Style x:Key="FontAwesomeFontIcon" TargetType="Label">
        <Setter Property="FontFamily" Value="{DynamicResource FontAwesomeLightFontFamily}" />
    </Style>
 
    <Style x:Key="FontAwesomeFontIconSolid" TargetType="Label">
        <Setter Property="FontFamily" Value="{DynamicResource FontAwesomeSolidFontFamily}" />
    </Style>
</ResourceDictionary>

Make sure the Properties are set like this:

2019-07-26 10_02_02-BpApp - Microsoft Visual Studio.png

Now just reference this new file in your App.xaml.

Now your App.xaml is nice a clean. You can add more style xaml pages, each with an area of responsibility, to your app.

<?xml version="1.0" encoding="utf-8"?>
 
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:themes="clr-namespace:App.Themes;assembly=App"
             mc:Ignorable="d"
             x:Class="App.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <themes:ThemeFonts/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

 

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:

 

 

 

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.