.NET Live Coding Talk in London UK at Medidata

On December 5th, I delivered a live coding demo at Medidata’s UK office, going over some of the newer stuff for .NET Web Developers. It’s 48 minutes long and covers MVC5, VS2013, EF6, SignalR 2 and some other bits while I build a rudimentary Twitter clone called “MediTwit”. Nuget blew up about half way through but we recovered. Full video below (visit the full post page to view): Read more

Open Sourcing “Cognition”

One of the perks of working in R&D at Medidata is “Innovation Time”. Twice a year, engineers get to spend two weeks building whatever they want. Ideally some of the things we build will go back into direct product development but if not, we are encouraged to open source the work.

Fresh from attending Microsoft’s Build 2013 conference in San Francisco, I wanted an excuse to use all the latest Microsoft web stack tools. Namely:

  • Visual Studio 2013 Preview
  • ASP.NET MVC5 Beta
  • Entity Framework 6 Beta
  • SignalR 2.0 Beta

I also wanted to test out CouchDB, which was made infinitely easier with the awesome MyCouch library by Daniel Wertheim. The result of which is “Cognition” – a cross between a wiki and a CMS that can be used as a basic CRM, a job board or knowledge base. The result of two weeks work can be seen on the company repo at https://github.com/mdsol/cognition – a test site can be seen hosted on Azure at http://cognition-demo.cloudapp.net. There is quite a lot of rough code with scant test coverage, unfortunately necessary to get the experiment out the door in two weeks. It does however show what is possible with the .NET web stack.

imageimage

Here is a short video showing the current state of the app (no audio – visit the full post page to view): Read more

Windows 8.1’s user-hostile backup story

Update 13th June 2015: It looks like Microsoft has reversed course and reinstated the Windows 7 Backup and Restore feature in Windows 10! Success!

Update 16th Sept 2013: What follows is a rant written after upgrading to 8.1 and seeing my automated backups just stop working and the backup restoration function also removed. An afternoon was wasted faffing about with the new File History feature which still refuses to backup files not on my system drive and deliberately ignores files in the SkyDrive folder, preventing you from having a local backup. I now use CrashPlan which behaves like Windows 7 and 8.0 used to be able to back up files.

Windows 8.1 is now released to manufacturing and those with MSDN or Technet Subs can download it now.

I have the RTM version now set up on home and work machines and have been running the Preview versions on both my Surface RT and Surface Pro. Windows 8.1 has some glaring errors.

SkyDrive integration now built in, removes features compared to the old Desktop client

You no longer have to install the SkyDrive app separately as it is now built into the OS. Windows 8.1 makes a concerted effort to force you to use SkyDrive.

image

The above is a screenshot of a screen displayed during the upgrade process. Can you see the error?

“automatically backed up to the cloud”

This is nonsense – if you delete a file from your local machine, it will be deleted from the cloud. This is NOT a backup. Live mirroring is NOT a backup. If a sync goes wrong – your file disappears completely. There is no backup.

Edit: Turns out SkyDrive has a “Recycle Bin” for deleted files, but it removes files once it is full or after 30 days. So, you might randomly be able to get your file back. Version History also only works for Office documents.

imageimage

On the left is Windows 8’s SkyDrive integration after installing the SkyDrive Desktop app. On the right is Windows 8.1’s built-in SkyDrive integration. This is now a system-level folder and doesn’t even have the syncing icons available. This folder is now virtualized and you aren’t guaranteed that the actual file will be present. Opening the file will sometimes download it from SkyDrive.

The “Windows 7 File Recovery” backup system has been removed in 8.1

Windows 8.0 actually contained two backup systems, the new “File History” and the awesome old backup system from Windows 7, threateningly renamed “Windows 7 File Recovery” as a warning that this will be removed. Lets compare the systems:

Windows 8 File HistoryWindows 7 File Recovery
Files in Libraries and desktop onlyAll files in all locations supported
No system image supportFull system image support
No progress barProgress bar

