Updating Xamarin in Visual Studio

Recently, when I opened a Xamarin project in Visual Studio, I received a message that an update for Xamarin for Visual Studio was available. The Xamarin icon appears in my SysTray, but clicking on it does nothing. Really?

Xamarin Update in SysTray

The Xamarin for Visual Studio extension appears in Extensions and Updates, but you can’t update it from there either. The solution to get the update is to go to Tools | Options | Xamarin | Other. In this dialog, there is a Check Now link. Clicking on it will bring up a list of updates that are available.

Update Xamarin in Options

Some people report finding the Check Now link under Android Settings and iOS Settings. It may depend on the version of Visual Studio, or on the version of Xamarin that is installed.

Read more

NUnit 3 Tests for .NET Core RC2 and ASP.NET Core RC2

Update: I have released beta 1 of dotnet-test-nunit which has been updated to the RTM of .NET Core 1.0. I have updated this post and the code on GitHub to reflect the changes.

The NUnit team has been working hard since .NET Core RC2 and ASP.NET Core RC2 was released last month to add full NUnit testing for .NET Core, and we are happy to announce the second alpha release of dotnet-test-nunit.

In my previous blog posts, I explained how to use NUnit to test .NET Core using NUnitLite which worked, but was not the ideal solution. The new dotnet-test-nunit allows you to test from the command line using the dotnet test command and allows you to run your tests within Visual Studio.

The code from this post is on GitHub and is based on the code from my previous post.

Create a .NET Core Project

In Visual Studio, File | New | Project… and select Class Library (.NET Core) under the new C# | .NET Core node.

New .NET Core Project

This it the code under test. To this, I have added the simple calculator class from the last post.

public static class Calculator
{
    public static int Add(int x, int y) => x + y;
    public static int Subtract(int x, int y) => x - y;
    public static int Multiply(int x, int y) => x * y;
    public static int Divide(int x, int y) => x / y;
}

Create an NUnit .NET Core Test Project

If you look in global.json, the new standard is to put your code in src and tests in test directories. To conform with this, add a New Solution Folder named test.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-003121"
  }
}

To this new test folder, add another Class Library (.NET Core) as your test project and edit the project.json based on the following;

{
    "version": "1.1.0-*",

    "dependencies": {
        "NUnitWithDotNetCoreRC2": {
            "target": "project"
        },
        "NUnit": "3.4.0",
        "dotnet-test-nunit": "3.4.0-beta-1"
    },
    "testRunner": "nunit",

    "frameworks": {
        "netcoreapp1.0": {
            "imports": [
                "netcoreapp1.0",
                "portable-net45+win8"
            ],
            "dependencies": {
                "Microsoft.NETCore.App": {
                    "version": "1.0.0-*",
                    "type": "platform"
                }
            }
        }
    }
}

Under dependencies, NUnitWithDotNetCoreRC2 is the project reference to the project under test. There are also dependencies on NUnit and the new dotnet-test-nunit.

After the dependencies, we specify that we want to use NUnit for testing with the line "testRunner": "nunit".

Under frameworks, we need to add to the imports because NUnit is still a PCL assembly. The .NET Standard (netstandard) version of the NUnit Framework won’t likely be ready until the 3.6 release this summer. We are waiting until after the final .NET Core release to start that work.

Add Tests

Next, you can add your tests to the project by adding a new class;

using NUnit.Framework;

namespace NUnitWithDotNetCoreRC2.Test
{
    [TestFixture]
    public class CalculatorTests
    {
        [TestCase(1, 1, 2)]
        [TestCase(-1, -1, -2)]
        [TestCase(100, 5, 105)]
        public void CanAddNumbers(int x, int y, int expected)
        {
            Assert.That(Calculator.Add(x, y), Is.EqualTo(expected));
        }

        [TestCase(1, 1, 0)]
        [TestCase(-1, -1, 0)]
        [TestCase(100, 5, 95)]
        public void CanSubtract(int x, int y, int expected)
        {
            Assert.That(Calculator.Subtract(x, y), Is.EqualTo(expected));
        }

