Prime Numbers Series Part 1

This is part 1 of a series of posts on writing scalable software.

Start at the Beginning.

So, what are the rules for finding prime numbers:

  • Rule 1: the number is greater than 1
  • Rule 2: the number is only divisible by 1 and itself.

Here is probably the simplest approach to implementing this in code, and is the same approach used to prove many hypotheses. We assume the number is a prime, and scan through all cases, apply the rule to each case if the rule fails we mark the candidate as being not a prime number. If the hypothesis passes all rules at the end, we have found a prime.

Here is the c# code:

static void Main(string[] args)
{
	long candidate = 1024 * 1024 * 1024 + 3;
	Stopwatch watch = Stopwatch.StartNew();
	long startAt = 2;
	bool isPrime = true;
	for (long i = startAt; i < candidate; i++)
	{
		if (candidate % i == 0)
		{
			isPrime = false;
			break;
		}
	}
	if (isPrime)
	{ 
		Console.Write("Found a new prime: {0}\n", candidate);
	}
	Console.WriteLine("Time Taken = {0:n} msec", watch.ElapsedMilliseconds);
}

You should get the following output:

Found a new prime: 1073741827
Time Taken = 16,916.00 msec

Let’s optimise our algorithm slightly. A non-prime number p, can always be refactored to n x m. But if sqrt(p) = n x n, so one of these must be less than sqrt(p) or (n x m) would be greater than or equal to p, so we only need to check for all values less than sqrt (p).

Our new algorithm:

static void Main(string[] args)
{
	long candidate = 1024 * 1024 * 1024 + 3;
	Stopwatch watch = Stopwatch.StartNew();
	long startAt = 2;
	bool isPrime = true;
	for (long i = startAt; i < Math.Sqrt(candidate); i++)
	{
		if (candidate % i == 0)
		{
			isPrime = false;
			break;
		}
	}
	if (isPrime)
	{
		Console.Write("Found a new prime: {0}\n", candidate);
	}
	Console.WriteLine("Time Taken = {0:n} msec", watch.ElapsedMilliseconds);
}

You should get the following output:

Found a new prime: 1073741827
Time Taken = 3 msec

Wow. That’s fast.

Let’s try a bigger prime: how about long.MAXVALUE - 24, or 9,223,372,036,854,775,783

Found a new prime: 9,223,372,036,854,775,783
Time Taken = 146493 msec to scan 9,223,372,036,854,775,783

We are starting to hit more limits now.

Firstly, the time taken is getting long again. Over two minutes, but if you look at our CPU usage, it’s stuck solid on 50% cpu utilisation. Since we are running a single linear thread of execution in our candidate search, we are not making full use of the processor cores in the computer. Maybe we should consider running our search in parallel over several threads of execution. We will look at this in a later post.

Secondly, our “long” variable can’t hold a number larger than MAXVALUE so 9223372036854775783 is the largest prime we can search for.

Let’s see if we can look for bigger number. I came across a library recently called System.Numerics which can deal with big integers. Let’s give it a spin.

Before we start looking for primes larger that 9223372036854775783, let’s search for our first test prime of so that we can benchmark the difference between a long search and a BigInteger search.

There are a few new concepts here. Firstly, there is no Math.Sqrt() for BigInteger, so we had to roll our own. Here is a sample on getting the Sqrt of a BigInteger. I have implemented this as an extension method. This is derived from the following stackoverflow post with a few tweaks. Here is the code to calculate the sqrt:

public static BigInteger Sqrt(this BigInteger n)
{
	if (n == 0) return 0;
	if (n < long.MaxValue)
	{
		return  (BigInteger) Math.Sqrt((long)n);
	}
	if (n > 0)
	{
		int bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(n, 2)));
		BigInteger root = BigInteger.One << (bitLength / 2);
		while (!isSqrt(n, root))
		{
			root += n / root;
			root /= 2;
		}

		return root;
	}

	throw new ArithmeticException("NaN");
}

private static Boolean isSqrt(BigInteger n, BigInteger root)
{
	BigInteger lowerBound = root * root;
	BigInteger upperBound = (root + 1) * (root + 1);

	return (n >= lowerBound && n < upperBound);
}

