VSTS and Automating Signing

Welcome

Happy new year everyone! Hopefully everyone had a good holidays (if that is your thing) and have come back refreshed, relaxed and ready for a new year. For my first post of 2018, I was going to switch it up from development and go into a bit of dev ops.

I was fortunate to see Donovan Brown present earlier this week at Microsoft Vancouver. It was a great presentation and demo and left me inspired to put some of those lessons to good use with one of my current projects, a .NET desktop addin.

Background

I am using Visual Studio Team Services Online for hosting my code repos, managing my backlog and bugs, but I haven’t made much use of the build systems. Setting up a build definition to build and run my unit test was pretty easy, and I was able to just use defaults for the most part.

But I had some struggles with how to automate the signing of the binaries. Afer doing some research on it, here is what I found and what worked for me.

Step 1

First we need to create a script of some kind to perform the actual signing of the files. I chose to use Powershell as I have never really worked with it before. In my Visual Studio solution directory I created a “build” folder and added the script there.

param($certFile, $pw, $buildDir)

Write-Host "****************************************"
Write-Host "****************************************"
Write-Host "*** S I G N I N G O U P U T ***"
Write-Host "****************************************"
Write-Host "****************************************"

Write-Host $buildDir
Write-Host $certFile

$exe = Get-ChildItem -Path "C:\program files (x86)\Windows Kits" -Recurse -Include signtool.exe | select -First 1
Write-Host $exe

$timestampUrl = "http://timestamp.comodoca.com/rfc3161"

ForEach ($file in (Get-ChildItem $buildDir))
{
  if ($file.Extension -eq ".dll")
  {
    Write-Host $file.FullName
    &$exe sign /f $certFile /p $pw -tr $timestampUrl $file.FullName
  }
  elseif ($file.Extension -eq ".exe")
  {
    Write-Host $file.FullName
    &$exe sign /f $certFile /p $pw -tr $timestampUrl $file.FullName
  }
}

So what is happening here? First thing is that this script takes three parameters:
– the location of the certification file
– the password for the certificate
– the build directory

We will look at how we get those parameters later during the task.

The first important thing the script does is locate the signing tool on the build agent. We know that it will be somewhere under the “C:\program files (x86)\Windows Kits” subdirectory, so we use the Get-ChildItem to recurse through that directory and return the first one it finds. It stores that location in a variable to be used later.

The next thing it doesis loop through the build directory for all of the .exe and .dll files. For each that it finds, it uses the sign tool, and the supplied certificate path and password to perform the signing.

The nice thing about the script above is that there is nothing in there that is project dependant. You can use this script on all of your projects.

Step 2

Next I had to upload my code signing certificate to VSTS. This is pretty easy to do, all you have to do is click on “Build and Release” on your menu, then click on “Library” and then “Secure Files”. Finally click on “+ Secure file” and upload your certificate.

codesignUploadSecureFiles

Step 3

Head over to your build definition by clicking “Builds” and then “Edit” from the build definition menu.

We are going to add a new task called “Download secure file”. You can give the task some kind of descriptive name, and then from the “Secure File” combo box, select your code signing certificate. I placed this task after the Test task.

codesignDownloadSecurefileTask

Now, if your tests pass, the build process will download the code signing certificate to your build host (either online or local). You should note that the build agent will clean up after itself.

Step 4

You need to add your certificate password to the list of variables for the build definition. In your build definition, click on variables and then “add” in the “Process Variables” group. Give your secret a name and provide the value. Don’t forget to click on the padlock to hide the value.

Once you save the build definition, the secret value is hidden. From the capture above you can see that I am unlocking my password and it doesn’t show the value.

Step 5

Finally, we just need to execute the script as a task in the build. Add a powershell task after the “download secure file” task that you created in step 3. You can make the type “File Path” and browse to the build script that we created in step 1 (remember to check it in). Next we need to add the arguments that the script is expecting.

codesignpowershellscript

Certificate file