File History is Microsoft’s attempt to copy OS X’s Time Machine, except Time Machine actually backs up all your files and lets your restore the entire OS partition, just like Windows 7 did! At least you had the choice in 8.0 to use the old system. In 8.1, Windows 7 File Recovery has been removed completely, you can’t even restore your old backups!

Edit: You can create a System Image in 8.1 (Click “System Image Backup” on the File History screen) but this doesn’t work on an automated schedule, so is not an automatic backup.

It gets worse. File History is even more useless in 8.1.

“File History” no longer backs up your SkyDrive folder in 8.1

Microsoft really don’t want you to have a local backup of your SkyDrive files. Take a look at this:

image

Above: Windows 8 File History

image

Above: Windows 8.1 File History

No problem you think? Just add your SkyDrive folder to a Library and it should back up? Nope – all the SkyDrive files are ignored completely, even if you manually add them to a Library.

The response from Microsoft on this is beyond tragic (from here):

image

Your files “are protected by the cloud in case user lose/damage their device”. What about protection from user error or viruses or badly written programs? If your files get corrupted the corrupted files will sync to the cloud and then sync to all your other devices.

Conclusions

It appears that Microsoft are desperate to push SkyDrive, even at the expense of the computing safety of their customers – customers you’d hope were being educated about safe computing. Now I am on 8.1 I am personally stuck with no built-in backup system. My experience with File History has been awful – it appears to even ignore an additional Library I’ve created to include non-library files. I literally cannot get it to back up files on my computer, it is useless. I am going to have to go with a third-party backup system like CrashPlan now.

Windows 8.1 was Microsoft’s chance to undo the wrongs of Windows 8. Users are now faced with the prospect of upgrading and being faced with no backup solution, or even worse their existing backups just stopping working with no warning.

Sort it out Microsoft.

Edit: Some excellent discussion on this over at Hacker News: https://news.ycombinator.com/item?id=6388431

ASP.NET MVC Basics Part 2: ViewModel to Model Mapping and Editing

In Part 1, I walked through creating a simple form with a backing ViewModel and Validation. In Part 2, I’ll walk through creating a backing Model and Edit functionality.

To start off from here, load up the code from part1: https://github.com/edandersen/mvcformtutorial/tree/part1

The final code for Part 2 will be uploaded here: https://github.com/edandersen/mvcformtutorial/tree/part2

Model Mapping flow

viewmodel-model-mapping

When editing a ViewModel, we need to prepopulate the view with real data from a domain model. This can be a database table mapped to an object via an ORM or data from another source. In the diagram above, we can see the GET Edit action requesting Model with an ID of 123 from the Repository holding the model data, creating a ViewModel that represents the Model and passing it onto the View to render. POSTing the data back is similar to the Create POST method in Part 1, except we load the existing Model from the repository, update it with the validated data from the ViewModel and update the model in the Repository.

Read more

ASP.NET MVC Basics Part 1: View Model binding

I’m going to walk through the basics of Form submission with ASP.NET MVC, showing some best practices. This set of tutorials will be useful for developers moving away from ASP.NET WebForms into ASP.NET MVC or even Rails developers curious about how we do things in .NET.

You can download the code for Part 1 at: https://github.com/edandersen/mvcformtutorial/tree/part1

Form submission flow

If you have come from WebForms, you’ll be used to being able to pull form values out in the code behind by simply referencing variables in your code behind. These magically map to elements on the page and most of the time you are blissfully unaware how the data gets there. With MVC, we don’t have the same abstraction. Whereas you can access POSTed variables directly with FormsCollection (or params in Rails) but with the ViewModel pattern, we can simulate the binding that ASP.NET provides and access our form variables in a strongly typed manner.

aspnet-form-submission-1

Read more

Life with Surface RT – and why I’ve upgraded to a Surface Pro

I picked up my Surface RT on launch day last year as I happened to be in New York for work. The strong yen made it a bargain and I’ve been living with it since. Because it won’t run most desktop apps, it has seen limited use. It was an excellent video player during flights, but nothing an iPad could not have handled. Word made a passing replacement for Windows Live Writer with it’s built in blogging system, but it wasn’t perfect. Thanks to Microsoft locking down compilation for ARM-based apps, third parties have not been able to fill in the missing functionality gaps.

