C# 6.0 – Null-Conditional Operators

This is another post in the series on the new features that are coming in C# 6.0.

This is one of my favourite new features. Have you ever written code like this?

if (line != null && line.Product != null)
{
    total += line.Product.Price * line.Quantity;
}

C# 6.0 introduces the ?. null-conditional operator that short circuits and returns null if anything in the chain is null. This combines really well with the null-coalescing operator allowing you to rewrite the above as follows.

total += line?.Product?.Price ?? 0 * line?.Quantity ?? 0;

This also works with indexers,

var firstProduct = OrderLines?[0].Product;	// Will return null if OrderLines is null

It also works with methods. This will be really handy for triggering events. Instead of writing,

if (OrderChanged != null)
{
    OrderChanged(this, EventArgs.Empty);
}

You will now be able to write.

OrderChanged?.Invoke(this, EventArgs.Empty);

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More

C# 6.0 – Auto-Property Changes

This is the second in a series of posts on the new features that are coming in C# 6.0. There have been a few small improvements to Auto-Properties.

Auto-Property Initializers

I hinted at this feature in my last post on Primary Constructors. Auto-Properties were introduced way back in C# 3.0, but unlike other members, you had to initialize their values in the constructor.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product()
    {
        Name = "Toy Car";
        Price = 9.99m;
    }
}

In C# 6.0, you can now initialize the properties where they are declared.

public class Product
{
    public string Name { get; set; } = "Toy Car";
    public decimal Price { get; set; } = 9.99m;
}

Getter Only Auto-Properties

You could always declare the setter of an auto-property private or protected to prevent it from being used outside of the class.

public decimal Price { get; private set; }

Now you can omit the setter and it makes the underlying field read-only, so you can only set it in the constructor, or in an auto-property initializer. This is a great feature for creating and enforing imutable classes and also chains well with Primary Constructors.

public class Product(string name, decimal price)
{
    public string Name { get; } = name;
    public decimal Price { get; } = price;
}

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More

C# 6.0 – Primary Constructors

This is the first in a series of posts on the new features that are coming in C# 6.0. If you want to try out any of these features now, check out the Rosyln compiler and then install the latest CTP of Visual Studio 14 or fire up a VM in Azure with Visual Studio 14 already installed.

To enable the new language features in Visual Studio 14, you will need to hand edit your project file and add the following line to each of the configuration sections,

<LangVersion>experimental</LangVersion>

When you are done, it should look like this,

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <LangVersion>experimental</LangVersion>
  </PropertyGroup>

Previous releases of C# were centered around enabling new language features such as async support in C# 5.0 or Linq in C# 3.0. If I was to pick a theme for C# 6.0, I would say that it is around developer productivity. Most of the features are conveniences that allow you to write code more succinctly and clearly. Primary Constructors are one such feature.

Primary Constructors allow you to declare a constructor and parameters directly on the body of the class or struct instead of explicitly declaring it within the body of the class or struct. For example, prior to C# 6.0 you would write a constructor with parameters like this;

public class Employee
{
    private string _name;
    private string _department;
    private decimal _salary;

    public Employee(string name, string department, decimal salary)
    {
        _name = name;
        _department = department;
        _salary = salary;
    }

    public string Name { get { return _name; } }
    public string Department { get { return _department; } }
    public decimal Salary { get { return _salary; } }
}

There is a fair amount of redundant code in this example. I am creating member variables, assigning them from the parameters of the constructor and returning them from the properties. C# 6.0 simplifies this;

public class Employee(string name, string department, decimal salary)
{
    public string Name { get; } = name;
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

Notice that we no longer have a constructor, it is inline with the class declaration. We also do not have to declare the member variables, the constructor parameters are in scope everywhere within the class. Also, notice the properties are using the new Auto-property initializer syntax which I will cover in my next post.

Primary Constructor Bodies

If you need to add functionality or validation to the Primary Constructor, you do it by adding a body to the Primary Constructor as follows;

public class Employee(string name, string department, decimal salary)
{
    {
        if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("name cannot be null or empty");
    }
    public string Name { get; } = name;
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

Explicit Constructors

You can still add additional constructors to a class with a Primary Constructor, but those constructors must chain to the Primary Constructor by calling the this initializer like this;

public class Employee(string name, string department, decimal salary)
{
    public Employee(string name) : this(name, "Intern", 10000)
    {
    }

