Posts

Programming Interview Questions: Recursion

In this screecast we solve two commonly asked interview questions; faculty and traversing binary trees.

Screencast

What’s recursion?

A recursive function is simply a function that repeatedly calls itself and the trick is to realize when to stop calling ourselves to avoid infinite loops that result in stack overflows.

If the interviewers ask you to write down an algoritm that gives you the n:th fibonacci number, calculate faculty or traverse a binary tree they probably want you to provide both an iterative and recursive solution. We don’t address fibonacci in the screencast, but the formula for the n:th number is simply the sum of the previous two, i.e.

f(n) = f(n-1) + f(n-2)

Is this a good interview question?

Here’s the recursive methods I developed during the screencast to calculate faculty and to sum the value of all the nodes in a binary tree:

    private static int sum(Node node) {
        if (node == null) return 0;
        return node.Value + sum(node.Left) + sum(node.Right);
    }
    
    private static long faculty(int n) {
        if (n == 1) return 1;
        return n * faculty(n - 1);
    }

As you can see the answers are usually very simple but it’s not unusual to see candidates try to make things more complicated than they need to be. Just keep it simple.

Interviewers tend to ask these kind of questions even if functional programming is a very small part of the day to day work. It’s always good to be prepared by training on some simple problems similar to the ones covered here. After one or two exercises you’ll get the hang of it and it won’t be a problem if they throw these kind of questions at you during the interview.

And as always, until next time, have a nice day!

Angular 2 Material First Look

In this weeks screencast we take a first look at the material components for angular2 that just released their first alpaha, code at https://github.com/ajtowf/ng2_play. We’ll integrate the button and checkbox component into our ng2play repo, the idea is to fully replace bootstrap down the road.

Screencast

Components

There will be breaking changes between alpha releases, first release of angular2-material includes the following components:

To learn more about material deisgn and components for angular, make sure to check out my pluralsight course Angular Material Fundamentals.

Until next time, have a nice day folks!

Connection leaks when using async/await with Transactions in WCF

If you’re getting “The current TransactionScope is already complete” from service calls that don’t even consume transactions, you’ll probably want to read/see this.

Screencast and Code

The code can be found on github, https://github.com/ajtowf/dist_transactions_lab, one change I did since the recording is that we don’t create the nhibernate factory with each call, we now use a singleton SessionManager instead. Also we’re adding the convention to the factory to never load lazy so that our Item entity don’t need to have virtual properties, which makes it easier to switch between OR-mapper implementations.

Leaking Connections

In a fairly complex distributed enterprise system we were getting some strange The current TransactionScope is already complete errors. We used transactions frequently but we saw this on calls that wasn’t even supposed to run within an transaction.

After trying almost everything we got a hint from a nhibernate analyzer product that we shouldn’t consume a nhibernate session from multiple threads since it’s not thread safe.

If you use await, that’s exactly what happens. Turns out entity framework has the same problem.

The following code in your service will leak connections if the awaited method or service call uses a database connection with EntityFramework or NHibernate.

    [OperationBehavior(TransactionScopeRequired = true)]
    public async Task CallAsync()
    {
        using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            await _service.WriteAsync();
            ts.Complete();
        }
    }

Why Tasks in the Service Contract at all?

The lone reason for our service contracts being task based is that we use the same interface to implement our client-side proxies, which is neat, but the service doesn’t need use await because of that. This will work for instance:

    [OperationBehavior(TransactionScopeRequired = true)]
    public Task CallAsync()
    {
        // Do synchronous stuff
        return Task.FromResult(true);
    }

or (don’t like this one though)

    [OperationBehavior(TransactionScopeRequired = true)]
    public Task CallAsync()
    {
        // Remember to copy the OperationContext and TranactionScope to inner Task.
        return Task.Run(() =>
        {
            // Do synchronous stuff
        });          
    }

Oh, you don’t want to return a Task if you’re not doing anything async? Do this then:

    [OperationBehavior(TransactionScopeRequired = true)]
    public async Task CallAsync()
    {
        // Do synchronous stuff
    }

What about the warning? Turn it off with #pragma.

     [OperationBehavior(TransactionScopeRequired = true)]
#pragma warning disable 1998
     public async Task CallAsync()
#pragma warning restore 1998
        {            
            // Do synchronous stuff        
        }