        [TestCase(1, 1, 1)]
        [TestCase(-1, -1, 1)]
        [TestCase(100, 5, 500)]
        public void CanMultiply(int x, int y, int expected)
        {
            Assert.That(Calculator.Multiply(x, y), Is.EqualTo(expected));
        }

        [TestCase(1, 1, 1)]
        [TestCase(-1, -1, 1)]
        [TestCase(100, 5, 20)]
        public void CanDivide(int x, int y, int expected)
        {
            Assert.That(Calculator.Divide(x, y), Is.EqualTo(expected));
        }
    }
}

Running Your Tests

Now you can run your tests in Visual Studio, or from the command line. In Visual Studio, you may need to reload the solution before your changes are picked up, then your tests will appear in Test Explorer after you build the solution.

NUnit testing .NET Core in Visual Studio

In addition, use the following commands to run your tests from the command line;

# Restore the NuGet packages
dotnet restore

# Run the unit tests in the current directory
dotnet test

# Run the unit tests in a different directory
dotnet test .\test\NUnitWithDotNetCoreRC2.Test\

Notes

Since this is an alpha release, so there are still likely bugs, but it is already being used by some large open source projects so is likely stable for production. Please report any bugs or issues to the dotnet-test-nunit repository on GitHub.

Finally, the dotnet command line swallows blank lines and does not work with color. The NUnit test runner’s output is in color, but you won’t see it. These are known issues with the dotnet CLI and not an NUnit bug.

Read more

Testing .NET Core RC2 Using NUnit 3

Update: full NUnit 3 support for .NET Core and ASP.NET Core has been released.

Things have changed since I wrote Testing .NET Core Using NUnit 3, so it is time to update the steps for .NET Core RC2.

The code from this post is on GitHub in the nunitlite and test_assembly branches. For those interested in an early peek at the new dotnet-test-nunit runner, there is an example on the master branch.

Upgrading your project to build on RC2 is a whole series of blog posts in and of itself, so I won’t cover it here, but I will remind everyone, “All previous versions of .NET Core and any tooling must be removed from the machine in order to properly install and use RC2 release.” I uninstalled everything, deleted all directories in Program Files that had DNX or DotNet in their name, deleted the .dnx directory in my user directory and combed through my user and global paths before installing .NET Core RC2. I didn’t get everything on one machine and was getting strange errors.

So, let’s go green field, in Visual Studio, File | New | Project… and select Class Library (.NET Core) under the new C# | .NET Core node.

New .NET Core Project

This it the code under test. To this, I have added the simple calculator class from the last post.

public static class Calculator
{
    public static int Add(int x, int y) => x + y;
    public static int Subtract(int x, int y) => x - y;
    public static int Multiply(int x, int y) => x * y;
    public static int Divide(int x, int y) => x / y;
}

If you look in global.json, the new standard is to put your code in src and tests in test directories. To conform with this, add a New Solution Folder named test.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview1-002702"
  }
}

To this new test folder, add a new Console Application (.NET Core) as your test project and add a reference to the main project.

Add New Console Project

Now, add the NUnitLite NuGet package to the test project and change Main in Program.cs.

using NUnit.Common;
using NUnitLite;
using System;
using System.Reflection;

namespace NUnitWithDotNetCoreRC2.Test
{
    public class Program
    {
        public static int Main(string[] args)
        {
            return new AutoRun(typeof(Program).GetTypeInfo().Assembly)
                .Execute(args, new ExtendedTextWrapper(Console.Out), Console.In);
        }
    }
}

You can now add your tests to the project.

using NUnit.Framework;

namespace NUnitWithDotNetCoreRC2.Test
{
    [TestFixture]
    public class CalculatorTests
    {
        [TestCase(1, 1, 2)]
        [TestCase(-1, -1, -2)]
        [TestCase(100, 5, 105)]
        public void CanAddNumbers(int x, int y, int expected)
        {
            Assert.That(Calculator.Add(x, y), Is.EqualTo(expected));
        }