Read on for my views on living with the Surface RT for six months, and why I’ve picked up a Pro.

 

IMG_8819[1]

Surface Pro on the left, Surface RT on the right. Note the difference in kickstand angles.

 

The Surface RT as a Remote Desktop machine

Where the Surface RT absolutely shined was a thin client, Remote Desktop machine. The latest version of the RDP Protocol that ships with Windows 8 is another leap forward from previous versions. Whilst we lose Aero remoting, we gain adaptive encoding that encodes different parts of the screen in the most appropriate fashion, changing algorithms for text, pictures and even video. Video now streams due to re-encoding on the host side – previous versions of RDP required Media Foundation compliant players which would attempt to bitstream the actual video file when being played. In reality, this only worked with Windows Media Player when playing MP4 or WMV video files. UDP support also improves connection reliability.

Remote Desktop is the reason I am not keen on using Macs when I have even one Windows machine in active use. The version of the Remote Desktop client for OS X runs a protocol somewhere between Windows XP and Windows Vista – it supports network-level authentication but the performance is that of an old Windows XP client, with almost a decade-old set of algorithms for streaming the session. It is unusable over cellular links and glitchy even over LAN. Surface RT of course has none of these problems due to an up to date client.

Surface RT for work

Because you cannot install binaries unless signed by Microsoft, you can kiss goodbye to the idea of doing any “real” work on the host OS of the Surface RT, beyond simple Office work in Word and Powerpoint. Outlook is not available, so you’ll be relegated to webmail (the Metro Mail app is so bad it is not worth talking about). You can of course Remote Desktop to a work machine, but be warned that if you require a non-standard VPN connection (such as Cisco AnyConnect), you won’t be able to install the software required to connect to your workplace.

I travel a bit for business, and the Surface RT has been great as a video player – the built in kickstand perfectly fitting on an economy airline table. The battery life will last even the majority of a 13 hour flight. Just remember you won’t be able to do real work on it (unless Powerpoint is your job) – so if you are flying business because your firm hopes you might get some work done (and be well rested), you’ll need to bring a real laptop with you. The Surface RT is small enough to slip in the same laptop sleeve as the MacBook I use for work, so carrying it is not a burden. However, MacBooks can play videos quite well and business class has power adapters so the Surface is a bit unwelcome if you have a “work laptop”.

Why buy a Surface Pro when I already have a Surface RT

So what made me get a Surface Pro? Ultimately it came down to it’s biggest failing – note-taking. Surface RT ships with it’s killer app, OneNote, but with a touch screen that won’t handle stylus input. I wanted to do some sketches in OneNote, so picked up the Adonit JotPlus capacitive stylus. Whilst it was somewhat accurate enough, the lack of palm detection made writing and drawing impossible. In OneNote – an application designed for handwriting and drawing. Palm Detection prevents your hand from interrupting your drawing, but with no stylus support, the Surface RT has no way of knowing what is a “pen” or your finger.

This was a bridge too far. I used to use OneNote back at university with the awesome, ahead of it’s time, HP TC1100.

hp_tablet_pc_tc1100_tastatur

The HP TC1100 discontinued in 2005 – look familiar?

The TC1100 had a Wacom stylus and digitizer (like the Surface Pro), a detachable keyboard (like the Surface Pro) and a 10.1 screen (like the Surface Pro, but 4:3 like the iPad, so actually useable in portrait orientation). Tablet PCs fell out of fashion around the time Windows Vista came on the scene – maybe because it wouldn’t run on any of them.

I remembered how OneNote basically got me through four years of note taking at University with this pen, before the battery completely died.

So, the Surface Pro can do everything the RT can do, except run for 9 hours on a single charge. However, it has a stylus, runs all Windows apps, supports unorthodox VPN software and even uses the same Touch Cover of the Surface RT? I was sold.

Buying a Surface Pro in Japan

After picking up the Adonis JotPlus pen from LOAX in Shibuya, trying it out in the pub and realizing that this isn’t the tablet experience I remember from 2004, I got on a train to Akihabara to see if I can find a Surface Pro.