and I have moved the prime search to this extensions method:

public static bool IsPrime(this BigInteger candidate)
{
	BigInteger sqrt = candidate.Sqrt();
	for (BigInteger i = 2; i < sqrt; i++)
	{
		if (candidate % i == 0)
		{
			return false;
		}
	}
	return true;
}

Let’s run again.

Found a new prime: 9,223,372,036,854,775,783
Time Taken = 1,145,536 msec to scan 9,223,372,036,854,775,783

Ouch! not good. This is approx 8 times slower than the previous calculation, but gives us a much bigger range. I’ve run off the first 3 primes starting with (long.MAX_VALUE - 24);

Found a new prime: 9,223,372,036,854,775,783. Time Taken = 1,690,790 msec
Found a new prime: 9,223,372,036,854,775,837. Time Taken = 1,550,355 msec
Found a new prime: 9,223,372,036,854,775,907. Time Taken = 1,884,315 msec
Found a new prime: 9,223,372,036,854,775,931. Time Taken = 1,599,943 msec
Found a new prime: 9,223,372,036,854,775,939. Time Taken = 1,718,325 msec
Found a new prime: 9,223,372,036,854,775,963. Time Taken = 1,580,920 msec

Our next optimisation: We actually don’t need to check every number, because if the number we are about to check is not a prime, it would already have been identified by one of it’s divisors, so we actually only need to check that it can be divided by a lower prime number. So, a new algorithm would be to have a array of every number between 2 and our candidate, and flag this number as true if it’s a prime, or false if it’s not a prime, and as we build up each candidate, we can first check if this number exists in our array first. Let’s see what happens if we try this.

Now, we quickly run out of memory if we do this, so what we can do is provide a service that caches the previous primes that we have persisted to storage, so that we don’t have out of memory issues. That’s our next step.

Read More

Getting Started with Xamarin Studio and the Android SDK

Let’s face it. Xamarin is a pretty amazing company when you look at it. The father of Xamarin, Miguel de Icaza had a vision when he saw the first release of Microsoft .Net and the C# language. He said, ( and I’m paraphrasing) - “this is an amazing technology and it needs to go open source and cross-platform so the whole world can benefit”. Well, maybe he didn’t actually day “cross-platform” per se, but certainly words to that effect.

One of the real stumbling blocks in moving from being a pure Windows developer to a Cross-Platform dev is understanding the Android SDK. When I first came across Xamarin Forms, I thought to myself, I wonder how far I can get without having to delve into masses of Android documentation and Hacker resources.

Don’t get me wrong. The Xamarin documentation is amazing, and very detailed. There just is a Lot of it. And I guess you could call me Lazy, but I really just want to follow the Pareto Principle in everything I do, and want to get 80% of the results with just 20% of the effort. It’s just more effective that way. I can always fill in the rest over the next decade.

For me I want to know what’s the least amount I need to learn about Android internals and get to being a really good cross platform dev. Simples!

So, what have I learned:

There were 3 major releases of the Android OS in recent times, all named after deserts. In order of most recent first, they are:

5.0 Android Lollipop which uses API Library 21 and beyond.

4.4 Android KitKat which uses API Library 19 and beyond.

4.1 Android Jelly Bean which uses API Library 16 and above.

Versions before 4.1 are probably not relevant to you unless you are thinking of targeting older devices, and you can probably work out the rest of the equation yourself with a quick Google search.

So, really you have two numbers to remember: the minimum SDK version you want to target, in my case, 16, and the current version you want to target. At the time of writing the latest version of the API is 22, so that’s what I’m going to target. Note that your app can run on a target platform newer than this, but the OS will not make any assumptions about newer features of the OS that your app doesn’t know about. So, to recap:

minSDKversion=16	
targetSDKversion=22

CPU and Emulation

Next, a quick note about CPU family & emulation.

When you start off with your first app, you really don’t want to use a real android device, because frankly the learning curve is enough without looking at debugging hardware issues and bricked phones. So we will start with a virtual device that runs a little virtual machine. That way we can wipe the device at any time and start again if we need to.