The download secure files tasks dumps the files into the build agent work folder _temp directory. So the first parameter is “$(Agent.WorkFolder)_temp\CodeSigning2019.pfx”

Password

The process variable contains our password, and to reference it as a parameter for our script, we uses “$(pfxpassword)”. “pfxpassword” is the name in my build definition.

Build Output Directory

Finally we need to specify where the files that are to be signed are located. We use another built in variable. For my build definition it looks like this: “$(Build.SourcesDirectory)\SbSol\StructureBuilder\bin\release”

Setup Complete

And that is it. Now when your build is run, you should see the following output in the logs.

codesignbuildlogoutput

You can see where the script is started, it is the blue line. Notice that the password has been blanked out on the command line. You can see next that it is showing the location of the build directory and the certificate file and even the signtool.exe that it found on the build machine. Next you can see it looping through all of the output files and the output of the signing operation.

Wrapping up

That is how I did it. Seeing as I use Visual Studio for building my Xamarin Forms apps as well, I could probably do something similar to sign that output.

Using IValueConverter

I was down in Las Vegas all of last week for the Autodesk Forge DevCon and Autodesk University: a full four days of learning about all of the up and coming Autodesk products and technologies and networking. Lots of fun, lots of new people to talk to. I had a chat with a somewhat new’sh dev and he was complaining about the difficulties of using XAML. We delved into a bit of MVVM and he wanted to know, in effect, how to bind visual properties.

From there we went to the use of value converters and all the potential they have for presentation without having to embed visual elements and other complex logic into your view model. And it is available across WPF, UWP and Xamarin Forms.

A Simple Case

My first value converter was in WPF and making visual elements visible or not based on a value in my view model. Lets pretend we have some additional controls in our window that are only visible if the user is an accounting user. In our view model, it is a bool property named IsAccounting. If we try to bind the IsAccounting property to the control Visibility property, a binding error occurs that says the type of the value is incorrect for the target property: because of the error we won’t see the UI change.


<!-- fails -->
<TextBox Text="{Binding AccountCode}" Visibility="{Binding IsAccounting}" />

We need a value converter that will change the bool value to a Visibility value.


public class BoolToVisConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool v = (bool) value;
        return v ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

To use it, make sure that you have the namespace that the value converter resides in declared in your Window XAML and then the converter itself referenced in the resource dictionary:

xmlns:local="clr-namespace:Demo"
<Window.Resources>
    <ResourceDictionary>
        <local:BoolToVisConverter x:Key="boolVisConverter" />
    </ResourceDictionary>
</Window.Resources>

Finally you add the converter to the binding expression of the control:


<TextBox Text={Binding SecretAccountCode} Visibility={Binding IsAccounting,Converter={StaticResource boolVisConverter}}" />

And the application looks like this:

2017-11-19boolvisconverter

I like this because it keeps the app logic free of the presentation code, and this makes your view model simpler, testable and portable.

Something More Powerful

Let’s take a look at where the IValueConverter can really help. In this example we will change the color of the text in a textbox based and an image based on the selected item in a combo box. I setup an enum with some employee types:

public enum EmployeeTypeEnum
{
	CEO,
	VicePres,
	EngDirector,
	Engineer,
}

and added EmployeeTypes and SelectedEmployeeType properties to the view model.


/// initialize this collection in the constructor with the enum values.
public ObservableCollection<EmployeeTypeEnum> EmployeeTypes { get; private set; } =
    new ObservableCollection<EmployeeTypeEnum>();

private EmployeeTypeEnum _selectedEmployeeType = EmployeeTypeEnum.CEO;
public EmployeeTypeEnum SelectedEmployeeType
{
    get => _selectedEmployeeType;
    set => SetProperty<EmployeeTypeEnum>(ref _selectedEmployeeType, value);
}

Here are our value converters, one of them will convert the SelectedEmployeeType value to a foreground color and the other will convert the SelectedEmployeeType value to an image.

