Category Archives: Uncategorized

Improving the 2nd way in knockout-winjs’s two way data binding

In the original version of the knockout-winjs sample I wrote a couple of days ago (see this post)there is a basic implementation of writing back to an observable when a control changes value. The part that does this can be found in the init method of the generic binding handler and it looks like this:

// Add event handler that will kick off changes to the observable values
// For most controls this is the "change" event
if (eventName) {
    ko.utils.registerEventHandler(element, eventName, function changed(e) {
        // Iterate over the observable properties
        for (var property in value) {
            // Check to see if they exist
            if (value.hasOwnProperty(property)) {
                // Determine if that value is a writableObservable property
                if (ko.isWriteableObservable(value[property])) {
                    // Kickoff updates 
                    value[property](control[property]);
                }
            }
        }
    });
}

You might notice that if a control has a change event (the name is control dependent and not all controls need one but in this case that name is set in the eventName variable) then we register an event handler with the element and update ALL writable observables bound to a property of the control.

This is of course not how we want to update our observables. I would prefer to update just the one that needs updating. So I introduced another field in the definition for each control’s binding handler (I named it the changedProperty). Also I won’t bind to the element’s event but to the control’s event directly. This has one issue however if you also want to be able to bind to this event explicitly.

To accomplish this I changed the above code to the following:

// Add event handler that will kick off changes to the observable values
// For most controls this is the "change" event
if (eventName) {
    // If the change event is already bound we wrap the current handler with our update routine.
    var currentEventHandler = null;
    if (control[eventName]) {
        currentEventHandler = control[eventName];
    }

    control[eventName] = (eventInfo) => {
        if (value.hasOwnProperty(changedProperty)) {
            // Determine if that value is a writableObservable property
            if (ko.isWriteableObservable(value[changedProperty])) {
                // Kickoff updates 
                value[changedProperty](control[changedProperty]);
            }
        }

        if (currentEventHandler) {
            currentEventHandler(eventInfo);
        }
    };
}

I also found out that if we want to bind two events on a single control the current implementation of binding event has a bug. It read as follows:

// After the control is created we can bind the event handlers.
for (var property in value) {
    if (value.hasOwnProperty(property) && (property.toString().substr(0, 2) === "on")) {
        control[property] = (eventInfo) => {
            value[property].bind(viewModel, viewModel, eventInfo)();
        };
    }
}

It turns out however that the ‘property’ variable is changed by the time the actual event is called. So we can’t really use it in the event. I fixed it in the following fashion:

// After the control is created we can bind the event handlers.
for (var property in value) {
    if (value.hasOwnProperty(property) && (property.toString().substr(0, 2) === "on")) {
        control[property] = (eventInfo) => {
            // Must use eventInfo.type here because 'property' will
            // be changed by the time the actual event is fired.
            value["on" + eventInfo.type].bind(viewModel, viewModel, eventInfo)();
        };
    }
}

To watch all this in action download this expanded example: ToDoApp4

WInJS Navigation and KnockoutJS, expanding the to-do sample

I was planning to expand my to-do sample with some more WinJS controls to weed out any bugs that might still be present in the knockout-winjs integration library. After thinking of some controls I would like to test out I figured I would need more than just the single page currently in the sample app. And that of course means some way to navigate between them.

WinJS comes with a navigation stack built-in, and it would be ridiculous not to use that. However a “simple” sample I found online (this one) turned out less simple than I expected. After some digging through the code however I found that for my simple purpose I could strip most of the plumbing and get something actually simple. So first we will set up some plumbing and then add a to-do item edit page.

I’m building on the outcome of my last blog post: ToDoApp2

Setting up the navigation plumbing

A few changes to the way we initialize the application:

function onDeviceReady() {
  // Handle the Cordova pause and resume events
  document.addEventListener('pause', onPause, false);
  document.addEventListener('resume', onResume, false);

  ConcreteCoding.KnockoutToWinJS.addBindings(ConcreteCoding.KnockoutToWinJS.controls);

  // When we navigate to a page, this event listener will render it, and apply our knockoutjs bindings.
  WinJS.Navigation.addEventListener("navigated", (eventObject) => {
    var url = eventObject.detail.location;
    var host = document.getElementById("pageContent");

    // Unload the previous page if needed.
    if (host.winControl && host.winControl.unload) {
      host.winControl.unload();
    }
    WinJS.Utilities.empty(host);

    eventObject.detail.setPromise(WinJS.UI.Pages.render(url, host, eventObject.detail.state).then(function () {
      ko.applyBindings(eventObject.detail.state, host);
    }));
  });

  WinJS.UI.processAll().then(() => {
    // Navigate to the initial page and supply the original view model as the state parameter.
    return WinJS.Navigation.navigate("/html/ToDoView.html", new ToDoViewModel());
  });            
}

