Posts

Navigate Code Efficiently with JetBrains ReSharper in VisualStudio

Started a new series on efficiency in visual studio with resharper, here’s the first part that’s on navigating the code. What’s your favorite navigation shortcut?

Shortcuts used in video:

  • Ctrl + Shift + T: Find everything
  • Ctrl + T: Find files
  • Ctrl + F12: Go to Implementations
  • Shift + F12: Find Usages
  • Ctrl + Alt + PgUp/PgDn: Navigate to next/prev usage
  • Alt + Shift + L: Find file in Solution Explorer

Hope you enjoy the video and make sure to subscribe if you do, cheers!

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!

First pluralsight course live

ps_course
I’m proud to announce that my first pluralsight course now is live, make sure to check it out:

Authenticating Your Angular SPA with ASP.NET Web API and Auth0

Modules

The course is split into the following three modules.

An Introduction

Course introduction with brief overview of Auth0, where we also register for a free developer account.

Building the Back-end API

In this module we create the back-end and secure it with Auth0, we also test our API by making secure calls with postman.

Building the Front-end SPA

In this module we create the front-end using AngularJS to communicate securely with our back-end. We use Auth0Lock to get a professional looking login dialog that displays well on any resolution and device.

Time spend

I must admit that it was quite cumbersome to edit the material especially since camtasia was really buggy on windows 10. I kept track of all my time and this is how I spent it.

Audition

8 hours to learn/record/edit the audition video. Check it out here if you’ve missed it!

Recording

19 hours to learn the tech I want to teach and record.

Editing

11 hours editing.

Total

38 hours for an hour of production material.

Financially worth it? (UPDATE)

Since I’m an independent consultant I can calculate if it was worth my time. UPDATE: Now after I’ve received my first royalty check and with my second course in the pipeline to be released soon, I can confidently say it was worth it. Both experience wise and financially. I also got reimbursed $200 for the new microphone, which was cool since I needed a new one for my youtube screencasts anyway.

One thing I do know though is that it’s good PR to be a pluralsight author, which could lead to higher hourly rating.

Working with pluralsight

From the initial contact with the audition to working close with my editor on the course, pluralsight was super professional. I really enjoyed the experience, and it’s definitely something I recommend and encourage others to do. Being a web developer using the aspnet stack it was quite hard to find a course that wasn’t already done though. First I wanted to do an angular 2 course, but that was off the table since it’s still in alpha and a lot of authors are standing in line on that topic. My second idea was to do something with aspnet5, but that was off the table as well since it’s in beta, soon to be RC.

One thing that bothers me though is that as I was completing my course, I saw Shawn Wildermuth do a course on aspnet5 that has gone viral. Seems like different rules apply to different authors, which isn’t cool. Other than that, I really enjoyed working with pluralsight.

In conclusion

So, 38 hours to produce a 1 hour long course, to be fair the audition process is something I only need to do once so it’s really 30 hours spend on the actual course. As I recorded the course I became better at it, I’m sure the next course I do will be quicker. I definitely encourage other developers to go through the experience of creating a course, even if I have some experience from creating screencasts on youtube this was something entirely different.

My ambition is definitely to create more courses for pluralsight, preferrably on angular 2 when it’s released.

Until next time, have an excellent day!

ASP.NET vNext – DNX, DNU and DNVM

There seems to be some confusion about abbreviations used with aspnet5 (vNext), let’s try to sort them out and give a brief explanation.

  • DNX is a SDK and a runtime environment for creating .NET applications for Windows, Mac and Linux. Basically it allows the cross-platform development using the .NET 5 Core.
  • DNU is the .NET Development Utility. It allows you to build, package and publish projects created with DNX.
  • DNVM is the .NET Version Manager. It is basically a set of command line instructions which allow you to configure your .NET Runtime.

The official docs of ASP.NET 5 is a great resource, here’s a link: http://docs.asp.net/en/latest/getting-started/index.html.

Cheers!

Entity Framework 6 Change Tracking POCOs vs nHibernate

Let me warn you that this post is kind of a rant. Entity Framework is on version 6 and Code First with POCOs still can’t track changes on detached object graphs that has been sent over the wire. The scenario is quite simple:

  1. A client request an entity from the server, e.g. asp.net mvc controller renders a view.
  2. The client modifies the entity and posts it back, i.e. form post.
  3. The MVC model binder deserializes the form data to our domain model.
  4. The MVC controller should be able to update the database without first fetching the data and applying the update per property.

Well this isn’t entirely fair since we can actually do this for first level properties, but not for navigation properties, e.g. has-many relationships. NHibernate has been able to do this for ages.

A colleague working on the web team asked me for help regarding this matter and I knew that this was the case in EF4/5, but I figured they’ve implemented it by now. So I threw together a test, just to confirm that it was still as bad as I remembered it.