Surface Pro has no scheduled date for Japan. Next month, Microsoft will release the Surface Pro in the UK, Australia, Austria, Belgium, Denmark, Finland, France, Germany, Hong Kong, Ireland, Italy, Luxembourg, New Zealand, the Netherlands, Norway, Portugal, Spain, Sweden, and Switzerland. But not Japan.

The first place I went was IOSYS in Akihabara, opposite Donki Houtei – the same place I got my Nokia Lumia 800 last year. This is a great shop that sells imported (US) phones and tablets. They had the Surface Pro in stock (along with the RT), the 64GB model was 124,999 yen, the 128GB was 139,999 yen. Note that this does not include a Touch or Type Cover (I already have a Type Cover for the RT) and works out at about $1400 – a 40% markup on the US RRP of $999. This isn’t a bad deal considering sales tax, shipping and the possibility of being stung by customs on import taxes. Its still a significant markup, but they do provide a 6 month warranty. I picked up the 128GB model.

First Impressions

The Surface Pro is slightly thicker than the RT, but unless you compare the two side by side, you don’t notice after a while. The angle of the kickstand is a little lower (meaning that it points up a bit more). The screen is at 1920×1080 and Windows has the desktop scaled to 150% to compensate. Be ready for some blurry text in badly-written applications unless you drop it down to 100% scaling. The high resolution isn’t too unusable if you are sitting in front of the machine, but the same restrictions about using it in your lap apply. Not that you’d want to – both Surface models are notoriously hard to use with the keyboard attached on your lap on in bed.

Performance is that of an average Core i5 laptop with an SSD installed. Visual Studio and SQL Server both installed in 15 minutes, whereas Office was pre-installed. All my machines are SSDs now, so performance is very similar across devices – the slightly slower processor here might bite me later if I decide to do something like encode video on the Surface Pro, but I would probably farm that out to my desktop machines. The RAM is a paltry 4GB but Windows 8 is very economical with OS memory usage. Serious processing tasks will still be farmed out to a larger machine.

The pièce de résistance is the stylus. It attaches to the power charger magnets instead of sliding inside the device like older Tablet PCs. The magnets are strong though and I haven’t had it disconnect in my bag yet. I don’t think this will be as easy to lose as some reviews are claiming. The stylus in OneNote compared to the JotPlus “fake finger” stylus is like night and day – the pen supports multiple pressure levels and you can reverse it and erase with the opposite end of the pen – exactly like in 2004. The biggest downside is the widescreen ratio of the Surface and the fact that portrait mode looks so stupid – maybe we’ll get a 4:3 version someday.

For media playing, it does everything the RT does, but you can actually install VLC and WinAmp. No longer do I have to convert MKVs to MP4 like I had to on the RT.

Overall

Ultimately I feel I will still use the Surface RT as a “holiday” device and the Surface Pro as a “business trip” device. The RT does everything I need for recreational purposes, with the ability to Remote Desktop into a “real” machine if I need access to unavailable applications. The Pro however, whilst I have no intention of doing so myself, could easily be a desktop replacement. The stylus has already reawakened my almost decade old OneNote obsession.

I’ll probably write up my experiences with the Surface Pro in a couple of months time. Stay tuned.

Adding a Dynamic Robots.txt file to an ASP.NET MVC site

Robots.txt is required to allow search engines to properly index your site, and more importantly not index it. If you have a public-facing staging or preliminary site that you don’t want to show up in Google results, you need to make sure that it returns the correct robots.txt with the

Disallow: /

line to prevent indexing. However, manually adding robots.txt files to staging and production environments as a manual process can be improved with the process below – the same code can serve up a locked down robots.txt in staging or internal URLs, and allow indexing in production.

First, add a route that responds to /robots.txt in either Global.asax.cs or RouteConfig.cs before your Default routes:

routes.MapRoute(
"Robots.txt",
"robots.txt",
    new
    {
        controller = "Robots",
        action = "RobotsText"
    }
);

You’ll also need to make sure that runAllManagedModulesForAllRequests is true in web.config as normally text files bypass the ASP.NET pipeline:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"></modules>
    ...
    </handlers>
  </system.webServer>