A few caveats: If you are already running Hyper-V, VMware, Virtual Box, or some other virtual PC framework, then this is not going to work. This is because you need to take advantage of a CPU virtualization feature called VT-x to manage virtual devices, and it’s a single resource. If Hyper-V is using it, your android virtual device can’t. It’s as simple as that. (Some motherboards require you to turn on VT-x in the BIOS. stackoverflow is your friend here).

Similarly, you can’t launch a virtual device from a virtual machine because it’s host is already using the virtualization bit feature.

Which makes laptops with about 8GB ideal for android development. Why? If you have already purchased a laptop with only 8GB of ram you probably have no plans to run hyper-v, because frankly 8GB is just not enough to run dev apps and virtual machines.

If you are running a desktop or server like Windows Server 2012 R2, you are more than likely already running hyper-v, or are thinking of running your dev environment in a guest virtual machine. It won’t work either. Or rather, you can compile and build your app, but you can’t test it because you can’t start a virtual machine.

Now all of the above is based on the premise that you are using hardware emulation. In other words, when you virtual android device is running, each machine code instruction that your virtual device executes is passed to your physical CPU but in a sandbox, and so can run at a speed that is reasonably close to the speed of a real device (Within an order of magnitude at least). So to run a virtual android device on an Intel or AMD architecture CPU, you need to choose an Intel Atom based virtual device hardware because it is of the same family of processors.

The alternative is software emulation, where the hardware CPU of your target device is a totally different CPU family. An example would be a virtual device running on an ARM architecture device. In this case each instruction has to be translated from an ARM architecture instruction to a set of equivalent Intel family instructions (x86 op codes), sent to your physical CPU to operate on, then take the result and translate this back.

This is painful slow, and while software emulation does work, you will find yourself wishing it didn’t every time you boot your virtual device. Believe me, it’s painful.

So the lesson here is not to use software emulation, at least not starting off, and not unless you have to.

There is however one last obstacle you have to overcome in order to be able to take advantage of hardware emulation. You need to download and install a hardware abstraction layer device manager tool to perform this hardware translation. Google “Intel Hardware Accelerated Execution Manager”. Search, download and install it now, as it will save you a lot of time and hassle later.

Armed with all the above info, all that is left to do is to download and install the Xamarin Studio Starter Edition to your laptop, and when prompted just choose the defaults for everything. It has to go off and install a whole range of SDKs and Tools, so best kick this off and let it run for a couple hours and do something more productive than watching a progress bar.

Once done, we need to start the Android SDK Manager and choose what API Libraries we want to install, and the OS images and Extras we need to get up and running. This is the focus of the next post.

Happy hunting.

P.S. Here are some handy references you will probably bookmark but never read later because you don’t have time.

http://developer.android.com/about/versions/android-5.0.html

http://developer.android.com/about/versions/android-4.4.html

http://developer.android.com/about/versions/android-4.1.html

Read More

Data Deduplication on Windows Server 2012 R2 Rocks!

I’m a bit of a stickler for backups, and just to be sure, I usually setup my traditional hard drives as Raid-1 mirrors. It’s twice the cost but it just gives me that little bit more reassurance. Besides, who really wants to spend half a day rebuilding a server and mucking about with restoring backups?

My main dev machine, CHAOS was running out of space…again. Recently I setup a secondary server purely for storage and moved a lot of devops stuff over there. For example, I have One Drive and One Drive for Business installed on my user account on that server, and since that’s my Home Folder on the AD domain, it means that they are accessible as my Z: drive for all other machines on the network. Net result is that I only have to install One Drive and One Drive for Business on a single machine and all my sync problems have gone away. It’s really great! STORAGE is running a few other projects too.. It’s acting as a Software SAN for the dev SQL Cluster, and I’m using it for my local code repository too - although, I have to say I am more likely to use GitHub or Visual Studio Online for that nowadays.

But still CHAOS was running low on space. I had about 100GB left on my 1.8GB RAID-1 D: drive. At the back of my mind, I had been thinking about Data Deduplication for a while now, but never gave it serious consideration. After all, I know my data and I’m pretty sure that apart from a couple of iTunes music archives that are mosty probably out of sync, I don’t have much duplicate data. At least that’s what I though…