public class EmployeeColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        EmployeeTypeEnum empType = (EmployeeTypeEnum) value;
        switch(empType)
        {
            case EmployeeTypeEnum.CEO:
                return Brushes.Aqua;
            case EmployeeTypeEnum.EngDirector:
                return Brushes.Green;
            case EmployeeTypeEnum.Engineer:
                return Brushes.Red;
            case EmployeeTypeEnum.VicePres:
                return Brushes.Blue;
            default:
                return Brushes.Black;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class EmployeeImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        EmployeeTypeEnum empType = (EmployeeTypeEnum) value;
        switch (empType)
        {
            case EmployeeTypeEnum.CEO:
                return new Uri("/ceo.png", UriKind.Relative);
            case EmployeeTypeEnum.EngDirector:
                return new Uri("/director.png", UriKind.Relative);
            case EmployeeTypeEnum.Engineer:
                return new Uri("/engineer.png", UriKind.Relative);
            case EmployeeTypeEnum.VicePres:
                return new Uri("/vicepres.png", UriKind.Relative);
	    default:
	        return null;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Add our converters to the resource dictionary:

<local:EmployeeColorConverter x:Key="empColorConverter" />
<local:EmployeeImageConverter x:Key="empImageConverter" />

The markup for our XAML looks like this


<ComboBox ItemsSource="{Binding EmployeeTypes}" SelectedItem="{Binding SelectedEmployeeType}" />
<TextBox Text="{Binding SelectedEmployeeType}" Foreground="{Binding SelectedEmployeeType,Converter={StaticResource empColorConverter}}" Margin="0,2" />

<Image Width="48" Height="48" Margin="4" Source="{Binding SelectedEmployeeType,Converter={StaticResource empImageConverter}}" />

And that is it. We have a simple and portable view model that can be used on other platforms.

2017-11-19_6-35-24

Feel free to check out the sample code in GitHub.

I also would like to give a shout-out to SyncFusion as I used their free MetroStudio icon generator to build my icons.

Platform Services: Part 2

Hello from Las Vegas! I am down in Las Vegas for the Autodesk Forge DevCon and Autodesk University. A total of four days of an absolute fire hose of information and learning! I have a few minutes of downtime and I wanted to provide an update on the new direction of consuming platform specific services in your portable project.

In my original post, I showed you how Prism would use the Xamarin Forms built in dependency service to resolve an object if it couldn’t find it in the container that Prism uses. That was the accepted practice for version 6.3 and earlier, but now, in the upcoming 7.0 release, the authors have specified that all object resolution should be done via the Prism container.

Fortunately it is pretty easy.

In Prism, there is an interface that you implement for each of your platforms: IPlatformInitializer where T is your Prism container. I typically use Unity, so my implementation would look something like this:

public class AndroidInitializer : IPlatformInitializer<IUnityContainer>
{
    public void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IPortableInterface, DroidImplementation>();
        // other registrations
    }
}

Now you just need to pass that implementation into the LoadApplication call in the platform specific app initialization. Continuing with Android, it looks like the following:


[Activity(Label="projectname" ...)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App(new AndroidInitializer()));
    }
}

From there, it goes into your App object that is derived from your selected container specific PrisApplication class. The constructor takes one parameter of IPlatformInitializer which you just move along to the base constructor.


public class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null)
        : base(initializer)
    {
    }

    /// ... rest of your implementation
}

And there you go: all of your registrations controlled directly within Prism for a one stop shop for managing them.

I will add one small caveat to the information above. I wrote most of this from memory while sitting in a hallway at the Sands Convention Center. Prism is going through a number of changes from 6.3 to 7 and I might have mis-spelled a class name. But I think it should stand up fairly well.

Xamarin Forms Layout Compression

One of the cool things coming in the 2.5 release of Xamarin Forms is something called Layout Compression. If you have done any kind of Xaml work whether with Xamarin Forms or WPF or even Silverlight, you know that end up with multiple levels of nested containers before finally reaching content.

All of these elements have to be recursed through to determine the measurements and the layouts and this can take time, especially when you start to consider wrappers for platform renderers, list/tree view item templates to name a few.