You’ll probably want to wrap the entire service class with that pragma disable.

Solution

The main take away here is to simply not use async/await in your service code if you’re awaiting methods or service calls that will use database connections. The following refactoring solves the problem:

    [OperationBehavior(TransactionScopeRequired = true)]
    public Task CallAsync()
    {
        _service.WriteAsync().Wait();
        return Task.FromResult(true);
    }

As always, until next time, have a nice day!

Distributed Transactions in WCF with async and await

TL;DR?

See my screencast explaining problem instead:

Problem

When flowing a transaction from a client to a service Transaction.Current becomes null after awaiting a service to service call.

Unless of course you create a new TransactionScope in your service method as follows:

    [OperationBehavior(TransactionScopeRequired = true)]
    public async Task CallAsync()
    {
        using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            await _service.WriteAsync();
            await _service.WriteAsync();            
            scope.Complete();
        }
    }

Problem UPDATE

It doesn’t even have to be a service to service call, an await to a local async method also nulls Transaction.Current. To clearify with an example

    [OperationBehavior(TransactionScopeRequired = true)]
    public async Task CallAsync()
    {
        await WriteAsync();
        // Transaction.Current is now null
        await WriteAsync();                     
    }

Why TransactionScopeAsyncFlowOption isn’t enabled by default I don’t know, but I don’t like to repeat myself so I figured I’d always create an inner transactionscope with that option using a custom behavior.

Attempted Solution

I created a Message Inspector, implementing IDispatchMessageInspector and attached it as a service behavior, code executes and everyting no problem there, but it doesn’t have the same effect as declaring the transactionscope in the service method.

    public class TransactionScopeMessageInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            var transactionMessage = (TransactionMessageProperty)OperationContext.Current.IncomingMessageProperties["TransactionMessageProperty"];
            var scope = new TransactionScope(transactionMessage.Transaction, TransactionScopeAsyncFlowOption.Enabled);            
            return scope;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            var transaction = correlationState as TransactionScope;
            if (transaction != null)
            {
                transaction.Complete();
                transaction.Dispose();
            }
        }
    }

by looking at the identifiers when debugging I can see that it in fact is the same transaction in the message inspector as in the service but after the first call, i.e.

    await _service_WriteAsync();

Transaction.Current becomes null. Same thing if not getting the current transaction from OperationContext.Current in the message inspector as well so it’s unlikely that is the problem.

Is it possible to create a TransactionScope in a Custom WCF Service Behavior?

Is it even possible to accomplish this? It appears like the only way is to declare a TransactionScope in the service method, that is:

    public async Task CallAsync()
    {
        var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
        await _service.WriteAsync();
        await _service.WriteAsync();            
        scope.Complete();
    }

with the following service contract it’s obvious that we get an exception on the second service call if transaction.current became null inbetween

    [OperationContract, TransactionFlow(TransactionFlowOption.Mandatory)]
    Task WriteAsync();

Got a link to a book posing the exact same question on my stackoverflow question. The conclusion is basically that it can’t be done in a clean way. Quoting the book:

We consider the lack of parity with standard WCF behavior introduces by async service operations a design flaw of WCF…

And then a far from ideal / insane solution is proposed.

Accepted Solution for now

It seems like the only way to make this work is to create an inner transaction, if you have a better solution feel free to comment or contact me or why not answer my stackoverflow question http://stackoverflow.com/questions/34767978.

Until next time, have an excellent day!

Introduction to ASP.NET 5 (Part I) – Frameworks, DNVM, DNX and DNU

This is the first part of an introduction to ASP.NET 5 series. We start easy by taking a look at the different runtime versions and the dnvm, dnx and dnu commands. Plan to release a new part/lesson every week, check out the entire playlist here.

Cheers!

Build automation for Angular 2 and TypeScript with Gulp

In this screencast we focus on creating a smooth workflow, we’ll build, run code analysis and serve the code, all with gulp. We also learn how to keep the browser in sync with the code. Let me know what you guys think.


Source code @ https://github.com/ajtowf/ng2_play/

Setup npm and gulp

Start off by installing gulp globally and then run npm init to create a packages.json file. Then install the gulp modules we’ll use locally.

npm install -g gulp
npm init // answer the questions, default values are OK
npm install gulp gulp-typescript gulp-sourcemaps gulp-tslint --save-dev
npm install browser-sync superstatic --save-dev // for serving the app

