SQL Server Management Studio is Free

SQL Server Management Studio aka SSMS is available to download and use for free from Microsoft. You do not require a SQL Server license.

The latest version of SSMS, and future versions, are available from here:

https://msdn.microsoft.com/en-us/library/mt238290.aspx

This makes this easier for developers and DBAs that want to work with SQL Server, without having to acquire and install a full, licensed SQL Server ISO.

Walkthrough: Using WinRT libraries from a Windows Desktop application

Summary

These are the steps for enabling WinRT libraries from within your Windows Desktop application. A more detailed walkthrough and explanation follows.

Steps

1) Editing your project file, add the platform target:

    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

2) Add the following references:

    <Reference Include=”Windows” />
<Reference Include=”System.Runtime” />
<Reference Include=”System.Runtime.InteropServices.WindowsRuntime” />
<Reference Include=”System.Runtime.WindowsRuntime” />

3) Load your project properties, and change the platform target from AnyCPU to x64 (or x86 if you’re on a 32 bit operating system).

Prerequisites / Limitations

  • You are obviously limited to WinRT-supported platforms: Windows 8 & 8.1, Windows Server 2012
  • Some of the WinRT libraries won’t work on the desktop platform, usually because they require a WinRT user interface. Pay attention to the MSDN docs which state whether they’re available for Desktop, but also feel free to experiment, as in some cases the docs are not accurate (for example, the Geolocation works on Desktop but the documentation states Windows Store apps only).

Overview

You might be surprised to know that WinRT can be used from Windows apps also, with a little bit of tweaking.

What is WinRT?

  • WinRT is not .NET or Win32, though it shares some similarities between both.
  • WinRT is an API over a new runtime, that supports platforms from Windows x86 to Windows Phone ARM.
  • WinRT is implemented in C++, but you can develop for it using C# and VB.NET.
  • Because the WinRT metadata is exposed as CLI metadata (in .WinMD files), you can reference and consume them from your CLR applications.

Why would you want to use WinRT?

Walk-through: Changing the Lock Screen

As a case study, we will look into changing the user lock screen to the Bing daily picture.

Prerequisites

  • You will need to be reasonably comfortable with async code, as most of the API is exposed via Tasks.

Getting started

Create a new Windows C# command line application:

clip_image001[4]

I’ll call mine WinRTTest.

Referencing a WinRT library: Take 1

Now let’s try adding a reference to a WinRT library.

Go to Add Reference, and choose Browse:

clip_image002[4]

Then hit the Browse button, and select C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral\Windows.winmd (or the 8.1 version) and click OK.

CLANG!

clip_image003[4]

Checking the documentation as instructed, we read this:

In the desktop projects, the Core subgroup doesn’t appear by default. You can add the Windows Runtime by opening the shortcut menu for the project node, choosing Unload Project, adding the following snippet, and re-opening the project (on the project node, choose Reload Project). When you invoke the Reference Manager dialog box, the Core subgroup appears.

<PropertyGroup>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

From <http://msdn.microsoft.com/en-us/library/hh708954.aspx>

Great! So now we know we must specify our target platform as 8.0.

Preparing the Project File

First let’s edit the project file; right click on the project file and choose Unload Project then Edit Project File.

I’ll add the target platform property in the property group at the top of the project file:

  <PropertyGroup>
<Configuration Condition=” ‘$(Configuration)’ == ” “>Debug</Configuration>
<Platform Condition=” ‘$(Platform)’ == ” “>AnyCPU</Platform>
<ProjectGuid>{4725C47D-8877-47C8-BD56-134E656BFF09}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WinRTTest</RootNamespace>
<AssemblyName>WinRTTest</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

Referencing a WinRT Library: Take 2

Now reload the project and choose Add Reference… again. Suddenly, the Windows tab is available for us:

clip_image006[4]

Let’s tick Windows and click OK.

Now let’s start coding with the WinRT libraries.

Adding the HttpClient NuGet package for downloading the Bing picture

The HttpClient class will be a nice easy way for us to use the Bing Daily Picture service.

First, add a reference to the NuGet package for the HttpClient.

  1. In the Visual Studio menu, go to Tools > NuGet Package Manager > Package Manager Console
  2. Then type in the following command at the prompt:Install-Package Microsoft.AspNet.WebApi.Client