I remember attending a seminar on the release of Windows Server 2012 R2 a few years back, when I first heard about Data Deduplicatio, but I never got a chance to try it out. Seemed like the timing was perfect.

I installed the Role under File and Storage Services > File and iSCSI Services > Data Deduplication. Done in a few seconds? Is that it?

Installing the Data Deduplication feature

It took a quick google on bind, and then all that is left is to navigate to the Server Manager > File and Storage Services > Volumes, Right-Click and select Configure Data Deduplication. I set the schedule to be quite agressive and to update twice per day, but I didn’t even notice any performance impact to be honest. I took a before and after screen shot of the disk usage.

Before

Next morning I was pleasantly surprised to see the 102GB free space had increased to over 550 GB, giving me a whopping DeDuplication rate of 23%. Happy Days!

After

What I love about features such as this, is that they are so easy to setup and configure.

Slán go Foil.

Read More

Windows Server Backup Feature won't show

Here is a strange one. About to backup one of the ADs in the lab, and restore to new hardware.

Installed Windows Server Backup Feature and another feature at the same time.

No errors, no warmings, but Windows Server Backup doesn’t show in the Server Manager Dashboard under tools.

I know it’s at least partially installed because I can run wbadmin from a cmd prompt.

Found this comment online.

Sorry, I hit submit in a frenzy of typing and fat-fingering. I wasn't quite 
done...
	
Don't ask me why, but it seems like the install of Windows Server Backup is 
in some odd way related to the WSUS role. I know it sounds crazy, but hear me 
out... I first began experiencing this issue on a server running WSUS. With 
both installed, I was able to use wbadmin as well as the GUI without issue. I 
then decided to transfer my WSUS server to a different machine, so I 
uninstalled the role, which took all the Windows Server Backup stuff with 
it... but left it as "installed" in Add/Remove features.

So, to test, I uninstalled Windows Server Backup, and then installed both 
Windows Server Backup and Windows Update Services together, including all 
dependencies, et voila, Windows Server Backup re-appeared and was available 
again to use.
	
I'm not suggesting there's a link between WSUS and Windows Server Backup. 
Rather, I'm suggesting there may be a bug in the Add/Remove Roles/Features 
system of 2012 with regard to one of the two services. I hope this helps.

Nothing to lose, and I took a stab in the dark that there a missing depeency for a multi-feature install. So, I installed Network Load Balancer and voila, Windows Server Backup appeared.

Removed Network Load Balancer, and Windows Server Backup disappeared again!

Read More

Getting Started with ASP.NET5.0 and the DNX Framework

I'm updating my Android SDK packages.

While I'm waiting, I'm going to install the latest DNX and aspnet5.0. It's a clean VM. No Visual Studio installed. Just Xamarin Studio, so should be a good clean install experience. Well. I was almost right.

If you want to know more, go to https://github.com/aspnet/home#upgrading-dnvm-or-running-without-visual-studio

From an Elevated command prompt (run as administrator), enter the following:

 

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}"

 

 

Then close the CMD prompt, and start a new cmd prompt.

Check to see if dnwm was installed correctly.

 

Where dnvm

 

And I get the location where it is setup:' C:\Users\micheal\.dnx\bin\dnvm.cmd

Now run dnvm to see the OOBE.

So, I get a really cool text ascii art. Excellent.

I really need a bigger command prompt window. Screen buffer height and windows size to 140. Also change the colors to dark blue and yellow. And fix that horrible font.

That's better.' Let's install a DNX.

 

dnvm install

 

Well that didn't work. So, I need to say what version to install. Let's go with latest stable version of dnx.

 

dnvm install latest

 

That's better. We are off to the races'

Now we are done. Lets' get some help on dnvm

 

dnvm help install

 


 

dnvm install

' Installs a version of the runtime

 

usage:

' dnvm install [<VersionNuPkgOrAlias>] [-arch <Architecture>] [-r <Runtime>] [-a <Alias>] [-f] [-Proxy <Proxy>] [-NoNative] [-Ngen] [-Persis