    public string Name { get; } = name;
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

Base Initializer

A Primary Constructor must always implicitly or explicitly call a base initializer. If you do not explicitly call a base constructor, it will call the parameterless base constructor. To explicitly call a base constructor, you do it like this;

public class Person(string name)
{
    public string Name { get; } = name;
}

public class Employee(string name, string department, decimal salary) : Person(name)
{
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More

Using Android-X86 as an Emulator in Hyper-V for Windows

Everyone knows how S-L-O-W and painful the Android emulator can be when developing. The Intel x86 system images are better, but still a bit slow, so most of us test and debug on actual devices. Still, emulators come in handy. In the past, I came across the Android x86 project and thought it would be a good option, but found the project to not be ready for prime time. With their 4.4 release earlier this month, that has changed.

It still isn’t straight forward to install, so I am going to document the steps and some of the problems I ran into.

Installation

First, download the ISO for the 4.4 or newer release Android x86 from the downloads page.

Next fire up Hyper-V Manager. I assume you have some experience creating virtual machines using Hyper-V, so I am just going to outline the setup. If you need more info, Google it or check out this quick-start.

First, we need to make sure that a Virtual Switch is setup to enable networking. If you haven’t already done it for another virtual machine, click Virtual Switch Manager on the right and create a new External Virtual Switch. Name it something like Ethernet and make sure it is linked to your Ethernet card, not your WiFi.

Virtual Switch Manager

Back in Hyper-V Manager, at the top right, click New, Virtual Machine and name it Android 4.4.

New Virtual Machine Wizard

Specify Generation 1 on the next screen, then select the startup memory. You probably want to increase it to 1024 or 2048 MB. Also, select Use Dynamic Memory.

New Virtual Machine Wizard - Memory

In Configure Networking, select the Ethernet switch we setup previously.

On the Connect Virtual Hard Disk page, you can use the defaults, but you will want to decrease the size of the disk to something like 16 GB.

New Virtual Machine Wizard - Connect Virtual Hard Disk

On the Installation Options page, select Install an operating system from a bootable CD/DVD-ROM and select the ISO you downloaded from Android-x86.

New Virtual Machine Wizard - Install Options

You can now click Next, check out the summary and click Finish to create your new virtual machine.

In Hyper-V Manager, click on your new Android virtual machine and click Connect in the lower right.

Connect to Virtual Machine

This will open the virtual machine in a powered off state. Press the Start button in the toolbar to power up and boot the machine. It will boot to the Live and Installation CD screen. Use the keyboard to scroll down and select Installation – Install Android-x86 to harddisk.

Boot to install

Select Create/Modify partitions,

Create partitions

Use the keyboard to highlight New and press Enter.

New Partition

 

Select Primary, then accept the size of the partition, then click on Bootable.

Bootable Partition

Now, highlight Write, press Enter and type in yes to create the partition. You can now Quit.

Write partition

You can now choose sda1 Linux Virtual Disk.

Choose partition

Format as ext3. confirm your selection, then wait while the partition is created. It will sit at 0% for awhile, don’t worry, it will go.

ext3

Next you will be asked if you want to install GRUB. Say yes.

Grub

 

Also say yes to making /system read-write.

system

It will now install Android on your virtual disk.

Installing

 

2014-08-19 16_24_13-Android 4.4 on XPS15 - Virtual Machine Connection

 

After a successful installation, you will be asked if you want to run Android or reboot. Don’t do either, click on the Turn Off button to shutdown the machine, then go to Media | DVD Drive and Eject the Android X86 ISO. Now press Start to boot the machine.

You will see the GRUB boot screen, then it will start booting Android and go to the initial setup. Step through as you would any Android device with a few small points.


Welcome

 

On the Just a sec progress screen, click the screen with the mouse a couple of times so that it doesn’t time out and lock the device.

2014-08-19 16_32_03-

 

Skip Wi-Fi setup. Your Ethernet card will act like cell data.

WiFi

If you have a Google account and want to use it, click Yes, otherwise No.

Google

Once you are done the setup, immediately go to Settings | Display | Sleep and set it to never. When Android x86 locks the screen, you cannot get it to wake up in Hyper-V. If anyone figures out how to do it, please post the solution in the comments.

Sleep

Debugging in Android Studio

Now for the fun stuff.

Setup the Emulator for Debugging

First, we need to enable debugging on the device. Go to Settings | About tablet and click on the Build number 7 times to enable the Developer Options.

Go back to settings and open Developer Options and turn on USB debugging. I also find it useful to enable Show Touches in the Input section so that you can see the mouse clicks.

Next, go back to settings and into Security and enable Unknown Sources.

Connect ADB

In Android, run the Terminal Emulator. The font is probably way too small to see, so go into Preferences and increase the font size.

Back in the emulator window, type netcfg and take note of the IP address of eth0.

netcfg

Now, back on Windows open a command prompt (with a path to your Android tools) and type adb connect [ipaddress] with the IP address from the device. Now when you do an adb devices, you should see your emulator listed.

C:\src&gt;adb connect 10.224.81.122
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
connected to 10.224.81.122:5555

C:\src&gt;adb devices
List of devices attached
10.224.81.122:5555 device

Debug Your App from Android Studio

Launch Android Studio and load your project. In the configuration dropdown in the toolbar, select Edit Configurations. In the dialog, click on your app configuration and in the Target Device section, make sure it says Show chooser dialog. Close the configuration dialog.

You can now Run or Debug your app and a Choose Device dialog will come up with your emulator listed.

Choose Device

So far, I haven’t been able to adjust the emulator resolution to portrait mode and you can’t rotate the device. From what I can tell, Hyper-V limits the available resolutions to common desktop resolutions. There is also no sound in the emulator and I haven’t been able to get it working with my WiFi card yet, but it is a great option for quick debugging and testing.

That’s all there is to it. If you have any solutions, questions or problems, post them in the comments.

Read More

Universal Projects in Visual Studio

Update – 15/07/14

While the below worked, I ended up abandoning the branch in the NUnit project. There were over a thousand warnings in the Visual Studio Error List from loading the project (not from building) and I could not fix them. In Xamarin Studio, there were just as many, but different warnings and the .NET 2.0 projects failed to build with odd errors.

When I get some time, I am going to take another stab at this, maybe with Update 3 of Visual Studio to see if things have improved at all.


UniversalAppWith Visual Studio 2013 Update 2, Microsoft released a new feature called Universal Apps. They are designed to share code between Phone and Windows applications. Before this, if you had code that was common between projects and weren’t using Portable assemblies, you would include the same source file in each project and use defines for platform specific code.

Universal Projects just automate that process. A Universal Project consists of two parts, the first is the SHPROJ project file. This file just imports the Code Sharing MSBuild extensions and imports the second PROJITEMS file. The PROJITEMS file is just an MSBuild file that looks very much like a CSPROJ file. This PROJITEMS file is then included in your platform specific projects and this is where the magic happens. The Universal Project appears under the references node of the project and when the project is built, all of the files in the Universal Project will get pulled in and built into the platform specific projects.

What most people don’t realize is that this can be used outside of sharing code between phone and desktop apps. For example, many libraries like NUnit or JSON.NET compile against multiple versions of the .NET Framework. They do this by having multiple projects for the library, each targeting a different framework, but including the same files. This becomes a maintenance nightmare on larger projects. For example, if I want to add a new class to the NUnit Framework, I need to add it to four nunit.framework projects and five nunitlite projects. Because of this, it is quite common for a feature to be missed on one platform when a developer missed adding a class file.

It is also causes problems developing. For example, if you open a file from a .NET 4.5 project and try to go to definition, but the target file was opened from the .NET 4.0 project, it fails with the error that the file is already open in another project.

Universal Projects to the Rescue

With Update 2 of Visual Studio 2013, the tooling around Universal Projects isn’t quite there, but with a bit of manual editing to get you started, you can quickly convert a solution with shared code. I will walk through how I did this for the NUnit solution.

First install the Shared Project Reference Manager extension for Visual Studio. This will allow you to add references to Universal Projects.

Next, with your favourite text editor, create the SHPROJ and PROJITEMS files based on the following templates. For NUnit, I just dropped them in the nunit.framework source directory with the platform specific projects.

nunit.framework.shproj

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Label="Globals">
    <ProjectGuid>c9209134-aea3-4c7f-ad74-00d578a6f208</ProjectGuid>
  </PropertyGroup>
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
  <PropertyGroup />
  <Import Project="nunit.framework.projitems" Label="Shared" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>

nunit.framework.projitems

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
    <HasSharedItems>true</HasSharedItems>
    <SharedGUID>c9209134-aea3-4c7f-ad74-00d578a6f208</SharedGUID>
  </PropertyGroup>
  <PropertyGroup Label="Configuration">
    <Import_RootNamespace>NUnit.Framework</Import_RootNamespace>
  </PropertyGroup>
</Project>

Generate a new GUID and use it in both files. Rename the Import Project in the SHPROJ file to whatever name you use and change the Import_RootNamespace in the PROJITEMS file to your namespace.

UniversalProjectNext, right-click on your solution and create a new Solution Folder called something like Universal or Shared. Next, right click on that folder and Add Existing Project to add your new Universal Project.

Now you need to add the source files to the shared project that you want to remove from the platform specific projects. I find it easiest to click on your Universal Project and click on the Show All Files button in the Solution Explorer. Because I placed the Universal Project in with the source files, I can just select all of the files that I want to move over and Include In Project.

Now open up your platform specific project and Exclude From Project all of the files that you added to the Universal Project. Do not Delete the files from your project as it will delete them from disk.

AddSharedReference

Finally, right click on the References for your project and Add Shared Project Reference. This menu option was added by the Shared Project Reference Manager extension that was installed earlier.

To finish, repeat with all of the platform specific projects until all of the shared code is moved out. Notice in the image above that there is now no code in the nunit.framework-4.5 project, it is all now in the Universal Project.

When working with the code, if you want to switch which platform you are looking at, you select it from the dropdown at the top-left of the editor window. Other than that, there is no difference to the development process.

If you want to see more, I also added a long write-up to the NUnit pull request on GitHub.

If anyone knows where I can get a Universal App project template that just creates the shared project, please let me know in the comments. The templates that ship with Visual Studio only create desktop/phone projects with a shared project between them.

Read More