PM> Install-Package Microsoft.AspNet.WebApi.Client
Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.4)'.
Installing 'Newtonsoft.Json 6.0.4'.
Successfully installed 'Newtonsoft.Json 6.0.4'.
Installing 'Microsoft.AspNet.WebApi.Client 5.2.2'.
You are downloading Microsoft.AspNet.WebApi.Client from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/net_library_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Microsoft.AspNet.WebApi.Client 5.2.2'.
Adding 'Newtonsoft.Json 6.0.4' to WinRTTest.
Successfully added 'Newtonsoft.Json 6.0.4' to WinRTTest.
Adding 'Microsoft.AspNet.WebApi.Client 5.2.2' to WinRTTest.
Successfully added 'Microsoft.AspNet.WebApi.Client 5.2.2' to WinRTTest.

So now we have our new references:

clip_image008[4]

The Code

Now, paste in the code below:

 

Note that we are hard-coded to get the 1080p version of the desktop, and there’s not much error handling. We’re keeping it nice and brief; getting the appropriate wallpaper size and error handling could be left as a future exercise.

David, your code sucks. It won’t compile.

I can’t argue with those statements:

1>------ Build started: Project: WinRTTest, Configuration: Debug Any CPU ------
1>C:\Projects\WinRTTest\WinRTTest\Program.cs(37,32,37,168): error CS4028: 'await' requires that the type 'Windows.Foundation.IAsyncOperation<Windows.Storage.StorageFile>' have a suitable GetAwaiter method. Are you missing a using directive for 'System'?
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

If you paid close attention to the MSDN docs earlier, it referred us to another page which states:

That said, your desktop app can’t consume much of anything from the Windows Runtime until you prepare your project with one essential reference. The Windows Runtime defines some standard classes and interfaces in System.Runtime, such as IEnumerable, that are used throughout the Windows Runtime libraries. By default, your managed desktop app won’t be able to find these types, and so you must manually reference System.Runtime before you can do anything meaningful with Windows Runtime classes.

From <http://msdn.microsoft.com/en-us/library/windows/apps/jj856306.aspx#consuming_standard_windows_runtime_types>

While we could browse around for files, I believe it’s actually less error prone and simpler to reference the assembly name in our project file, and let Visual Studio do the rest. It also means you can prepare your project for WinRT in one edit of the project file (see the summary at the top of the article).

Now the System.Runtime reference isn’t going to be enough for us, as the async support extensions are in the WindowsRuntime classes. So add the following:

    <Reference Include=”Windows” />
    <Reference Include=”System.Runtime” />
    <Reference Include=”System.Runtime.InteropServices.WindowsRuntime” />
    <Reference Include=”System.Runtime.WindowsRuntime” />
</ItemGroup>

Now we can compile!

Testing

So we run the app. The image comes down and is saved into our Pictures folder as LockScreen.jpg:

clip_image009[4]

But if you lock your machine by hitting Windows + L, our lock screen isn’t showing the changes.

Weirdly, it’s showing in the control panel though:

clip_image010[4]

Well after some trial and error myself, let’s change the target platform from AnyCPU to x64 (or x86 if you’re on a 32 bit machine):

clip_image011[4]

And it should suddenly work!

Now, it’s unclear why this is necessary (and why we see no errors, and the lock screen actually shows in the control panel). Frustratingly, I can’t troubleshoot the problem properly, as setting the platform target back to Any CPU suddenly continues to work also. There may be something else happening here; so I will update this article if an explanation ever comes to light.

Conclusion

Now you can play around with some of the interesting WinRT libraries from your desktop applications, as well as exciting new WinRT extensions such as the Microsoft OCR Library: http://blogs.windows.com/buildingapps/2014/09/18/microsoft-ocr-library-for-windows-runtime/

GORILLA.BAS, QBasic & Edit

Nostalgia time!

Back when I got my first PC, QBasic was part of the operating system.

I spent hours and hours playing around with QBasic and MS-DOS Editor (or simply edit as we all knew it) to see what graphics and games I could whisk up.

There was a game that came with QBasic and MS-DOS called Gorillas, which was effectively like Worms and Scorched Earth.

Look at those mind-blowing graphics!

Man, have editors and IDEs come a long way; but edit was a great editor for its time. What a twinge of nostalgia I feel when I see this screen:

http://www.computerhope.com/jargon/e/doseditwindow.jpg

Edit came along for the ride all the way to Windows 7; but sadly, it doesn’t come with any 64 bit OSes.

RIP, old friend.

Fix the missing right click menu for Unreal Engine Projects (.uproject)

When you right click on an Unreal Engine project file (.uproject), these is the kind of menu options you should see:

image

But what do you do if you only see this? :

image

The right click context menu is set up via the Windows Registry.

You could get someone to export their working keys for you, but their installation paths may be different to yours.

I’ve created a Windows batch file instead which will:

  1. Try to find the Unreal Engine installation path on your machine
  2. Add the necessary registry keys to register the Unreal Project type, and the right click options.