tent] [-Unstable]

 

options:

' <VersionNuPkgOrAlias> The version to install from the current channel, the path to a '.nupkg' file to install, 'latest' to

install the latest available version from the current channel, or an alias value to install an alternate

runtime or architecture flavor of the specified alias.

' -arch The processor architecture of the runtime to install (default: x86)

' -r The runtime flavor to install (default: clr)

' -a Set alias <Alias> to the installed runtime

' -f Overwrite an existing runtime if it already exists

' -Proxy Use the given address as a proxy when accessing remote server

' -NoNative Skip generation of native images

' -Ngen For CLR flavor only. Generate native images for runtime libraries on Desktop CLR to improve startup time. This option

'requires elevated privilege and will be automatically turned on if the script is running in administrative mode. To opt-out in administrative mode, use -NoNative switch.

' -Persistent Make the installed runtime useable across all processes run by the current user

' -Unstable Upgrade from our unstable dev feed. This will give you the latest development version of the runtime.

 

remarks: A proxy can also be specified by using the 'http_proxy' environment variable

So, Let's see where it put out dnx stuff. Navigate to %userprofile%\.dnx\runtimes

And have a look at the environment variables:

Let's clone some stuff. Have I git installed yet?

 

Z:\>git

'git' is not recognized as an internal or external command,

operable program or batch file.

 

Nope, let's get it

'https://windows.github.com/

I don't remember this ever been so easy!

Start a Git Shell from the desktop.

That't better

Let's clone the ASPNET

D:\Developer>mkdir aspnet

D:\Developer>cd aspnet

D:\Developer\aspnet>git clone https://github.com/aspnet/Home.git

Cloning into 'Home'...

remote: Counting objects: 1150, done.

Receiving objects: 100% (1150/1150), 628.01 KiB | 413.00 KiB/s 0

Receiving objects: 100% (1150/1150), 702.31 KiB | 413.00 KiB/s, done.

Resolving deltas: 100% (668/668), done.

Checking connectivity... done.

 

D:\Developer\aspnet>cd Home\samples

 

D:\Developer\aspnet\Home\samples>cd latest

 

D:\Developer\aspnet\Home\samples\latest>cd ConsoleApp

 

D:\Developer\aspnet\Home\samples\latest\ConsoleApp>dnu restore

Restoring packages for D:\Developer\aspnet\Home\samples\latest\ConsoleApp\project.json

' GET https://www.myget.org/F/aspnetvnext/api/v2/FindPackagesById()?Id='System.Console'.

' GET https://nuget.org/api/v2/FindPackagesById()?Id='System.Console'.

' OK https://nuget.org/api/v2/FindPackagesById()?Id='System.Console' 2192ms

 

 

 

Now we have dnx

D:\Developer\aspnet\Home\samples\latest\ConsoleApp>dnx

Microsoft .NET Execution environment v1.0.0-beta4-11566

 

Usage: dnx [options]

 

Options:

' --appbase <PATH>' Application base directory path

' --lib <LIB_PATHS> Paths used for library look-up

' --debug ' Waits for the debugger to attach before beginning execution.

' -?|-h|--help Show help information

' --version Show version information

' --watch ' Watch file changes

' --packages <PACKAGE_DIR> Directory containing packages

' --configuration <CONFIGURATION>' The configuration to run under

' --port <PORT> ' The port to the compilation server

Something I didn't get. You have to run dnvm upgrade or dnvm use default -p to set the path.

Let's run it.

 

D:\Developer\aspnet\Home\samples>dnvm upgrade latest

Determining latest version

'dnx-clr-win-x86.1.0.0-beta4' is already installed.

Adding C:\Users\Micheal\.dnx\runtimes\dnx-clr-win-x86.1.0.0-beta4\bin to process PATH

Adding C:\Users\Micheal\.dnx\runtimes\dnx-clr-win-x86.1.0.0-beta4\bin to user PATH

Updating alias 'latest' to 'dnx-clr-win-x86.1.0.0-beta4'

 

Now, navigate to, and run the console app.

 