And we also have to extract the page from the index.html into its own ToDoView.html.

Index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>ToDoApp</title>

    <link href="WinJS/css/ui-light.css" rel="stylesheet" />
    <script src="WinJS/js/WinJS.js"></script>

    <link href="css/index.css" rel="stylesheet" />

    <script src="scripts/platformOverrides.js"></script>
    <script src="scripts/knockout-3.3.0.debug.js"></script>
    <script src="scripts/knockout-winjs.js"></script>
    <script src="scripts/index.js"></script>

    <script src="cordova.js"></script>    
</head>
<body>
    <div id="pageContent"></div>
</body>
</html>

ToDoView.html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <input type="text" data-bind="textInput: newDescription" />
    <br />
    <div data-bind="foreach: toDoItems">
        <input type="checkbox" data-bind="checked: done" />
        <span data-bind="text: description"></span>
        <a href="#" data-bind="click: $parent.removeItem.bind($parent, $data)">x</a>
        <br />
    </div>

    <div data-bind="winAppBar: {placement: 'bottom'}">
        <button data-bind="winAppBarCommand: {label: 'Add', type: 'button', icon:'add', onclick: addNewItem }"></button>
    </div>    
</body>
</html>

Adding the new page with the navigation button

So ofcourse we create a new file containing the HTML for the new page. Very simple but using the WinJS BackButton control, because we are using the WinJS navigation stack. I also changed some properties in the ToDoItem class so we have a bit more to fill the page with.

The new HTML page:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button data-bind="winBackButton"></button>
    <h1 class="win-type-xx-large">Edit item</h1>
    <br />
    <label>Title</label>
    <br />
    <input type="text" data-bind="textInput: toDoItem().title" />
    <br />
    <label>Done?</label>
    <input type="checkbox" data-bind="checked: toDoItem().done" />
    <br />
    <label>Description</label>
    <br />
    <textarea data-bind="textInput: toDoItem().description"></textarea>
</body>
</html>

The new view model class for the above view, and the new ToDoItem class:

class EditToDoItemViewModel {
    toDoItem: KnockoutObservable<ToDoItem>;

    constructor(item: ToDoItem) {
        this.toDoItem = ko.observable(item);
    }
}

class ToDoItem {
    title: KnockoutObservable<string>;
    description: KnockoutObservable<string>;
    done: KnockoutObservable<boolean>;

    constructor(title: string) {
        this.title = ko.observable(title);
        this.description = ko.observable("");
        this.done = ko.observable(false);
    }
}

Finally we add an editItem method that handles navigating to our new page, we place it in the ToDoViewModel class. This method should also be data bound on a button or link for each to-do item in the main page, but I’ll leave that as an exercise for the reader (or you can just download the complete project at the end of the post):

editItem(item: ToDoItem) {
    WinJS.Navigation.navigate("/html/EditToDoItemView.html", new EditToDoItemViewModel(item));
}

Now just run it, and you should be able to add items, edit them in a separate edit page, and navigate back to the original page. The complete project can be found here: ToDoApp3

Cordova + KnockoutJS + WinJS example

After my post yesterday about making KnockoutJS and WinJS work together I figured it would be a good idea to make a nice sample application to show everything works. And why not user Cordova in the process.

So here is a very simple ToDo sample I created for a knowledge sharing session at the office. Which I will ‘enhance’ with WinJS stuff: ToDoApp1

It is very simple, and it doesn’t even save your to-do items but it shows off some knockout JS stuff, and that was the point.

What I did was change the Add button to a button on a WinJS AppBar and bind the onclick handler to the exact same method that was used before. Apart from adding the WinJS nuget package, the WinJS typescript definition files and the knockout-winjs library from my previous post to the project (and referenced in the HTML file), I only changed a few simple things:

Added this piece of HTML at the end of the body:

<div data-bind="winAppBar: {placement: 'bottom'}">
    <button data-bind="winAppBarCommand: {label: 'Add', type: 'button', icon:'add', onclick: addNewItem }"></button>
</div>

Changed the onDeviceReady method to register the WinJS control binding handlers and add the WinJS.UI.processAll method to start the WinJS magic:

function onDeviceReady() {
  // Handle the Cordova pause and resume events
  document.addEventListener('pause', onPause, false);
  document.addEventListener('resume', onResume, false);

  ConcreteCoding.KnockoutToWinJS.addBindings(ConcreteCoding.KnockoutToWinJS.controls);

  WinJS.UI.processAll().then(() => {
    ko.applyBindings(new ToDoViewModel());
  });            
}