In 2.5, you can tell Xamarin Forms which views can be opted out of rendering to speed up your UI, simply by adding the ‘CompressedLayout.IsHeadless=”True”‘ to your Layout.


<StackLayout CompressedLayout.IsHeadless="true" >

</StackLayout>

It’s important to remember that anything you expected to be part of the layout will be gone, things such as the background color, gestures etc. So be careful what you compress!

I am looking forward to trying out 2.5 (still in pre-release in nuget) on one of my projects.

 

Xamarin Forms, Prism and Platform Services

One question that I have had a few times now is how do I integrate platform specific implementations of services into the Prism Framework? It’s not hard, in fact, you don’t have to do anything at all! Let’s take a look at how it works. I am going to focus on the Unity container: it’s my favorite for no other reason than it was the first container I started using and it has always worked well for me across all different .NET projects. The other containers have similar capability.

Recap Abstracting Platform Services

All the platforms have very similar capabilities, especially in the case of Bluetooth, Bluetooth LE, GPS, text-to-speech etc., but each of these capabilities requires a platform specific process of consuming them. I am sure most know that an interface needs to be  created the portable/shared project and then platform specific implementations in each of the platform projects. But here is a quick recap of what it looks like.

Portable/Shared Project

Create your Xamarin Forms project and use nuget to add Prism.Unity.Forms. The latest stable release at the time of writing was 6.3.0. Once you have your project created, you would need to create your interface definition. Everyone loves to use text-to-speech for these kinds of samples, so let’s do that.


public interface ITextToSpeech
{
    void SayIt(string text);
}

For each of the platforms the parts that we are interested in for the sake of the article is pretty much the same. I won’t reproduce the actual speech code here, but if you are interested in how it is done, there is a good sample on the Xamarin developer site.

Platform Projects

Here is what the class looks like for each of the platforms.


///usings up here
[assembly: Dependency(typeof(AndroidTextToSpeech))]
namespace Sample.Droid
{
    public class AndroidTextToSpeech : ITextToSpeech
    {
        public void SayIt(string text)
        {
            /// do implementation here
        }
    }
}

/// usings up here
[assembly: Dependency(typeof(IosTextToSpeech))]
namespace Sample.iOS
{
    public class IosTextToSpeech : ITextToSpeech
    {
        public void SayIt(string text)
        {
            // do implementation here
        }
    }
}
/// usings up here
[assembly: Dependency(typeof(UwpTextToSpeech))]
namespace Sample.Uwp
{
    public class UwpTextToSpeech : ITextToSpeech
    {
        public void SayIt(string text)
        {
            // do implementation here
        }
    }
}

As promised, each of the platform implementations look the same and this is the pattern you would follow even if you weren’t using a framework like Prism. The key is the attribute just above the namespace statement that registers your implementation with the Xamarin Forms dependency service.

Consuming in ViewModel

Normally we would consume the service in the view model using the following pattern:

public class MyViewModel : BindableBase
{
    private ITextToSpeech _speechService = null;

    public MyViewModel()
    {
        _speechService = DependencyService.Get<ITextToSpeech>();
    }
}

The above looks ok, but it does tie your view model to the Xamarin Forms DependencyService. This makes things a little more painful for testing.

What Prism Does For You

What Prism does for you is remove that dependency on the Xamarin Forms dependency service and allow you to pass in the service as a constructor parameter like follows:

public class MyViewModel : BindableBase
{
    private ITextToSpeech _speechService = null;

    public MyViewModel(ITextToSpeech speechService)
    {
        _speechService = speechService;
    }
}

How does Prism do that? It creates a special extension to the Unity container (similar capabilities exist within the other containers) that basically say to the container if the requested interface isn’t registered in the container, look for it in the Xamarin Forms DependencyService. That’s pretty cool! No additional work is required and you right away have a more testable and maintainable solution. If you are interested in seeing what this looks like, you can look at the
DependencyServiceStrategy class and the ConfigureContainer method in the PrismApplication class.