Thursday, 15 August 2013

How do they do it – the right way to write software



[Concrete / Interesting] Sitting at my desk and looking at the plans for the next scheduled release of our enterprise application and, oh boy, this looks like it’s gonna take forever. Not an unusual thought to pass through the mind of a development manager. But wait, does it really have to be this difficult? Is there a better way.

How do they do it?

On another subject, one of the guys in the team shows me Trello ( – 5 minutes in and it looks like the right tool for the job.

It’s a line of business application and it does what it says on the tin. Then my mind wanders and I find myself asking “how do these guys make any money? how do they write this stuff and sell it for nothing? how do they do it?”. So I dig a little deeper and the clue to how is to be found at the following URL:

Yes, behind the web client, iOS, Android and Windows 8 clients, there is a business level REST API. And take a look at the structure, API nouns based on key business entities like ‘board’ and ‘card’ with REST based verbs like GET / PUT / DELETE and where it makes sense, a search API.

What about the client?

Well looking more closely at the web client with web kit tools and Fiddler I discover how simple it is. The web client implements the user interface directly against the REST API. A very appealing UX is provided by jQuery and a few extension libraries like jquery-ui for UI widgets, drag & drop.

XHR – The final bit of the puzzle falls into place

But is the client really doing all the work or is there a server side? Well watching the page load I can see a bunch of XHR requests – that is XMLHttpRequests or AJAX. The first one gets the summary level details like a list of the boards, summary attributes and status and then there are further calls for board details and other board status. So there is no server side as you would find in an ASP.Net class of application, just the web service API supporting a client.

Putting it all together

So Trello and applications like it can be classed as API based client applications, whether it is a web client written in HTML, CSS and jQuery or mobile app written in mobile native (iOS, Android or similar). With these applications the following features seem to come up again and again:


Behind the app is a REST API with business specific APIs with entity based nouns and REST verbs. And typically the API provides one or more search 2.0 methods.

2) Fixed and limited scope to the app.

The app is typically limited to a single core concept – for Trello this is ‘Organize anything together’ or collaborative project management. Even if this is not the case after a few generations of the application, the early generations are typically single paged with singular business focus and a limited set of business entities.

3) Rich UI / UX

Being very focused and limited in terms of scope allows the developers to invest in a rich user interface and user experience.

4) Multi-platform

Again, because of tight scope and especially because all the hard work is being done by the API, the developers can invest effort in native ports to multiple platforms like iOS and Android.

Testing the theory

Ok, so that all sounds easy enough. To get an app out fast I need to write an excellent but business focused REST API and chuck a rich user interface on top. To test the theory I put together a simple one page application for performing ‘Sentiment Analysis’ on twitter terms.

Sentiment Analysis simply tells you whether a population ‘likes’ or ‘hates’, ‘agrees’ or ‘disagrees’ with something. I built a Bayesian filter with corpora weighted for ‘like’ and ‘dislike’ based on a large number of Tweets. I then used this filter against a search of recent tweets matching a given search term. So for a term like ‘TFL’, 100 tweets are analysed as either positive or negative.

In this app, a simple web service is responsible for returning the resulting analysis for a given search term. You can see this API at:

For the client, I started with a template website from ThemeForest ( Lots of templates to choose from, many of them containing rich user interface component, HTML5 and responsive web designs.

Just add a little AJAX to an input field and voila – a single page application is born. Total development time – about 6 hours:


P.S Why’s it so slow

The site is slow but the development was really quick. The site and REST API are both hosted on a slow platform and would benefit from deployment to an enterprise platform. There are a bunch of improvements that can be performed server side and this is where performance improvements should be considered so that all the client benefit.

More can be done on the client, like some graphics to better illustrate the response from the search. But this is version 1. And remember, all done in less than a day.

Performance Boost for XML Stored Procedures

xml[Concrete / Mildly Interesting] Sometimes SQL Server makes you want to pull your hair out. If you are using XML types in your stored procedures and seeing some  very poor performance, I may have an answer for you in this post.



XML is working, but maybe a little too hard

Today I was looking at the performance profile of one of our applications and after a little digging I noticed that a stored procedure was performing rather poorly. We pass a lot of parameters to some of our stored procedures and when we do this we use XML. This technique allows you build parameters using LINQ XElement types and with LINQ to SQL, simply pass the XElement as a parameter to the stored procedure. It’s a great technique so it’s even more disappointing to see it perform so badly. And what’s worse, it seems it’s the simple operation of fetching out the data using nodes() that causes all the problems.

To illustrate this, take a look at the following XML:


Ok, not very exciting, but you get the idea. Here I have 10 parameters in my XML. And here is a simple stored procedure that is passed the XML and fetches out the parameters:

@doc XML

@Param01 INT, @Param02 MONEY, @Param03 DATETIME, @Param04 INT, @Param05 MONEY,
@Param06 BIT, @Param07 INT, @Param08 MONEY, @Param09 DATETIME, @Param10 INT

SET @Param01 = (SELECT doc.col.value('.', 'INT') FROM @doc.nodes('/Transaction/Parameter01') AS doc(col))
SET @Param02 = (SELECT doc.col.value('.', 'MONEY') FROM @doc.nodes('/Transaction/Parameter02') AS doc(col))
SET @Param03 = (SELECT doc.col.value('.', 'DATETIME') FROM @doc.nodes('/Transaction/Parameter03') AS doc(col))
SET @Param04 = (SELECT doc.col.value('.', 'INT') FROM @doc.nodes('/Transaction/Parameter04') AS doc(col))
SET @Param05 = (SELECT doc.col.value('.', 'MONEY') FROM @doc.nodes('/Transaction/Parameter05') AS doc(col))
SET @Param06 = (SELECT doc.col.value('.', 'BIT') FROM @doc.nodes('/Transaction/Parameter06') AS doc(col))
SET @Param07 = (SELECT doc.col.value('.', 'INT') FROM @doc.nodes('/Transaction/Parameter07') AS doc(col))
SET @Param08 = (SELECT doc.col.value('.', 'MONEY') FROM @doc.nodes('/Transaction/Parameter08') AS doc(col))
SET @Param09 = (SELECT doc.col.value('.', 'DATETIME') FROM @doc.nodes('/Transaction/Parameter09') AS doc(col))
SET @Param10 = (SELECT doc.col.value('.', 'INT') FROM @doc.nodes('/Transaction/Parameter10') AS doc(col))

Of course, in the real world the parameters would have meaningful names and you’d want to do more than just set a parameter with values from the XML, but even in this simple example the problem raises it’s ugly head.

Testing the stored procedure

I’ve put together a console application to gather average timings for 100 calls to the stored procedure. I’m using XElement to represent the data and LINQ to SQL to call the stored procedure:

Ok, time to light the fuse and see what develops….

The Results

The results are very unexpected and a big cause for concern:

  • TotalExecution = 6573ms
  • AverageExecution = 65ms

The Explanation

Well, that’s going to cause any program to run like a dog. So why so slow?

After some digging into MSDN articles I found This talks about ’Performance Optimizations for the XML Data Type in SQL Server 2005’ and deep in the article is discusses problems with un-typed XML and this is the root of the problem. With un-typed element based XML, it appears that selecting a node selects the  value of the node and all the children under that node. Even if there are no children as in the example above, the operation is costly because there is no XML index to work with so the XML is parsed to match the XQuery expression.

However, there are ways to improve on this situation:

Solution 1 – Use attributes, not elements

Solution 2 – Use .text() accessor

If you can’t use attributes because you don’t own the schema of the XML, use a .text() accessor get the node as text and stop any further parsing of the XML. To achieve this, alter the .nodes() expression to include the accessor:


XML in SQL is powerful and extremely useful. But you need to check your implementation for performance. I’ve touched on one pitfall but be warned, there are more out there.

Tip of the day - where possible, let SQL Server know as much as possible about your XML.

Thursday, 24 May 2012

Sending Email Landscape style in Cocos2D


iPhone-Mail[Concrete/Interesting] You know when sometimes a piece of code seems really simple, but it just won’t go right? The code just won’t behave properly. Fix one problem and another one pops up...

Well, all I wanted was to use MFMailComposeViewController in my Cocos2d application. I’ve done it before so thought it would be a quick job. After many, many hours, I got it working, so to save you all the effort, here is what I did.

Landscape and MFMailComposeViewController

The problem was the game is in Landscape mode and it seems the mail view controller doesn’t like landscape. Works beautifully on the iPad, but the iPhone sees the world in Portrait.

The standard method to launch email is to call presentModelViewController. Here’s the sort of thing that works well in Portrait:

//Create the mail view controller
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"The Title"];