Create the following files in the root directory: gulpfile.js, gulp.config.js and tslint.json

Serve the application

Now that we have everything setup, we’ll get our code analyzed, compiled, served and updated as we save changes to our files just by typing:

gulp

Pretty neat, right? I hope you guys enjoyed the screencast, until next time, have an excellent day!

Aurelia Validation

In this screencast we implement validation in our simple todo application that we created here, it’s basically the same exercise as we did in the angular 2 forms screencast, make sure to check it out if you missed it. The idea is to compare aurelia with angular2, imho aurelia is winning the race right now, let me know what you think.

Steps to get validation with Aurelia

If you’re new to aurelia, make sure you check out my first screencast on aurelia here, before you follow these steps on how to implement validation.

Install the validation plugin by executing the following command via JSPM:

jspm install aurelia-validation

 
And change the aurelia-app attribute to aurelia-app=”main”.

<body aurelia-app="main">

 
The aurelia framework will now bootstrap the application by looking for your main.js file and executing the exported configure method. Add a new main.js file with the following contents:

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-validation'); 

  aurelia.start().then(a => a.setRoot('app', document.body)); 
}

 
Once you’ve loaded the plugin, validation is set up using the fluent validation API in the view model (borrowed from http://aurelia.io/validation/#/).

import {Validation} from 'aurelia-validation';
export class Person {
  static inject() { return [Validation];}
  constructor(validation) {
    this.firstName = 'John';
    this.validation = validation.on(this)
      .ensure('firstName')
        .isNotEmpty()
        .hasLengthBetween(3,10);
  }
}

 
With the following template:

<template>
  <form role="form" validate.bind="validation">
    <div class="form-group">
      <label>First Name</label>
      <input type="text" value.bind="firstName" class="form-control" >
    </div>
  </form>
</template>

 

That’s it, you’re done! You don’t need to mess around with annotations and keep track of what needs to be passed as viewBindings or directives to the template as seen in angular 2 forms. Honestly, it just works!

Conclusion

For the moment Aurelia feels a lot more finished and easier to use. I was struggling with getting angular2 forms up and running and it’s poorly documented, whereas I could just follow the documentation on the aurelia validation github repo and be up and running within minutes. Let me know what you think in the comments, it’s OK to disagree! ;-)

Anyways, I hope you guys enjoyed the screencast, until next time, have an excellent day!
 

Source code as always at @ https://github.com/ajtowf/ng2_overview/

Pluralsight Author

My last couple of screencasts, including the last blog entry was about angularjs 2.0 and aurelia. That’s because I decided to audition for producing courses for pluralsight, and guess what — I’m now an approved pluralsight author. If you don’t know what pluralsight is, here’s a definition by google (authored by themselves?):

Pluralsight is the leading online provider of tech and creative training for professionals.

The audition

To become an author for pluralsight, you need to do an audition. There’s a hard time limit on 10 minutes and you should cover a topic completely in this time, having an introduction, main part and a summary. You can obviously do some assumptions about the viewers’ prior knowledge since 10 minutes really isn’t that much of time. I did a module on bootstrapping the application with angularjs 2.0, as if it was a part of a larger course. You can see it here below, let me know what you guys think!

Time spent

I spent a day familiarizing myself with the framework and producing an example, you’d save some time if you pick a topic you already know of course. Then another day editing and revising the video, bear in mind I hadn’t used the video editing software, camtasia, before. All and all, including emailing back and forth with my acquisition editor I spent roughly two work days, 8 hours each. Was it worth it? Well, we’ll just have to wait and see, so far it hasn’t been too much work in my opinion.

I really look forward to producing a course in the next couple of months. Until next time, have a nice day!

AngularJS 2.0 Forms & Validation

In this screen cast I familiarized myself with angular 2 forms by extending the todo application that we created in our previous screencast, check out the screencast below and let me know what you think.

Common misstakes

I’ve seen many questions on stackoverflow where people even struggle to setup the most basic example. The angular team are lagging behind with sample code on angular.io and the typescript definition file on definitely typed is a mess.

At the time of writing the current alpha release is up to 34, the highlighted lines are essential to get right be able to use angular 2 forms.