You need to make sure the batch file is run with administrator privileges, as it needs to write to HKLM.

You can download the batch file (zipped up): Unreal Project Menu Registration.

Here’s the source code:

 

Unreal Tournament 3 (UT3) Protocol Registry Fix for launching UT3 links

UT3, at least installed via Steam, doesn’t seem to register a URI scheme in Windows so that you can create links to UT3 servers, as was possible in earlier versions of Unreal Tournament.

This can be fixed by manually adding a ut3 protocol to the Windows registry.

Instructions

  1. Download the initial registry fix, but don’t merge it yet: Download UT3 Protocol registry fix
  2. Open it with a text editor such as Notepad
  3. Change the install location to make where you have UT3. If your steam library is by default C:\Games\Steam, then you won’t have to change anything.
  4. Save the file.
  5. Double-click the file to merge it with Windows Registry; click Yes at the warning prompt to proceed.

For information’s sake, the contents of the registry file is below. You can create your own registry file from this by copying and saving the text, giving the file a .reg file extension.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\unreal]
@="URL:Unreal Tournament 3 Protocol"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\unreal\DefaultIcon]
@="C:\\Games\\Steam\\steamapps\\common\\unreal tournament 3\\Binaries\\UT3.exe,1"

[HKEY_CLASSES_ROOT\unreal\shell]
@="open"

[HKEY_CLASSES_ROOT\unreal\shell\open]

[HKEY_CLASSES_ROOT\unreal\shell\open\command]
@="\"C:\\Games\\Steam\\steamapps\\common\\unreal tournament 3\\Binaries\\UT3.exe\" \"%1\""


I will look into automating this to detect where UT3 is installed, but I’m not sure how or where to get this information from Steam programmatically.

Creating server links

Format:

unreal://serveraddress:port

The address starts with unreal://, followed by the server name or IP address, then the server port (default being 7777).

UT3 apparently only likes the unreal protocol; changing it to ut3 or ut, the game complains at launch time about the URL.

Examples:

Using MSBuild property functions and inline tasks: Example doing performance calculations

The Problem

User RandDavis on Reddit asked a question about capturing elapsed time of tasks in MSBuild:

I’m using MSBuild 4.0 (I also have MSBuild.Community.Tasks available). Note that I’m new to the syntax involved. All I’m trying to do is this: store the current time to a property, run a process, and determine the time that has elapsed. I’ve managed to write System.DateTime.Now to a property, but I don’t know how to do a simple datediff or construct a TimeSpan, so that I can get at what I’m looking for. I’d be utterly shamed if I had to resort to string comparisons or writing a custom task.

Options

The good thing is that he’s using MSBuild 4.0, which means he can use any combination of property functions and inline tasks to achieve all he wants from within the MSBuild code, without having to compile and version custom MSBuild task assemblies, which can become a pain in the ass to move forwards with.

When benchmarking from .NET, the best practice is to use the Stopwatch class in System.Diagnostics. Using DateTime functions is the natural but more inaccurate and naive way to benchmark. Eric Lippert of C# compiler fame did a good series on benchmarking mistakes, with Stopwatch mentioned in part 2.

In MSBuild, you’re limited to what classes you can use for property functions, so this means we have to resort to using inline tasks if we want to use Stopwatch. And because MSBuild is an imperative, XML-based language, we can’t really use Stopwatch in the normal way (get an instance, start and stop it, etc).

Because Rand (I’m guessing that’s his name) doesn’t seem to require much precision, using DateTime might be more than enough, and it can also make for some simpler code.

Solution 1: Using property functions and DateTime ticks

So here’s the first example, using property functions and DateTime:

Interestingly, the Stopwatch uses DateTime Ticks if it can’t use high precision time. So this is likely as good as we’re going to get using DateTime. If we run the project using MSBuild, Notepad should pop up. We can leave it open for a bit, then close it down, and see what measurement we got:

C:\>"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" Test.DateTime.proj
Microsoft (R) Build Engine version 12.0.30501.0
[Microsoft .NET Framework, version 4.0.30319.18408]
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 19/07/2014 5:07:25 p.m..
Project "C:\Projects\Test.DateTime.proj" on node 1 (default targets).
Test:
Starting ticks: 635413432457421728
notepad
Elapsed time: 00:00:02.4999296
Done Building Project "C:\Projects\Test.DateTime.proj" (default targets).

Build succeeded.
0 Warning(s)
0 Error(s)

Time Elapsed 00:00:02.51

OK, seems fair enough! The code is quite simple too, and could be fine if we’re not needing much precision.

Solution 2: Using inline tasks and Stopwatch

OK, so how can we use inline tasks to leverage the power of the .NET framework?