// Email Body
NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:@"<html><body>"] retain];
[emailBody appendString:@"<p>Some body text</p>"];
[emailBody appendString:@"</body></html>"];
[picker setMessageBody:emailBody isHTML:YES];

//An image
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation([self previewImage])];
[picker addAttachmentData:imageData mimeType:@"image/png" fileName:@"image.png"];

//Present the mail view controller
[[[CCDirector sharedDirector] view] addSubview:emailController.view];
[emailController presentModalViewController:picker animated:YES];
[picker release];
Ok, to get this working you need to ensure the class calling this code is marked as a MFMailComposeViewController delegate by inheriting from <MFMailComposeViewControllerDelegate>. You will also need a suitable UIViewController. This is emailController in the code above.
Notice also that I’m using cocos2d version 2. If you use an earlier version you will need to change the code below:
//Cocos2d version 2 uses view
//[[[CCDirector sharedDirector] view] addSubview:emailController.view];

//For earlier version use openGLView
[[[CCDirector sharedDirector] openGLView] addSubview:emailController.view];

Under Landscape it all goes wrong on the iPhone

But the code above doesn’t work in an application forced into Landscape orientation. What you get is part of the picker showing, clipped and rotated. Oddly enough, the onscreen keyboard is shown correctly, but this is like rubbing salt into an open wound. You will also find that touch handling is messed up and you can’t cancel the email process using the ‘Delete’ or ‘Save as Draft’. Just not working at all well.

There are a number of tips and tricks on the internet to get around this. One method is to handle the presentation of the modal view controller yourself. Tried this and it worked well, up to a point.

But everything went south after choosing an email address using the address book picker. Once again you end up with a clipped and ill orientated modal view.

Solution: Use the Root Controller

Digging deeper it looks like the mail picker and other pickers launched during the process are just not aware of the orientation of the device and application. They seem to be doing their best to ignore what is around them and are going for Portrait. Why?

Well it all comes down to the UIViewController used to present the pickers. In the world of MVC, the view controller used to present other views are responsible for describing the container’s properties, including the orientation. The problem is the UIViewController being used is not doing enough for the picker. In fact the solution is ever so simple, use the application root controller that is responsible for managing cocos2d and the views in this environment:

UIViewController *rootViewController = (UIViewController *)[[[CCDirector sharedDirector] view] nextResponder];
[rootViewController presentModalViewController:picker animated:YES];

The nextResponder to cocos2d’s main view is the root view controller. If you use this to present the modal mail picker, it all works like a charm. Only took me 8 hours to get to this solution.

Wrapping it all up

I like to wrap things up tight so I created a class called EmailScene that encapsulates all the code to present a mail picker:


#import "cocos2d.h"
#import <MessageUI/MFMailComposeViewController.h>


@interface EmailScene : CCScene <MFMailComposeViewControllerDelegate>
NSString *emailTitle;
NSString *emailBody;
UIImage *emailImage;
MFMailComposeViewController *picker;

-(id)initWithTitle:(NSString *)title body:(NSString *)body image:(UIImage *)image;


The implementation looks like this:

#import "EmailScene.h"

@implementation EmailScene