import {Component, View, bootstrap} from 'angular2/angular2';
import {formDirectives, FormBuilder, ControlGroup, Control} from 'angular2/angular2';
import {Validators} from 'angular2/angular2';

@Component({
  selector: 'app',
  viewBindings: [FormBuilder]
})
@View({
  templateUrl: 'app.html', 
  directives: [formDirectives]
})
class AppComponent {
  constructor(fb: FormBuilder) {    
    // use the formbuilder here...
  }
}

 

  1. Don’t try to import from angular2/forms even if their documentation says so if you’re using the definition file from definitely typed, it’s all under angular2/angular2.
  2. Make sure you pass the FormBuilder to a property named viewBindings to the Component-annotation and nothing else, this keeps changing name so it’s easy to get wrong.
  3. If dependency injection to the constructor fails, you are probably doing the first point wrong.

Completing the angular.d.ts file

The angular team seems to be lazy on updating the definitely typed repo definition file. If you’re playing around with forms, you probably want to mark a field as required. To be able to do so by following some samples, you’ll need to add a static property to the Validators class in the definition file angular2.d.ts.

class Validators {
  static required: any;
}

 

Conclusion

I can’t shake the feeling that they are over complicating things, the syntax is very verbose and stuff is happening behind the scenes that always don’t seem that intuitive. The code is changing a lot from one version to another, it feels a bit premature to see all the ng-conf sessions talking about angular 2. It’s obvious that the community is frustrated (from reading blogs and stack overflow questions) over that it’s quite hard to get a simple sample up and running even though I personally don’t share that feeling.

Anyways, I hope you guys enjoyed the screencast, until next time, have a nice day as always!

 

Source code as always at @ https://github.com/ajtowf/ng2_overview/tree/ng2

Aurelia VS AngularJS 2.0

Angular

I spend a couple of hours familiarizing myself with angular 2 for a pluralsight audition which resulted in the following screencast.

Aurelia

I then got an interesting comment that aurelia is the client side app framework to use. I try to be agnostic about the frameworks, libs and the tools that I use, so spent a couple of hours familiarizing myself with aurelia as well which resulted in the following screencast where I port the angular app in a matter of minutes.

Conclussions

Angular is at the time I’m writing this post in alpha and it’s changing a lot, which is really frustrating since something always seems to be broken and documentation/examples are inaccurate even on their own site. It’s hard to keep track of if it’s *for, *ngfor, *ng-for or something completely different from one build to the other.

I like that web components are the mainstay and it unifies react.js, angular.js and polymer. One big thumbs up to that $scope is gone, but also a big thumbs down for that two-way data-bindings is gone. Kind of a deal breaker for me. Angular has teamed up with the typescript team and they are pushing it which definitely is a good thing but not angular specific ergo no credit for that.

Learning curve was about the same for both frameworks, both are using the ES6 module loading system and depending on runtime transpilation to ES5 for now. What tips the scale towards Aurelia for me is that it’s cleaner, supports two-way data-bindings and that it’s all about conventions over configuration/code. That’s my opinion after a first look at both frameworks, watch the screencasts and judge for yourself.

As I mentioned I try to stay agnostic about the frameworks, libs and tools that I use, but I’ll definitely give aurelia a try for my next web project and try to forget that there is an IDE named VS Code out there. *BOOM* ;-)

EDIT: About 2-way data binding

It’s ridiculous how many emails I’ve received about this, but really, there is no 2-way data binding in angular 2. Do not confuse the square-bracket-parenthesis-syntax [(ng-model)] with two-way bindings — it one-way binds to the property with square brackets and listens for events with parenthesis. They obviously realized that typing


is cumbersome so they introduced a new directive called ng-model


So now you have very angular specific code in your view templates instead of just two-way binding to the DOM property. I refactor the code to bind to the checked property from this screencast in the beginning of next one here.

I like angular

Don’t get me wrong, I like angular and I will use angular 2, but I don’t mindlessly love everything they do like some fan boy. Stay open minded people and don’t be afraid to express your opinion, it’s just yet another framework. You don’t need to love everything the angular team produces.

By the way, make sure to check out my latest screencast on angular 2 forms!

 

Until next time, have a nice day!  

 

Source code as always at @ https://github.com/ajtowf

Links: aurelia.io angular.io

Keywords : Visual Studio Code, HTML5, JavaScript, AngularJS 2.0, Aurelia, TypeScript