        [TestCase(1, 1, 0)]
        [TestCase(-1, -1, 0)]
        [TestCase(100, 5, 95)]
        public void CanSubtract(int x, int y, int expected)
        {
            Assert.That(Calculator.Subtract(x, y), Is.EqualTo(expected));
        }

        [TestCase(1, 1, 1)]
        [TestCase(-1, -1, 1)]
        [TestCase(100, 5, 500)]
        public void CanMultiply(int x, int y, int expected)
        {
            Assert.That(Calculator.Multiply(x, y), Is.EqualTo(expected));
        }

        [TestCase(1, 1, 1)]
        [TestCase(-1, -1, 1)]
        [TestCase(100, 5, 20)]
        public void CanDivide(int x, int y, int expected)
        {
            Assert.That(Calculator.Divide(x, y), Is.EqualTo(expected));
        }
    }
}

You can now set the test project as your startup project and run your tests. If it helps, put a breakpoint in Main to see the output.

NUnitLite 3.2.1 (Portable)
Copyright (C) 2016 Charlie Poole

Test Files
    D:\Src\Spikes\NUnitWithDotNetCoreRC2\NUnitWithDotNetCoreRC2.Test\bin\Debug\netcoreapp1.0\NUnitWithDotNetCoreRC2.Test.dll

Run Settings
    Internal Trace: Off

Test Run Summary
  Overall result: Passed
  Test Count: 12, Passed: 12, Failed: 0, Inconclusive: 0, Skipped: 0
  Start time: 2016-05-18 14:47:56Z
    End time: 2016-05-18 14:47:56Z
    Duration: 0.070 seconds

All in all, for a green field app, then it is pretty straight forward. If you prefer that your tests are in a DLL, then you can follow the steps above, but possibly name the NUnitLite project as a runner and change the AutoRun to get the assembly from a class in your test project. If you prefer this method, I have done it in the test_assembly branch on GitHub.

I am in the process of upgrading a few RC1 projects, so if I find any other gotchas, I will update. For upgrades, one thing you will have to do is add an imports statement to your project.json to handle the renaming of the targets in RC2. This is done for you if you create a new project, but not if you are upgrading.

For project.json in a console runner;

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }

Or in an assembly;

  "frameworks": {
    "netstandard1.5": {
      "imports": "dnxcore50"
    }

Read more

Arduino based Build Indicator

Arduino based build indicatorI found a red strobe light in the bargain bin at a local electronics store and immediately knew what to do with it – create a build failed light. There is a long history of dev shops creating build indicator lights using lava lamps, stop lights and computer monitors mounted on the wall and I’ve always wanted to build one.

The strobe was rated at 12V, but I wanted to run it off USB, so I hooked it up to a 5V power supply. It strobed a bit slower, but it worked, so I checked the amps. It drew a steady 70mA which is too much to run directly off an Arduino pin which are limited to around 40mA, but still low enough to run off USB and the 5V pin on the Arduino. I could use a relay to switch the strobe, but it seemed like overkill, so I checked my parts drawer and found some PN2222A transistors which are rated to 40V and 800mA.

Software

Since I was going to power this project off USB, I decided to let the computer do the heavy lifting of checking the state of the build and signal the Arduino over serial. The Arduino code is pretty simple, listen on serial, if it receives a 0, set pin 13 LOW, if it receives a 1, set pin 13 HIGH.

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize serial:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // prints title with ending line break
  Serial.println("Alert Ready. Enter 1=ON 0=OFF");
  
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  if(Serial.available())
  {
    char input = Serial.read();
    if(input == '0'){
      digitalWrite(13, LOW);
      Serial.println("Turning OFF alert");
    }
    else if(input == '1') {
      digitalWrite(13, HIGH);
      Serial.println("Turning ON alert");
    }
    else {
      Serial.println("Unrecognized command.  Enter 1=ON 0=OFF");
    }
  }
}