- (id) init {
self = [super init];
if (self != nil) {
[self showMailPicker];
return self;

-(id)initWithTitle:(NSString *)title body:(NSString *)body image:(UIImage *)image
self = [super init];
if (self != nil) {
emailTitle = title;
emailBody = body;
emailImage = image;
[self showMailPicker];
return self;

picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
picker.modalPresentationStyle = UIModalPresentationFullScreen;
picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

[picker setSubject:emailTitle];
[picker setMessageBody:emailBody isHTML:YES];

NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
[picker addAttachmentData:imageData mimeType:@"image/png" fileName:[NSString stringWithFormat:@"%@.png", emailTitle]];

[[CCDirector sharedDirector] pause];
UIViewController *rootViewController = (UIViewController *)[[[CCDirector sharedDirector] view] nextResponder];
[rootViewController presentModalViewController:picker animated:YES];
[picker release];

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
[[CCDirector sharedDirector] resume];
[controller dismissModalViewControllerAnimated: YES];

And to show the picker from any scene in any orientation on iPhone and iPad, simply call the appropriate initializer:
// Email Body
NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:@"<html><body>"] retain];
[emailBody appendString:@"<p>Example Email Body</p>"];
[emailBody appendString:@"</body></html>"];

//Show the mail picker
[[EmailScene alloc] initWithTitle:@"Subject Line" body:emailBody image:takeScreenshot(rtx)];

Friday, 27 January 2012

LINQ to SQL Dynamic Stored Procedures

linqpadlogo[Concrete/Little bit interesting] I wanted to call stored procedures by name using a string parameter. Sounds simple and with ADO it's a breeze. But with LINQ to SQL, life is a little more complicated. Here is how I cracked the problem.





In Visual Studio, when you add LINQ to SQL Classes to you project, you are creating a class that provides a convenient set of classes for managing tables, views, functions and stored procedures:


When you add LINQ to SQL Classes to your project, Visual Studio creates a .DBML file set. These files describe the managed entities with partial class definitions. The main class is derived from System.Data.Linq.DataContext and provides the link between your code and the database connection. LINQ to SQL works through defining class members that maps LINQ onto the entity and makes use of attributes to map columns, parameters and returns to .Net classes.

LINQ to SQL Classes takes a lot of code out of your application and is easy to use. For example, to call a stored procedure, simply open the .DBML, drag a stored procedure from a data connection on the Server Explorer or Toolbox over onto the Object Relational Designer: this creates the class entries that maps the entity onto LINQ, then from your code, call the stored procedure as shown below:

using (CatalogueDataContext db = new CatalogueDataContext())    
db.usp_Biometrics_Update_OperatorFingerprint(input.OperatorId, input.Fingerprint, false);

In the above example, I’m calling the stored procedure usp_Biometrics_Update_OperatorFingerprint which is defined in a database called Catalogue, LINQ to SQL provides me with the data context on which the stored procedures are defined. All I need to do us use an instance of CatalogueDataContext and from this, call the stored procedure. Because it’s all about classes, Visual Studio can help me with the parameters and returns through Intellisense. 

The Problem

Under most circumstances calling a stored procedure as described above is sufficient. But there are times when you need to call a stored procedure by name, not by class method. Say for example you have a bunch of stored procedures called:


where TableName is a name of a table, any table. The implementation of this stored procedure for any given named table may be complex, for example, they may include selecting output from child tables where foreign key are present. So in this example, a table called Customer may return the following XML:

<address>First Postal Address<address>
<address>Second Postal Address<address>
So for each row of Customer data, there may be multiple address rows.
For another table called Car the data is simpler:
<model>Grand Voyager</model>

So for each table, I need a specific stored procedure that returns table data as XML. Each one of these stored procedure returns the XML data as an output parameter and all the stored procedures have the same signature. Below is an illustration of the stored procedure for the table Car:
Create Procedure usp_get_Car_As_XML

set @xml = (
registration, make, model
For XML RAW('row'), Root('rows'))

Return @@Error

So the problem is, from code, how do I call the stored procedure for a given table name, returning the XML representation of that table?

The Solution

Well of course I could use some sort of if…elseif… or big switch statement. This will work but I’m not keen on big switch statements. What I really want is to call the stored procedure by name. Fortunately, we can use .Net reflection to find the method in the data context and execute this method:

using (CatalogueDataContextEx db = new CatalogueDataContextEx())
XElement xml = null;
String script = String.Format("usp_get_{0}_As_XML", tableName);
db.CallScriptByName(script, ref xml);

//handle the results in xml variable
Notice that in this example, the data context is called CatalogueDataContextEx. This is a derived class based on CatalogueDataContext and implements the CallScriptByName() method:
public partial class CatalogueDataContextEx : CatalogueDataContext
public void CallScriptByName(String script, ref XElement xml)
var sp = typeof(CatalogueDataContext).GetMethod(script);
var result = this.ExecuteMethodCall(this, sp, xml);
xml = (XElement)result.GetParameterValue(0);

So what is going on here?

In my derived class I have access to all public and protected methods of the data context. This is important as I want to call the ExecuteMethodCall() method on the class, which is protected.

I’m using reflection to get a reference to the stored procedure by name, This is then executed using the ExecuteMethodCall. This call takes a list of the parameters to this stored procedure. In our case, there is only a single output parameter for the XML.

Once the call is made, the results are passed back in a IExecuteResult return parameter. This return can be used to access the call’s parameters, in our case the xml output parameter.

And that’s it.

Future Improvements

This implementation is not completely dynamic. Specifically, the CatalogueDataContext must have definitions for the stored procedures I’m going to call. A better implementation would use a generic data context and build up the method to call.

Wednesday, 21 September 2011

Using IActiveAware and INavigationAware

prism[Concrete/Little bit interesting] The Microsoft Prism framework provides a couple of very useful interfaces for managing awareness of view activation and navigation.





IActiveAware is a simple interface you can implement on your views to indicate that you want the view to be notified when it is made active or inactive. It looks like this:

public interface IActiveAware
    /// <summary>
    /// Gets or sets a value indicating whether the object is active.
    /// </summary>
    /// <value><see langword="true" /> if the object is active; otherwise <see langword="false" />.</value>
    bool IsActive { get; set; }

    /// <summary>
    /// Notifies that the value for <see cref="IsActive"/> property has changed.
    /// </summary>
    event EventHandler IsActiveChanged;

The IsActive flag lets you know if your view is active, and the IsActiveChanged event will fire when that state changes.

If you implement this on your view class, then you need to ensure the event gets fired when the state is changed by the region behaviour. You do this by adding the IActiveAware interface to your View-Model:

public class LoginViewModel : NotificationObject, IActiveAware, INavigationAware

An example of the implemented interface is shown here:

#region ViewModel activation
private bool _IsActive = false;
public bool IsActive
        return _IsActive;
        _IsActive = value;
        if (value)

public event EventHandler IsActiveChanged;

In the above example I use the changing state of IsActive to trigger the private methods OnActivate() and OnDeactivate(). These methods are thus called when the view active state changes.

IActiveAware Example - Managing Devices

A good example of the use of IActiveAware is the subscription to an control of devices. We use event aggregation to interface with physical devices, that is, we subscribe to device notifications. The simplest scheme is to subscribe to all the device events in the View-Model constructor:

//Subscribe to device events

Of course, this means that the View-Model will be called back on device events during the entire lifetime of the module housing the View-Model and the associated views.

To ensure you only act on the device events when your view is the active view, simply use the IsActive property appropriately in the event callback:

private void ScannerInputReceived(ScannerEventParameter param)
    //Handle input if active and OperatorId has focus
    if (IsActive == false || OperatorHasFocus == false)

    if (!string.IsNullOrEmpty(param.Barcode))
        OperatorId = param.Barcode;
        ValidateLoginInput(false, null);
        ProgressMessage = Resources.Message_InvalidInput;

OnActivate() and OnDeactivate()

These methods when implemented should be used to handle the View-Model initialisation and termination state. For example, in a Login screen, during OnActivate(), the View-Model should initialise the various entry fields and properties used to control the view:

private void OnActivate()
    ProgressMessage = String.Empty;
    ChangingPassword = false;
    NewBiometricEntry = false;
    LoginWithPassword = configurationManager.GetBool(ConfigurationNames.LoginWithPassword);


Here we are setting the title through a published event, clearing the progress message, clearing some flags (used to control the visibility state of page elements), resetting the OperatorId and Password and ensuring we are logged off. These operations will be performed every time a view in this module is activated.

IActiveAware Limitations and INavigationAware

Responding to IActiveAware works fine in a module that supports a single view. In this scenario, the View-Model activation is one-to-one with the View activation. However, if there are more than one view associated with a View-Model, you will have to implement INotificationAware:

public interface INavigationAware
    bool IsNavigationTarget(NavigationContext navigationContext);
    void OnNavigatedFrom(NavigationContext navigationContext);
    void OnNavigatedTo(NavigationContext navigationContext);

This interface when implemented provides callbacks to handle the navigationContext switch in the form of OnNavigatedFrom() and OnNavigatedTo(). A typical implementation here is to keep a copy of the navigationContext passed to the OnNavigatedTo(). This can be used later to perform view-to-view navigation:

#region Navigation Aware for view switching in this module
private IRegionNavigationService navigationService;

public bool IsNavigationTarget(NavigationContext navigationContext)
    return true;

public void OnNavigatedFrom(NavigationContext navigationContext)

public void OnNavigatedTo(NavigationContext navigationContext)
   navigationService = navigationContext.NavigationService;

and to perform view-to-view navigation (for example, Go Back):

private void onGoBackHandler()
    if (navigationService.Journal.CanGoBack)

Note that in the above implementation of the interface we are returning true from the IsNavigationTarget() method. This method is called by the framework to determine if the current views should be reused for the navigation target. Returning true indicated the views should be reused. Since we pre-create all our views, you should return true.

Thursday, 8 September 2011

This is a test Article on the blog



Here is a picture

Like it?



Actually, this is a test for using Windows Live Writer to publish to SharePoint Wiki. Which sounds easy, but you guessed it, it’s not.

I’ll let you know how I get on.


Frankly, it’s all rather disappointing. I guess someone at Microsoft, looking to make SharePoint a little more useful thought “well it’s good at lists and HTML docs, if you add a template with an on-page editor, hey presto, you’ve got a Wiki”. Only, it’s not that simple and the editor is far too lightweight.

Windows Live Write (WLW) on the other hand is a well thought out, powerful tool. Clearly the best Blog editor in my mind. It’s the reason I have a Windows VM on my Mac.

So I gave it a go and WLW doesn’t want to talk to the Wiki because it’s not a blog, doesn’t support the APIs, just a list with an editor.

However, it was suggested that I could author my pages against my SharePoint blog. Great. It worked brilliantly. WLW talks to SharePoint blogs and does an excellent job of it.

Once published, all you have to do is open the blog in SharePoint for editing, copy the raw HTML and paste it to the Wiki.

It works, but it’s far from perfect

The main advantage of this is the editor in WLW. It’s excellent, support plug-in for styles, adopts site templates. I’m using it now and what I type is what I will see on the blog site.

A very useful benefit of this approach is image publishing. It’s a royal pain in the arse when editing on the SharePoint Wiki. Using this method, images are published to my blog and can be referenced in the Wiki without need to upload anything or mess around.

But the main problem is I’m publishing to a blog and have a second copy in the Wiki. I may even have a third local copy on my Mac saved by WLW. These copies can easily get out of step.

Worse still, the images are associated with a my blog and my account, not the Wiki. If my account gets deleted, I guess these resources will disappear.

Finally, the point of a Wiki is that the documents are live and through collaboration, the Wiki will change over time. So my copy on my blog is very likely to be out of step. This could result in changes being lost as the WLW view of the document is that of the blog, not the Wiki.

You could of course create a shared blog and keep this as the master document site. I thought of this and it occurred to me that if I was to do this, I might as well try to use that as my Wiki. Well that made the whole exercise seem pointless.

Improved on-page Editing

You can of course change the Wiki template to use a more advanced editor. This is a very satisfactory solution. One of the recommended ones is the Telerik RadEditor that can be integrated into SharePoint 2010:

Problem is, it cost about $800. And I’ve already spent half that purchasing a better Forum web part because the out of the box solution from Microsoft is just rubbish. Starting to sound like throwing good money after bad,

Microsoft SharePoint Designer 2010

Ok, time to bring the big guns out. I’m only trying to update pages on the Wiki!

Well, this is a powerful tool. It’s also typical of the development/management tools from Microsoft. Yes, I can edit the Wiki, but it’s not easy. Ultimately, this tool provides a Visual Studio / Microsoft Expression type of view on the site and site document. Not really what you want.



I’ll keep looking for a better solution to editing on-page in SharePoint. Maybe Microsoft will provide a link between WLW and SharePoint Wiki.

However, until a solution is found, the SharePoint Wiki experience will be very disappointing.

Given that for a Wiki, the ease of authoring and content creation is as important as the content itself, you might just decide that SharePoint doesn’t even qualify as a Wiki.

Monday, 30 May 2011

Fermat’s Last Theorem

image[Concrete/Interesting] A while back I saw a BBC Horizon programme about Fermat’s Last Theorem and the mathematically heroic work by Andrew Wiles in raising the Taniyama-Shimura conjecture from a mere conjecture to a theorem and using this to show a contradiction between the predictions of the epsilon conjecture and Wiles’ proof that all such elliptic curves must be modular. This contraction implies there are no solutions to Fermat’s equation, hence Fermat’s equation is true.


Like many, I was excited about this proof and although difficult to follow (Elliptic Curves are hard to understand, no kidding), the proof was without a doubt a clever piece of late 20th century mathematical wizardry, full of deep insight and imagination.

But something was wrong. It was all to clever, all too complex, all to contemporary. So to mark the birth of my new baby boy, Khaliq, I decided to provide a simple proof, maybe not complete in mathematical rigor and probably nowhere near robust enough for Cambridge Mathematics, possibly not even correct, but something I think 17th century mathematicians would have found interesting. See what you think.


To my son, Khaliq George Mahmood, born 26th May at 11.24pm (7lb, 12oz). Hope you find life as fascinating as I have.


Fermat’s conjecture is so tidy, so elegant and simply described as:


That is to say, for all integers, except 2, the equation has no non-zero integer solutions. For 2, where we square x and y, the sum of the squares of x and y is equal to the square of z

For n = 2, this may be familiar to some of you, and is known as The theorem of Pythagoras. Pythagoras, mathematician, philosopher and scientist, provided a proof for his equation based on logic and simple geometry. In fact, the equation was known to many at the time, but is was the application of mathematical rigor that gave Pythagoras the title over the equation.

It is from the relationship between the equation and a right angle triangle that I will start my ‘proof’’.

Mathematical Rigor and Proof

Mathematics is complicated, at least for the majority of us.I don’t want to pretend I am a mathematician or blessed with anything but a cursory level of competence in mathematics.

For a proof to stand on it’s own two legs it must be a convincing argument and this must be based on deductive reasoning which shows a statement to be true in all cases. Ok, so I don’t think I’m going to be able to do that. But I hope I can present an somewhat unproven proposition that I believe to be true – that, at least is a conjecture, and is something others may be able to prove.

So away with the shackles of mathematical rigor, eyes down for what I hope is an interesting conjecture:

Not Now Nigel’s Conjecture

Above n=2 where n is the geometric dimension, there are no simple object with 3 ‘flat’ boundaries.

By way of explanation, for n=2, the equation maps to a 2 dimensional polygon with three flat or straight line boundaries, commonly known as a Triangle:


But for higher dimensions, there are no object with 3 ‘flat’ sides. For example, for 3 dimensions, there is no polyhedron with 3 planar surfaces. The nearest is something like a Tetrahedron with 4 sides.

In proving this conjecture and in saying that Fermat’s equation is represented by this geometry, there lies a simple proof to Fermat’s Last Theorem. Q.E.D.