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>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>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

Running MongoDB on Windows

MongoDbLogoI’ve been working with MonogDB lately. Getting it setup and running on a development box is easy, but I wanted to document the steps for reference.

Install MongoDB

Download MongoDB from their website. For windows, I prefer the 64-bit Zip file. The MSI installs into Program Files, but I prefer to keep the binaries and the databases together and not have to run as an Admin.

Extract the Zip file to c:\MongoDB

In the MongoDB directory, create a data subdirectory and in it add db and log subdirectories. The bin subdirectory should already be there. Your directory structure should now look like this,

c:\mongodb
    \bin
    \data
        \db
        \log

Configure MongoDB

Add a text file called  c:\MongoDB\mongod.cfg that contains the following,

systemLog:
   destination: file
   path: c:\mongodb\data\log\mongodb.log
   logAppend: true
storage:
    dbPath: c:\mongodb\data\db
net:
   bindIp: 127.0.0.1
   port: 27017

This sets the log and the db path and also sets the port to the default so it is easy to change later. Notice that I am only binding to 127.0.0.1 because my server is currently insecure so I do not want to expose it on the network. For more configuration options, see the documentation.

Test MongoDB

Now that I have it set up, it is time to test the installation. Start it at the command prompt like this,

C:\MongoDb\bin>mongod.exe -f ..\mongod.cfg

Then in another command window, connect to the running server to make sure it is up and running. I am shutting the server down while I am connected to it, thus the errors.

D:\MongoDb\bin>mongo
MongoDB shell version: 2.6.1
connecting to: test
> use admin
switched to db admin
> db.shutdownServer()
2014-06-10T14:28:35.567-0400 DBClientCursor::init call() failed
server should be down...
2014-06-10T14:28:35.571-0400 trying reconnect to 127.0.0.1:27017 (127.0.0.1) failed
2014-06-10T14:28:36.579-0400 warning: Failed to connect to 127.0.0.1:27017, reason: errno:10061 No connection could be made because the target machine actively refused it.
2014-06-10T14:28:36.579-0400 reconnect 127.0.0.1:27017 (127.0.0.1) failed failed couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
> exit
bye

Install as a service

We now know that our configuration is correct, so now I want to install it as a service so that it is always running,

Start an Administrator command prompt. On Windows 7, press WIN+R, then type cmd, them press CTRL+SHIFT+ENTER. On Windows 8, press WIN+X, then press A.

Now run the command,

sc.exe create MongoDB binPath="C:\MongoDB\bin\mongod.exe --service --config=C:\MongoDB\mongod.cfg" DisplayName="MongoDB 2.6 Standard" start="auto"

You should then see,

[SC] CreateService SUCCESS

You can now start and stop the service with the following commands,

net start MongoDB
net stop MongoDB

If you ever want to uninstall the service, the command is,

sc.exe delete MongoDB

Next Steps

You now have a MongoDB development server running on your local system. It does not require authentication, but is not exposed on the network, only through 127.0.0.1. When you are ready to deploy to production, you will need to set up security and replication.

For development in .NET you will want to start with the Official MongoDB C# driver NuGet package.

Read More

Custom Fonts in WPF Applications

I am working on a WPF application and wanted to use Font Awesome for the icons within the application. Font Awesome is a series of 369 scalable icons that are distributed in font form and mainly used in web development. I am using it to add modern looking icons to my application, but you can use this technique for embedding any font in your WPF application.

imageFirst, download Font Awesome, extract the ZIP file and copy fonts/fontawesome-webfont.ttf into a Fonts folder in your solution. Set the Build Action in the properties to Resource if it isn’t already.

imageNext, add a Style to the Resources in App.xaml. Don’t forget the # at the front of the font name and remember to use the internal name of the font, not the name of the file. To check the name of the font, just double click on the font file and it will open in the Windows Font Viewer. The font name will be at the top.

<Application.resources>
    <style x:key="FontAwesome">
        <setter property="TextElement.FontFamily" 
            value="pack://application:,,,/fonts/#FontAwesome" />
    </style>
</Application.resources>

Now you can use add this style to your WPF controls.

<TextBlock 
    Style="{StaticResource FontAwesome}"
    FontSize="36" 
    Text="&#xf09b;" />

If you are using a regular text font, just add the text as you normally would. If it is an image font, then use the unicode values for the images you want, for example &#xf09b; for the GitHub icon. For Font Awesome, you can look up the values on the Cheat Sheet.

Here is the result in the application I am working on.

image

Update

If the fonts are resources in another assembly, not in the application, you need to change the font name in your XAML to use the name of the assembly that the font is in. For example, change MyAssembly in the following to the name of the assembly the font is in.

<Application.resources>
    <style x:key="FontAwesome">
        <setter property="TextElement.FontFamily" 
            value="/MyAssembly;Component/Fonts/#FontAwesome" />
    </style>
</Application.resources>

Read More

Gas Mileage Android App

Gas MilieageGas Mileage calculates your vehicle’s fuel economy using your trip odometer. Tracking your fuel usage helps you keep an eye on the health of your vehicle and see how changes to how you drive affects your mileage. Gas mileage is a simple application that does one thing and does it well.

Other mileage tracking calculators require you to add entries every time you fill up and if you forget, it is difficult to catch up. Gas Mileage is different, just remember to reset your trip odometer every time you fill up your tank and then add entries when you remember.

Features

  • Enter and display values in any common unit
  • List of fill-ups are color coded based on the mileage
  • Supports as many vehicles as you like
  • Icons for each of your vehicles
  • Shows your best mileage, average mileage, worst mileage and the last mileage you entered
  • Easily edit, delete or update any of your fill-ups
  • Add notes to fill-ups and view them later

Get it on Google Play

Read More