D:\Developer\aspnet\Home\samples>cd latest\ConsoleApp

 

D:\Developer\aspnet\Home\samples\latest\ConsoleApp>dnx . run

Hello World

 

Sweet jesus, it ran!

Let's try the HelloWeb Sample:

 

D:\Developer\aspnet\Home\samples\latest\ConsoleApp>cd ..\HelloWeb

 

D:\Developer\aspnet\Home\samples\latest\HelloWeb>dnx . web

System.InvalidOperationException: No service for type 'Microsoft.Framework.Runtime.IApplicationEnvironment' has been registered.

at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)

at Microsoft.AspNet.Hosting.Program.Main(String[] args)

 

Not sure what this is about. I though I installed latest? I googled it on bing, and found this:
http://stackoverflow.com/questions/30013929/service-missing-for-type-microsoft-framework-runtime-iapplicationenvironment

I had a similar issue when trying to run from the \samples\latest folder instead of \samples\1.0.0-beta4 folder. Simply trying again from where I was supposed to be worked.

So, use the 1.0.0.-beta3 not the [latest] like I have above. Change to the beta4 path and run

D:\Developer\aspnet\Home\samples\1.0.0-beta4\HelloWeb>dnx . web

Started

Yah!

Browe to localhost:5001

Finally, HelloMVC

 

D:\Developer\aspnet\Home\samples\1.0.0-beta4\HelloMvc>dnx . web

Started

 

And, what do you know? My Android SDK's are just finished. Brilliant.

P.S. I have since found out that if you upgrade to the unstable branch (-u), that running the above HelloWeb and HelloMVC in the [latest] folder works just fine. More about this in another post.

Read More

Can you show me how to use Azure

“Can you show me how to use Azure”? I have been asked the same question many times over the past while. It’s an awkward question. Azure isn’t a tin-opener. It’s a platform, combining many different technologies, tools and service offerings.

I mean, I could get into the little detail, and say “Sure, which part of the Azure platform are you interested in”?

If the person is a Developer and there is a clear response like Shared Storage, or Continuous Deployment or Mobile Services or Streaming Analytics or even Machine Learning, then we are off to a good start and we can make progress.

But the first issue is that it’s not a Developer who is asking the question. It’s usually the Business Owner, or Senior Management, or worse - the CTO. The second issues is that the response I usually get back is “I don’t really know, I thought you could tell me”.

Ouch!

I have come to the conclusion that we have to stop looking at Azure as a platform or a bunch of technologies or services, and instead start looking at Azure as a Strategy. (AaaS)

The real question they are asking is: “Can you help me form an Azure Strategy”?

That’s a very different question.

You see, the first question is driven out of fear of being left behind and uncertainty about the future. Business owners are constantly hearing about the Cloud and Azure, but beyond Office365 and perhaps spinning up a VM in Azure and sticking a database driven web-server on it - Which by the way is frankly a waste of time (*) - the whole Azure “thingy” all seems a little too much like Dark MagicDark Magic

I am constantly seeing developers dip their toes in the world of Azure and getting burnt, and trying to justify their actions to management either by taking the victim stance - “Azure is X” - where X is some derogatory nominilization (Azure is Slow/Immature/Down), or by saying Azure doesn’t support Y, where Y is some feature that has nothing to do with Scalable cloud Architecture (such as, Azure doesn’t support sticky sessions/ Linked Databases / CONTEXT_INFO objects).

The second question is very different, because it is a realisation that Azure is not a silver bullet, and it will not solve all the technical debt that the organisation has built up over the last five years. In fact Azure will most probably bring your technical debt into the spotlight, perhaps with red faced defenses and blame been thrown at junior developers who have long left the fold.

Developing an Azure Strategy involves building a clear and simple 3 step plan:

  • Step 1. Where am I now ?
  • Step 2. Where do I want to be?
  • Step 3. What do I need to Change to get there?

Over the next few posts, I will work towards answering these questions in the context of four Key Performance Indicators. These are:

  • Cost
  • Time
  • Work-flow Efficiency
  • Repeatability

Next week: Background to an Azure Strategy: Why choose these Key Performance Indicators?

Read More