On the computer, I wrote a simple Python script to get the RSS feed for our CruiseControl.NET build results. RSS doesn’t contain build specific nodes, so I just search for the word Success in the RSS title. The python script just loops, looks for new RSS items and sends a 0 or 1 to the Arduino over serial. It should be fairly simple to change the script to work with your build server.

#! python3

import feedparser
import serial
import time

COM_PORT  = 'COM6'
BAUD_RATE = 9600
FEED_URI  = 'http://ccbuild/ccnet/server/local/project/OurProductBuild/RSSFeed.aspx'
CHECK_FREQUENCY = 60    # How often to check in seconds

def printTitle(title):    
    print('===================')
    print('  ' + title)
    print('===================')
    print()

id = '' # Track the last RSS entry we found
port = serial.Serial(COM_PORT, BAUD_RATE)
print(port.readline().decode())

while True:
    # get the feed data from the url
    feed = feedparser.parse(FEED_URI)

    # display info for the first post
    num = len(feed.entries)
    success = False
    if num > 0:
        entry = feed.entries[num-1]

        # Have we already seen this entry?
        if id == entry.id:
            time.sleep(CHECK_FREQUENCY)
            continue

        id = entry.id
        printTitle('New build found')
        print(entry.title)
        print()
        success = 'Success' in entry.title
    else:
        printTitle('No build found')

    # Switch the Arduino alert on/off
    if success:
        print('Build succeeded')
        port.write(b'0')
    else:
        print('Build failed')
        port.write(b'1')
    
    print(port.readline().decode())
    time.sleep(CHECK_FREQUENCY)

Hardware

I started by prototyping on a breadboard using a red LED to stand in for the strobe. The green LED is a power indicator. Once I knew the code and the hardware was working, I then added the strobe in parallel to the LED and its resistor.

Strobe Breadboard

I then soldered the components for the transistor switching circuit onto a small prototyping board.

Transistor switching circuit

Then wired the board to an old Arduino Uno, put it in a small box and screwed the strobe to the box.

Project box

And then put the strobe up at work. Sorry, I couldn’t catch the flashing…

Build indicator strobe

Read more

Restore a SQL Server Backup to LocalDb

I’m experimenting with taking a 3-tier client/server/database application and creating a lightweight client application that uses an embedded database. We use stored procedures and our server application uses SQL Server, so SQL Express LocalDB has potential. The only problem I ran into was restoring a backup taken from SQL Server to LocalDB and it appears that I am not the only one that had problems.

In the end though, it was pretty easy, it just required a few steps that most DB admins are already familiar with, but developers may stumble on. Here are the developer-centric instructions using Visual Studio.

Restoring the DB Backup

In Visual Studio, open SQL Server Object Explorer (Ctrl+\, Ctrl+S) or under the View menu. Open the SQL Server node and you will likely have several LocalDB instances. If not, click the Add SQL Server button and from the dropdown, select (localdb)\MSSQLLocalDB.

Open the node for the version of LocalDB you want to use and expand Databases | System Databases. Right click on master and select New Query…

New Query

Execute the following query using the path to your database backup.

RESTORE FILELISTONLY
FROM DISK = 'D:\tmp\ivaraapplicationtesting75.bak'

In the results, take note of the LogicalName.

LogicalName

Modify your query to do the restore, using your database name, backup and the LogicalName from the previous query. You can restore the database to any existing path, in this case, I am restoring to my home directory.

RESTORE DATABASE IvaraApplicationTesting
FROM DISK = 'D:\tmp\ivaraapplicationtesting75.bak'

WITH MOVE 'ivara_data' TO 'C:\Users\rob.prouse\IvaraApplicationTesting.mdf',
MOVE 'ivara_log' TO 'C:\Users\rob.prouse\IvaraApplicationTesting.ldf',
REPLACE;

First time I did this, I thought it didn’t work because it happened so quickly and because the database did not show up in SQL Server Object Explorer, but all you need to do is click refresh.

Results

If you expand your new database, you will see that all of your tables are there and you can execute queries against it.

Read more