Let’s say our db context looks like this:

public class Db : DbContext
{
    public Db() : base("Db")
    {
        Configuration.LazyLoadingEnabled = true;
    }

    public DbSet Foos { get; set; }
    public DbSet Bars { get; set; }
}

With the following entities:

public class Foo
{
    public int Id { get; set; }
    public string Value { get; set; }
    public virtual ICollection Bars { get; set; }
}

public class Bar
{
    public int Id { get; set; }
    public string Value { get; set; }

    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }
}

Our db initializer just adds one record of Foo that has a child record Bar with the values Value:

public class DbInitializer : DropCreateDatabaseAlways
{
    protected override void Seed(Db context)
    {
        context.Foos.Add(new Foo
        {
            Value = "Value", 
            Bars = new List
            {
                new Bar { Value = "Value" }
            }
        });

        context.SaveChanges();
    }
}

Our test first reads the entity and disposes the context, i.e. the graph is now detached. We make some changes to the detached graph and try to apply the changes by passing the object to SaveOrUpdate with a new db context, i.e. simulating a post from the client to our server:


[TestFixture]
public class Test
{
    [Test]
    public void TestChangeTracking()
    {
        System.Data.Entity.Database.SetInitializer(new DbInitializer());
        
        Foo foo;
        // Read and send to the client over the wire
        using (var db = new Db())
        {
            foo = db.Foos.First();
            Assert.AreEqual(1, foo.Bars.Count);
        }

        // Client changes some values
        foo.Value = "Changed";
        foo.Bars.First().Value = "Changed";

        // Post to server for an update
        using (var db = new Db())
        {
            db.Foos.AddOrUpdate(foo);
            db.SaveChanges();
        }

        // What got saved?
        using (var db = new Db())
        {
            foo = db.Foos.First();
            Console.WriteLine("Foo.Value: {0}", foo.Value);
            Console.WriteLine("Foo.Bars[0].Value: {0}", foo.Bars.First().Value);
        }

        Assert.Fail("Use nhibernate instead.");
    }
}

What got saved? Foo.Value got updated to Changed but Bars didn’t. Pretty lame if you ask me. If you insist on using EF instead of nhibernate you’ll need to fetch the record in the new db context, diff and apply the changes to it and save.

ef_update_fail

Hope they do something about this soon, until next time, have a great weekend!

Asynchronous proxy for a synchronous WCF service

I recently had this scenario while working for a client where we wanted to consume a synchronous service asynchronously. We couldn’t change the service contract since it would break other proxy implementations. Luckily conventions implemented by the guys at microsoft made this task surprisingly easy, this is how we solved it.

Let’s say our service contract looks like this:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    string GetData(int value);
}

With the following service implementation:

public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}

An synchronous proxy would look something like this:

class ServiceClient : IService1
{
    private readonly IService1 _channel;

    public ServiceClient()
    {
        var factory = new ChannelFactory(binding, address);
        _channel = factory.CreateChannel();
    }

    public string GetData(int value)
    {
        return _channel.GetData(value);
    }
}

And consuming it synchronously is trivial:

var client = new ServiceClient();
var data = client.GetData(10)

So how do we consume this asynchronously? We simply define a parallel async service contract with the same ServiceContract name, like this:

[ServiceContract(Name = "IService1")]
interface IService1Async
{
    [OperationContract]
    Task GetDataAsync(int value);
}

And an asynchronous proxy would look something like this:

class ServiceClientAsync : IService1Async
{
    private readonly IService1Async _channel;

    public ServiceClientAsync()
    {
        var factory = new ChannelFactory(binding, address);
        _channel = factory.CreateChannel();
    }

    public Task GetDataAsync(int value)
    {
        return _channel.GetDataAsync(value);
    }
}

And consuming it asynchronously becomes trivial:

var client = new ServiceClientAsync();
var data = await client.GetDataAsync(10);

To summarize: The convention is as long as the service name is the same on the contract the method will be called if the method name matches and also if you’ve appended Async to the method name. Pretty smooth imho, and all without the need to change the “legacy service” contract.

Cheers!

socialtime.se lab days project

Lab days

I’ve been super busy at work but finally I’ve come around for some fun lab days coding.

The objective

I’ve often wondered how much time we spend on social media apps on our phones. The idea came pretty naturally – create an app that accurately measures the time for us.

Coding sessions

The 1.0 version of socialtime.se was coded in 4 sessions and this is how I disposed the time. The sessions are 1 or 2 days apart since I rarely have the time to sit and code for 8h straight nowadays, unless it’s for a paying customer of course.

  1. 2h developing the android app for monitoring running processes.
  2. 1h studying the android facebook SDK and implementing auth from the app.
  3. 4h developing REST backend with facebook auth and a super simple frontend.
  4. 1h publishing the app to play store and minor refactorings.
  5. 1.5h writing this blog post, 45 minutes on creating the graphics ;-)