The create a new controller called “RobotsController” with a single action “RobotsText”. All requests to /robots.txt will go here:

    public class RobotsController : Controller
    {

        public FileContentResult RobotsText()
        {
            var contentBuilder = new StringBuilder();
            contentBuilder.AppendLine("User-agent: *");

            // change this to however you want to detect a production URL
            var isProductionUrl = Request.Url != null && !Request.Url.ToString().ToLowerInvariant().Contains("elasticbeanstalk");

            if (isProductionUrl)
            {
                contentBuilder.AppendLine("Disallow: /elmah.axd");
                contentBuilder.AppendLine("Disallow: /admin");
                contentBuilder.AppendLine("Disallow: /Admin");
                contentBuilder.AppendLine("Sitemap: http://www.mysite.com/sitemap.xml");
            }
            else
            {
                contentBuilder.AppendLine("Disallow: /");
            }

            return File(Encoding.UTF8.GetBytes(contentBuilder.ToString()), "text/plain");

        }
    }

You can try a number of ways of detecting a production environment, from the naïve URL checking above to environment variables in your application container.

Surface Windows RT DOES NOT support Cisco IPSec VPNs

A promising slide from TechEd 2012 promises VPN support for Cisco VPNs:

And from here:

The TechEd 2012 session “Windows 8: Windows RT Devices for Business” (http://channel9.msdn.com/ Events/TechEd/NorthAmerica/2012/WCL202) stated at the 26 min mark that Microsoft incorporate the Cisco VPN client into Windows RT out of the box.

It doesn’t work for most Cisco VPN setups where the IT department has decided to use PSK authentication. Windows never natively supported the IPSec Identifier, or “Group Name” feature in Cisco VPNs, which I argue would be the vast majority of real use cases.

See? No Group Name option. Compare this to OS X:

OS X supports Cisco IPSec natively and has a field for Group Name. iOS also does.

On Windows RT, you cannot install the Cisco AnyConnect client. You shouldn’t have to do this anyway – Windows should natively support this, as Apple has chosen to do. Some people are going to get pretty annoyed when they realize they can’t use Windows RT devices to remote in to corporate VPNs, although some would argue that corporate VPNs should be using certificates and not Pre Shared Keys for IPSec.

iPads can connect to Cisco VPNs natively – sort it out Microsoft.

Remap CapsLock key to Control key on Surface Windows RT

The CapsLock key is rubbish. Remapping it to Control is easy on OS X and the Happy Hacker keyboard I use on my desktops doesn’t even have one. On standard Windows you can run a key remapping program but WinRT is locked down (for now). Here is an easy way to map Caps Lock to Control.

First, hit the Windows key and type “Powershell”. Right click on the Powershell icon. You will see some options appear at the bottom of the screen – click “Run as Administrator. Agree to the UAC elevation prompt.

The elevated Powershell prompt will appear. You need to enter the following command and hit Enter:

Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Control\Keyboard Layout" -name "Scancode Map" -Value ([byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x1d,0x00,0x3a,0x00,0x00,0x00,0x00,0x00))

This sets up some keyboard scancode remapping in the Registry, which is what keyboard remapping programs would do if they had access. Restart the machine (swipe from right, Settings Charm, power, Restart) to make the change take effect.

Good riddance Caps Lock!

AdBlock alternative on Windows RT’s IE10

On the Surface’s Windows RT, you cannot install alternative browsers. This means no AdBlock.

There is a workaround to this, using IE10’s “Tracking Protection”. First, fire up desktop IE10, click the little gear in the top right and select Safety -> Tracking Protection. Click on “Get a Tracking Protection List online…”.

You should see a list of tracking protection lists on Microsoft’s site. You will want to click Add next to the Easylist lists. These might not cover all ads – feel free to add a few more.

With these lists added to IE10, both the Desktop and Metro versions will filter out the ads. This method is not quite as good as AdBlock which removes the ads from the screen entirely, but is better than nothing.

See before and after screenshots of The Register in Metro IE10 below.