I also added a little padding to the body in CSS because the WinJS style sheets put everything frighteningly close to the edges of the screen. But I’ll leave that to your imagination. Or you can download the entire project from here: ToDoApp2

I’ll try to add some more WinJS controls to this little sample to test them out (and if needed fix the knockout-winjs library in the process). So keep an eye out.

Find all string literals in C# code files, but not the ones in comments

When trying to find string literals to translate in our rather large 59 project solution I found out it is not that easy to search for string literals in your code when you use the default code comments format.

You see, there is a default regular expression in Visual Studio which lets you search for string literals (eg. search for all strings that are between quotes). This regular expression is:

((".+?")|('.+?'))

This regular expression however will also find entries in code comments like this:

/// <summary>
/// Begins to invoke the action in the current controller context.
/// </summary>
/// <param name="callback">The callback.</param>
/// <param name="state">The state.</param>
/// <returns>
/// Returns an IAsyncController instance.
/// </returns>

It took me and a co-worker some time to come up with a regular expression to filter these out. Our result was:

(?=(^((?!///).)*$)).*((".+?")|('.+?')).*

I’m not entirely sure myself how it works. But it is based on the fact that we only want to know the entire line which contains the string literal (and not specifically only the string literal). So we match all lines that don’t start with whitespace followed by ///, then in those lines match the original regex.

OAuth configuration URL’s and general information

Last couple of weeks I have been working on a new implementation of the login and security stuff in our new MVC application. We wanted to use 3 external OAuth Authentication providers (LinkedIn, Microsoft and Google). I noticed I had to look up application configuration links from samples and tutorials on the internet, since they were hard to find when actually logged on as a user for each of these services. So for easy reference, here are the URLs:

Microsoft: https://account.live.com/developers/applications/index
Google: https://console.developers.google.com/project
LinkedIn: https://www.linkedin.com/secure/developer

Another thing of note are the strange things you request from a user’s Google account when using OAuth. See for instance these stackoverflow questions: http://stackoverflow.com/questions/18329629/scope-to-get-email-address-alone
http://stackoverflow.com/questions/24410179/is-there-a-way-to-only-get-a-users-email-address-with-googles-oauth2-impleme

Enabling TypeScript builds for library projects in Visual Studio.

If you are creating a modular web application where all content files and script files are embedded in library projects, migrating from JavaScript to TypeScript will need some extra work. As I already discussed in a previous post, debugging TypeScript might be a bit tricky, and I already mentioned there that we have our TypeScript in library assemblies.

I did not mention how we enabled TypeScript build support for these assemblies (since it will not work out of the box for this project type). So here is a small instruction manual:

– Unload the project you want to add TypeScript support to.
– Open the project file in the XML editor.
– Add the following at the end of the file (but before the Project end tag):

<Import Project="$(MSBuildExtensionsPath32)MicrosoftVisualStudiov12.0TypeScriptMicrosoft.TypeScript.targets" />

– Save and close the project file, then load the project again.

The build will now work. However it will likely have problems with overwriting the generated .js files. You probably have those file in source control because you want them added as an Embedded Resource to your output assembly. And if they are in source control they will be read-only by default.

To fix this you can add a pre-build event to your project that clears the read-only attribute (and since we also have the .js.map files are Embedded Resources we fix these up too):

attrib -r /s "$(ProjectDir)*.js"
attrib -r /s "$(ProjectDir)*.js.map"

It is probably possible to use the tf command line tool to actually check these files out instead of changing just the read-only stamps, but the above works fine for us.

Debugging typescript when they are built into a class library.

We have created a modular MVC website where each module is built in a class library. There are plenty of examples on the web on how to do this. However when we decided to convert our Javascript files to TypeScript we ran into a few issues regarding debugging.

If you put a breakpoint into a TypeScript file in a regular project, Visual Studio will automatically pick it up (using the running javascript, and the mapping file generated by typescript). If you are using a custom VirtualPathProvider to retrieve the js files from resources in a class library things get a bit harder to debug.

To accomodate this scenario there are a few things we must do:

– Just as the javascript files we need to mark the js.map files as embedded resource too.
– Just as the javascript files we need to mark the TypeScript files as embedded resource too.
– The above file types must be retrieved via the custom VirtualPathProvider.
– Because we need to mark the TypeScript files as embedded resources, and because file can only have one build action, we also need a good way to compile all typescript files.

The first two points are obviously the easy parts, just select all .ts and .js.map files in your class library project, and set the build action to Embedded Resource.

|To have the custom VirtualPathProvider pick up those file types, you will have to change the web.config file of your MVC host project. Something like the following line should already be present:

<add verb="GET" path="*.js" name="Static for js" type="System.Web.StaticFileHandler" />

Add the following two lines just below that:

<add verb="GET" path="*.ts" name="Static for ts" type="System.Web.StaticFileHandler" />
<add verb="GET" path="*.js.map" name="Static for js.map" type="System.Web.StaticFileHandler" />

Now for the final bit. Since we set the TypeScript files to EmbeddedResource they won’t compile to a javascript file anymore when you build the project. To counteract this, add a typescript file to your project that just references all your other typescript files like so:

/// <reference path="My1stFile.ts" />
/// <reference path="My2ndFile.ts" />

Keep this file set to the regular build action. And on build, this file, and all files it references will get built.

Signing executables with authenticode certificate without the need for CAPICOM.

A couple of years ago the recommended way of signing executables with an authenticode certificate was using the SignTool applications that is distributed with the Windows SDK. With the release of x64 operating systems (especially Windows 7 x64) people started seeing that tool fail since it depends on CAPICOM, and this is only available in 32-bits (and it is also not supported anymore).

I already discussed this issue in a previous blogpost. But i wanted a permanent solution because it gets annoying redirecting my co-workers to a tool that is unsupported and doesn’t work out of the box. I decided to do some research on the subject and came up with a tool that does what we need it to do, but is not a full replacement for Microsoft’s own SignTool.

I could not have done this without this exelent blog post.

I started with refactoring the p/invoke code to C#:

// #define CRYPTUI_WIZ_NO_UI     1
public const int CRYPTUI_WIZ_NO_UI = 1;

// #define CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE     0x01
public const int CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE = 1;

// #define CRYPTUI_WIZ_DIGITAL_SIGN_CERT                    0x01
public const int CRYPTUI_WIZ_DIGITAL_SIGN_CERT = 1;

// #define CRYPTUI_WIZ_DIGITAL_SIGN_COMMERCIAL  0x0001
public const int CRYPTUI_WIZ_DIGITAL_SIGN_COMMERCIAL = 1;

// typedef struct _CRYPTUI_WIZ_DIGITAL_SIGN_INFO {  
//   DWORD dwSize;  
//   DWORD dwSubjectChoice;  
//   union {    
//       LPCWSTR pwszFileName;    
//       PCCRYPTUI_WIZ_DIGITAL_SIGN_BLOB_INFO pSignBlobInfo;  
//   };  
//   DWORD dwSigningCertChoice;  
//   union {    
//       PCCERT_CONTEXT pSigningCertContext;    
//       PCCRYPTUI_WIZ_DIGITAL_SIGN_STORE_INFO pSigningCertStore;    
//       PCCRYPTUI_WIZ_DIGITAL_SIGN_CERT_PVK_INFO pSigningCertPvkInfo;  
//   };  
//   LPCWSTR pwszTimestampURL;  
//   DWORD dwAdditionalCertChoice;  
//   PCCRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO pSignExtInfo;
// } CRYPTUI_WIZ_DIGITAL_SIGN_INFO;
[StructLayout(LayoutKind.Sequential)]
public struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO
{
    public int dwSize;
    public int dwSubjectChoice;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pwszFileName;
    public int dwSigningCertChoice;
    public IntPtr pSigningCertContext;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pwszTimestampURL;
    public int dwAdditionalCertChoice;
    public IntPtr pSignExtInfo;
}

//typedef struct _CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO {
//  DWORD             dwSize;
//  DWORD             dwAttrFlags;
//  LPCWSTR           pwszDescription;
//  LPCWSTR           pwszMoreInfoLocation;
//  LPCSTR            pszHashAlg;
//  LPCWSTR           pwszSigningCertDisplayString;
//  HCERTSTORE        hAdditionalCertStore;
//  PCRYPT_ATTRIBUTES psAuthenticated;
//  PCRYPT_ATTRIBUTES psUnauthenticated;
//} CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO, *PCRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO;
[StructLayout(LayoutKind.Sequential)]
public struct CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO
{
    public int dwSize;
    public int dwAttrFlags;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pwszDescription;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pwszMoreInfoLocation;
    [MarshalAs(UnmanagedType.LPStr)]
    public string pszHashAlg;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pwszSigningCertDisplayString;
    public IntPtr hAdditionalCertStore;
    public IntPtr psAuthenticated;
    public IntPtr psUnauthenticated;
}

// typedef struct _CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT {  
//      DWORD dwSize;  
//      DWORD cbBlob;  
//      BYTE* pbBlob;
// } CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT;
[StructLayout(LayoutKind.Sequential)]
public struct CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT
{
    public int dwSize;
    public int cbBlob;
    public IntPtr pbBlob;
}

// BOOL WINAPI CryptUIWizDigitalSign(
//      DWORD dwFlags,
//      HWND hwndParent,
//      LPCWSTR pwszWizardTitle,
//      PCCRYPTUI_WIZ_DIGITAL_SIGN_INFO pDigitalSignInfo,
//      PCCRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT* ppSignContext
// );
[DllImport("Cryptui.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptUIWizDigitalSign(
    int dwFlags,
    IntPtr hwndParent,
    [MarshalAs(UnmanagedType.LPWStr)]
    string pwszWizardTitle,
    ref CRYPTUI_WIZ_DIGITAL_SIGN_INFO pDigitalSignInfo,
    ref IntPtr ppSignContext);

// BOOL WINAPI CryptUIWizFreeDigitalSignContext(
//   PCCRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT pSignContext
// );
[DllImport("Cryptui.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CryptUIWizFreeDigitalSignContext(IntPtr pSignContext);

I added the CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO structure as well. I didn’t get this part to work, but I kept the definition for future reference.

With the P/Invoke definitions done actually signing a file was remarkably simple (don’t mind the CommandLineArguments class, it is defined in the sample download):

var cert = new X509Certificate2(cla.Certificate, cla.Password);
var digitalSignInfo = new CRYPTUI_WIZ_DIGITAL_SIGN_INFO();
digitalSignInfo.dwSize = Marshal.SizeOf(digitalSignInfo);
digitalSignInfo.dwSubjectChoice = CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE;
digitalSignInfo.pwszFileName = cla.FileToSign;
digitalSignInfo.dwSigningCertChoice = CRYPTUI_WIZ_DIGITAL_SIGN_CERT;
digitalSignInfo.pSigningCertContext = cert.Handle;
digitalSignInfo.pwszTimestampURL = cla.TimestampUrl;
digitalSignInfo.dwAdditionalCertChoice = 0;
digitalSignInfo.pSignExtInfo =IntPtr.Zero;

IntPtr pSignContext = IntPtr.Zero;
if (!CryptUIWizDigitalSign(CRYPTUI_WIZ_NO_UI, IntPtr.Zero, string.Empty, ref digitalSignInfo, ref pSignContext))
{
    throw new Win32Exception(Marshal.GetLastWin32Error(), "CryptUIWizDigitalSign");
}

if (!CryptUIWizFreeDigitalSignContext(pSignContext))
    throw new Win32Exception(Marshal.GetLastWin32Error(), "CryptUIWizFreeDigitalSignContext");

This is all there is to it. I have included a zipped sample of the application which includes a bit more plumbing (like some crude command line arguments handling). And a failed attempt to also use the extended info class (that would be needed for the original SignTool’s /d and /du options).

Download the sample here: SignToolNet

Preparing for 70-496: Administering Visual Studio Team Foundation Server 2012

I am finally trying to make some time to study for and pass this exam. I thought I’d write down my progress and study plan in case other people find it interesting. First of all you should head to the Microsoft site for this exam:

http://www.microsoft.com/learning/en-us/exam-70-496.aspx

Since I am a self-paced training kinda guy I’ll start with the Jump Start course (which is free). I already know quiet a lot about TFS so this probably won’t be much of a challenge. I also don’t think it will be enough to pass the exam.

http://www.microsoftvirtualacademy.com/training-courses/administering-visual-studio-tfs-2012-exam-496-jump-start

After this I am going to go through the measures skills categories one at a time. I could download Brian Keller’s excellent TFS VM’s (http://blogs.msdn.com/b/briankel/archive/2013/08/02/visual-studio-2013-application-lifecycle-management-virtual-machine-and-hands-on-labs-demo-scripts.aspx), but since the first category of measures skills is “Installation and Configuration” I think I’ll create a VM myself.

More on that later.

ClosedXml exception when opening an Excel sheet.

We handle may Excel sheets in our automated systems and we use the great ClosedXml opensource library (https://closedxml.codeplex.com/). However today we stumbled upon a sheet that crashed one of our applications.

InvalidOperationException: Sequence contains no matching elements.

After downloading the ClosedXml source I found out the sheet had a rogue comment. Somehow this comment did not have the shapetype that ClosedXml expected. After removing it everything ran smoothly again.

It seems I am, for the first time, going to make a bugfix contribution to an opensource project….