Android App

The app is really basic, it has a background service running which monitors the running processes on a separate thread and just one activity to display the social time.

socialtime_app_v1.0

My first approach was to read the log and filter for ActivityManager since that seemed to work with the adb. But when running logcat from within the app I didn’t get the same information, which I guess is a good thing looking at it from a security standing point.

REST API and Authentication

Since we initially only measure facebook time it’s safe to assume that the users could use facebook to authenticate themselves. One other upside is that we can retrieve their identity by requesting their public information, meaning they won’t need to create a local account for providing a username.

This is where it became interesting, we’ve built a backend using asp.net webapi which allows authorized calls if the user’s authenticated via facebook. The user is authenticated via facebook but via the app, we can’t use the access token issued for the app to communicate securely with our backend. So this is my solution.

android facebook webapi authentication

In a sentence – We issue a new custom token by validating the facebook access token that is passed to us which can be used for secure communication. Pretty neat!

Frontend

I think it was about 2:55am when I finished the app and the API and everything was in place and working. My deadline was 3pm and not a minute more, I needed to be at work 9am and since I’m not in my twenties anymore I need the sleep to function properly.

I hosted the backend in an azure website and I had bought the domain socialtime.se via surftown and once I uploaded the page to surftown I noticed it couldn’t fetch the data. Why? You guessed it, I hadn’t enabled cross-origin resource sharing. So I quickly just installed the nuget package for cors, enabled it, decorated the controller with a EnableCors-attribute, re-deployed the API and voilá, beautiful fully working stack in place. And all this exactly as the clock turned 3am!

 

socialtime_v1.0

It isn’t pretty but hey, it worked!

Future

The infrastructure is in place so adding functionality will go fast. My unprioritized backlog looks something like this.

  • Measure time for Twitter, Instagram and G+, separately.
  • Measure time spent per app and per day. (now it’s just milliseconds since forever)
  • Proper frontend and move it to azure.
  • Remove the public list, you’ll need to login to see only your social time. Several requests for this actually :-)
  • Use some cool HTML5 charting lib to display your social time.

Until then, get the app and have a nice day!

 

googleplay

 

Entity Framework 6 Code First unreported breaking change/bug when migrating from version 5

Came a cross a nice bug in my golf score app on my season premiere round yesterday. I suddenly had a couple more strokes than I should with my HCP, although it seemed fair since it was the first round and all it didn’t make sense. I hadn’t made any (programmatic) changes to the code since the last time I played.

It took me a while to figure it out but my strokes were based on the female slope. All the custom male and female slopes were suddenly flipped, how come? I had moved the site from surftown to windows azure and with that also upgraded EF from 5 to 6 and compiled the back-end for .NET 4.5 instead of 4.0.
Without diving into golf details a golf club has one to many courses and a course has one to many tees. How many strokes a player gets from a given tee is based his HCP and is usually calculated with a formula. Unless the course has a custom slope table, then you’ll need to specify explicitly how many strokes you’ll get for a given HCP. The latter is the case on my home course, which also is the reason for me creating the app, since there is no other app that handles this well.
So my entities looked something like this (yup, I’m serializing my EF POCOs directly in my WebApi service, get over it :D)
public class Tee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    ...
    
    [InverseProperty("TeeAsMale")]
    public virtual ICollection CustomHcpAsMale { get; set; }
    [InverseProperty("TeeAsFemale")]
    public virtual ICollection CustomHcpAsFemale { get; set; }
}
public class TeeHcp
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonIgnore, IgnoreDataMember]
    public int Id { get; set; }

    public double From { get; set; }
    public double To { get; set; }
    public int Strokes { get; set; }
}
And since I haven’t mapped up the inverse property EF won’t be able to give the foreign keys good names, so the table will look like this:

ef_breaking_change_no_inverse_prop

which isn’t neat but it’s fine imho, it works, or at least it did work! Now all of the sudden CustomHcpAsMale and CustomHcpAsFemale switched places when getting the data. Since EF seemed to be confused I went ahead and explictly mapped the inverse properties, changing the code to something like this:
public class Tee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    ...

    [InverseProperty("TeeAsMale")]
    public virtual ICollection CustomHcpAsMale { get; set; }
    [InverseProperty("TeeAsFemale")]
    public virtual ICollection CustomHcpAsFemale { get; set; }
}
public class TeeHcp
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonIgnore, IgnoreDataMember]
    public int Id { get; set; }

    public double From { get; set; }
    public double To { get; set; }
    public int Strokes { get; set; }

    [JsonIgnore, IgnoreDataMember]
    public Tee TeeAsMale { get; set; }
    [JsonIgnore, IgnoreDataMember]
    public Tee TeeAsFemale { get; set; }
}
which after applying the migration changed the tables to look like this:

ef_breaking_change_with_inverse_prop

and voilá, problem solved! Once again upgrading libraries to run the latest and greatest versions for no reason bites me in the ass. I’ll try to report this to Microsoft as a breaking change, at least it was an easy fix and I figured it out quickly!
Lessons learned – don’t be lazy like me when mapping navigation properties!
Hope it helps somebody out. Peace!

Lab days with focus on security (STS, WebApi, WCF and WIF)

Lab days once again at work, this time I focused on security. Can’t share the code this time since it contains some company confidential stuff but the diagram below basically summarizes my architecture idea.

lab_days_security

Securing WCF service with WIF

There are plenty of blogs out there descibing how to do this so I’m not going to explain this i depth, if you however only have experience with using WIF 3.5 as me I found an excellent migration guidelines page on msdn (http://msdn.microsoft.com/en-us/library/jj157089.aspx). We use a custom binding for tcp transport support with reliable sessions which makes you wanna kill yourself when you see the binding configuration. Due to this I can’t share the code since it is considrered “intellectual property” of Saab (me?).

Important WIF 3.5 to 4.5 change!

You could previously access the calling users claims in the WCF service by casting ServiceSecurityContext.Current.PrimaryIdentity to ClaimsIdentity. This is no longer true, you’ll get the claims by casting Thread.CurrentPrincipal to ClaimsPrincipal or Thread.CurrentPrincipal.Identity directly to ClaimsIdentity. For this to work you’ll also need to set <serviceAuthorization principalPermissionMode=”Always” /> on the service behavior declaration. See also Dominick Baiers post for more details.

JWT, Identity Server v2 and WebApi

I’ve updated our development STS in our product at work from startersts to identityserver v2, which I thought was a great platform to continue exploring, especially since it supported to issue JWT (json web tokens). At least I thought it did until I discovered that it doesn’t! They do however have a branch that supports it and uses Microsoft JWT (https://github.com/thinktecture/Thinktecture.IdentityServer.v2/tree/Microsoft-JWT).

I found a nice message handler that validates JWTs which uses JSON Web Token Handler For the Microsoft .Net Framework 4.5 written by the security guru Vittorio Bertocci (http://code.msdn.microsoft.com/AAL-Native-Application-to-fd648dcf/sourcecode?fileId=62849&pathId=697488104). And as always I encountered major problems when trying to validate the JWT issued by identity server on the server-side (webapi). Victor uses windows azure ad together with Windows Azure Authentication Library which of course validates the token correctly.

I think there is a may release coming up for identity server, perhaps I’ll give it another shot then, but for now I had to use Azure AD.

The outcome wasn’t actually what I expected when I began but the road there was educative, I suggest following Victor on http://www.cloudidentity.com/blog to keep up with the updates on the json web token handler which currently only is in the developer preview stage. It hurts to keep up and always use bleeding edge technology but hey, they don’t call it lab days for nothing. ;-)

 

Peace!

WinRT app @ Labdays

Installed win8 on my work laptop not too long ago so I decided to create my first winrt app during lab days at work. Due to lack of imagination I created a simple dashboard app for our product SAFE (really ugly page on saabgroup btw).

Started of by looking at some sessions on channel9 and googled design patterns, frameworks and ended up with the following:

I ended up writing a custom navigation service that I bootstrapped on application startup to make the IOC container from MVVM Light play nicely together with the AlternativeFrame from WinRT Xaml Toolkit. If you pay attention to the navigation between pages you can notice the nice dissolve transition which is done in AppShell.xaml in only 4 lines of markup.
Once I got the basic architecture in place I noticed that the panorama control from windows phone was missing for winrt. One google search later I found a blog post that addressed this issue so I ended up copying some code since I didn’t want to install the entire nuget package win8nl. What it basically does is to add a panorama behvior to the FlipView control. The sad thing though is that you can’t flick the screen if you don’t have a touch screen, which is extremely frustrating!
As for what goes for component arts data viz library I really think it’s not worth to pay for (trial is free), in the short time I played around with it I stumbled upon several bugs. An ugly work around for the PieChart control can be seen in the code behind file MainPage.xaml.cs. When data binding to an observable collection the control goes bananas as items are added to the collection, I needed to reset the DataSource for each added item for it to work properly.
All and all I’m pretty satisfied with the choice to use MVVM Light together with WinRT Xaml toolkit and the custom navigation service, I will definitely reuse that part for other projects.
Anyways the result can be seen in the vid below, you can get the source code here, if you’re interested in how I hooked up the components and architecture. You will probably not be able to run the application since it requires our back-end and I didn’t spend too much time on exception handling.

 

Merry x-mas everybody and a happy new year, I’m off for two whole weeks!