Phew! Ok this code would be smaller and simpler if you removed some of my comments, and Microsoft had made some of the key methods and properties in the Stopwatch class available.

So here’s how that looks:

C:\Projects>"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" Test.StopWatch.proj
Microsoft (R) Build Engine version 12.0.30501.0
[Microsoft .NET Framework, version 4.0.30319.18408]
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 19/07/2014 5:52:59 p.m..
Project "C:\Projects\Test.StopWatch.proj" on node 1 (default targets).
Test:
  Starting timestamp: 5443820462687
  notepad
  Elapsed time: 00:00:02.7861944
Done Building Project "C:\Projects\Test.StopWatch.proj" (default targets).


Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:02.87

Would it be possible some way to return a Stopwatch object that could be started and stopped, as you would do in C# code? Possibly! But I think that wouldn’t fit well with the way MSBuild works.

Links:

Gist containing these two code files. You should change the extension back to .proj, being MSBuild projects. I need to keep the extension to .xml so Gist renders the code as XML.

References:

Neat Reader: My Google Reader replacement

I already had the idea of writing my own feed reader on my list of things to do, so when news came out that Google were phasing Reader out, it naturally became my next hobby project.

Only spending a few hours here and there over several months, I’ve personally been using it since Google Reader died.

Only in the last few weeks has it been fit for human consumption (or even gotten a proper name).

Neat Reader has changed a lot already in the last few weeks, and there’s lots more to come.

Asychronously upload a file using jQuery to a Web API controller

Here’s the code for the HTML5 form:

<form id="upload">
    <div>
        <label for="myFile"></label>
        <div>
            <input type="file" id="myFile" />
        </div>
    </div>
    <button type="submit">Upload</button>
</form>

We need to use jQuery to handle when the user submits the upload, to make sure it gets handled asynchronously and posted to our Web API controller:

        // Hook into the form's submit event.
        $('#upload').submit(function () {

            // To keep things simple in this example, we'll
            // use the FormData XMLHttpRequest Level 2 object (which
            // requires modern browsers e.g. IE10+, Firefox 4+, Chrome 7+, Opera 12+ etc).
            var formData = new FormData();

            // We'll grab our file upload form element (there's only one, hence [0]).
            var opmlFile = $('#opmlFile')[0];

            // If this example we'll just grab the one file (and hope there's at least one).
            formData.append("opmlFile", opmlFile.files[0]);

            // Now we can send our upload!
            $.ajax({
                url: 'api/upload', // We'll send to our Web API UploadController
                data: formData, // Pass through our fancy form data

                // To prevent jQuery from trying to do clever things with our post which
                // will break our upload, we'll set the following to false
                cache: false,
                contentType: false,
                processData: false,

                // We're doing a post, obviously.
                type: 'POST',

                success: function () {
                    // Success!
                    alert('Woot!');
                }
            });

            // Returning false will prevent the event from
            // bubbling and re-posting the form (synchronously).
            return false;
        });


Ok and now in our controller, we can deal with the uploaded file(s):

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Web;
    using System.Web.Http;

    class UploadController : ApiController
    {
        public async void Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
            }

            // We'll store the uploaded files in an Uploads folder under the web app's App_Data special folder
            var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Uploads/"));

            // Once the files have been written out, we can then process them.
            await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                // Here we can iterate over each file that got uploaded.
                foreach (var fileData in t.Result.FileData)
                {
                    // Some good things to do are to check the MIME type before we do the processing, e.g. for XML:
                    if (fileData.Headers.ContentType.MediaType.Equals("text/xml", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // And this is how we can read the contents (note you would probably want to do this asychronously
                        // but let's try keep things simple for now).
                        string contents = File.ReadAllText(fileData.LocalFileName);
                    }
                }
            });
        }
    }

Uninstalling VMWare Workstation when Hyper-V is installed

Well, it was annoying enough that VMWare doesn’t launch on my machine when Hyper-V is installed. I’m skeptical that VMWare wouldn’t run if Hyper-V isn’t running at the same time, and this check just reeks of anti-competition.

Unfortunately for VMWare, that can work against them rather than encourage me to uninstall Hyper-V. That means I’m ditching them for now (mainly as Visual Studio integration with Hyper-V for things like Windows 8 and Windows Phone 8 development is good; not to mention, Hyper-V is built in and doesn’t cost extra).

I went to uninstall VMWare today but got this error:

image

Wow! Talk about pain in the ass.

Fortunately a quick search later, Jussi Palo has a simple solution, altering the installer’s lua script to skip this check:

Remove VMware Workstation or Player when Hyper-V is installed

And now I can uninstall.