Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

Using Grunt/Karma/Jasmine-Ajax inside your Jasmine Tests

My current client is trying to add JavaScript specs to its code base and we have decided to implement a Grunt/Karma/Jasmine solution.

Like many (if not most) JavaScript code bases our code will make remote calls via jQuery to the server to Get or Post data. I wanted to be write tests which mocked the over the wire call and returned me some stubbed data. Accomplishing this took very little effort and was quite simple once I figured it out.

Here is how I accomplished this
1) Add the Mock-Ajax.js file to your test suite. I did this manually as the NPM package used a very old version of the .js file and it caused me issues.

2) Add a reference to the mock-ajax.js file to your Karma configuration

    files: [
        ...
        'js.tests/mock-ajax.js',
        ...
    ],

3) Install the mocks inside the beforeEach() method inside your spec

    beforeEach(function() {
        jasmine.Ajax.install();
    });

4) Create your test response you are mocking inside your spec

var testResponses = {
    results: {
        success: {
            status: 200,
            responseText: { json goes here }
        }
    }
};

Your test response needs to follow this pattern because the mock library is going to inspect the response for success/failure status.

5) Run your JavaScript code as normal, no need to setup spy’s or mocks as the Ajax library is going to intercept all HTTP calls automatically.

6) Grab the most recent request and shove in the mock results

        var request = jasmine.Ajax.requests.mostRecent();
        request.respondWith(testResponses.results.success);

You can add the code below AFTER the code that makes the HTTP call, it is ok. You should notice that I am pushing in the success result inside of the respondWith() call, this will tell the Ajax library how to respond inside your code.

7) setup your asserts as expected based on your mock results.

Hope this helps.

Till next time,

Posted in Grunt, Jasmine, Testing | 2 Comments

C# 6 Features – Private Auto Properties

C# 6 is on the horizon with a slew of new features being introduced. One of them that I find pretty cool is the ability to have Auto Properties with an inferred private setter.

It is very typical in my normal development process to create code just like below.

public class Mammal
{
    public Mammal(string type)
    {
        Type = type;
    }

    public string Type { get; private set; }
}

Anyone who has done any C# knows that I just created a auto property with a private setter. But why should I have to go through the ceremony of having the ‘private set;’ in code, why cannot I simply omit the setter and everything just works? Well in C# 6 you can do exactly this. Take a look at the code below.

public class Mammal
{
    public Mammal(string type)
    {
        Type = type;
    }

    public string Type { get; }
}

Notice I simply removed the ‘private set’ code, but I did not touch the code in the constructor which is setting the property and everything still worked. This is a nice little compiler enhancement to make your code a bit more terse. One thing I should point out is that you can ONLY set the setter inside the constructor of the class.

When you look at this feature, I would expect that under the covers the compiler would weave in code which adds back in the private setter. Yea, not so much.

Take a look at the decompiled code below.

Source for the ‘old’ way of doing things

    public class Mammal
    {
        public string Type
        {
            get;
            private set;
        }

        public Mammal(string type)
        {
            this.Type = type;
        }
    }

Source for the ‘new’ way of doing things

    public class Person
    {
        public int Age
        {
            get
            {
                return this.<Age>k__BackingField;
            }
        }

        public Person(int age)
        {
            this.<Age>k__BackingField = age;
        }
    }

If you compare the 2 blocks of code above they are not what I would have expected. I would have expected that the compiler to weave code into the ‘new’ style of doing things to make the code look exactly as the old way. Oh well, it is different but really who cares :)

This new feature is small, and is really just compiler candy, but honestly I like it. It will go a long way in helping to push more people to write immutable code.

Till next time,

Posted in C# | 2 Comments

Solving Json discrepancies using a JsonConverter

During my day job I am a client developer who is beholden to various back end API’s. Normally these API’s are well thought out and pretty easy to use, and normally their resulting json model make sense. But as we know, normally does not mean always. A few weeks ago I was implementing a feature which and built a object model based on the response from the API and the needs of my feature. Fast forward to present time and I am implementing another feature, similar but different. At first glace of the resulting json coming from the API it dawned on me that I could resume my object model from before (this makes sense since the features are in the same scope and are very tightly coupled).

As I set out to code my solution I hit a point where I needed to desearlize my json document to my object graph. No big deal as I am using Json.net and this is cake. But we know that nothing in software is cake. I immediately get an error while deserializing my graph, but why.

Below is my original json graph

"participants": [
{
  "id": "1ab644ce-481d-443f-a569-202a06cad740",      
  "calls": {
      "id": "c72537f6-af1e-4afe-abc2-5815b25960eb"
    }
},       

This graph looks pretty normal (note that most properties were removed as they were just noise). I have an array of participants and each participant has a calls subobject.

No look at the json graph from the 2nd api hit

"participants": [
{
  "id": "1ab644ce-481d-443f-a569-202a06cad740",      
  "calls": [
    {
      "id": "c72537f6-af1e-4afe-abc2-5815b25960eb"
    }
  ]
},

Do you see the subtle difference? In the second graph the Calls subobject is not an object but rather an array of objects. WTF????

I stared at this problem for some time trying to find the most elegant way to solve the problem and be able to resume my object graph, since the graph is expected to be the same.

The solution I found was to use a JsonConverter which will allow me to custom convert my Calls node as needed.

The first thing I needed to do is decorate my Call property in my object graph as below

        [JsonProperty("calls")]
        [JsonConverter(typeof(VoiceConversationCallsConverter))]
        public VoiceConversationCall Call { get; set; }

The next thing I need to do is create my VoiceConversationCallsConverter. Inside this converter I am going to determine if the node currently being parsed is an object or an array and return back the correct value.

    public class VoiceConversationCallsConverter : JsonConverter 
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartObject)
            {
                return serializer.Deserialize(reader);
            }
            
            if (reader.TokenType == JsonToken.StartArray)
            {
                var asArray = serializer.Deserialize<List>(reader);
                if (asArray != null && asArray.Any())
                {
                    return asArray.First();
                }

                return new VoiceConversationCall();
            }

            return serializer.Deserialize(reader);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }

Pay attention to the ReadJson method. Inside this method I am looking at the TokenType for the current node and asking if it is an object or an array. once I know the TokenType I can deserialize my reader into the correct type and return it as needed.

Doing this allowed me to have a single object graph (again, which is expected) and process two slightly different json graphs.

Till next time,

Posted in C# | Tagged | 1 Comment

Using Grunt-TSD w/ Node

If you are a fan of Typescript I assume you are well aware of the amazing type definition repository over at definitelytyped.org. This repository is great because it provides a definitive source for type definitions for pretty much every major JavaScript library.

If you are a fan of Node.js and JavaScript I have to assume that you are a fan of Grunt (or Gulp, your choice). You can use Grunt to automate pretty much every action needed when building HTML/JavaScript applications. Did you know you can also use Grunt to automate the retrieval of update type definitions from the DefinitelyTyped repository? Yup, you can. You simply need to use the Grunt-TSD plugin.

Here is how:

Reference the Grunt-TSD Plugin:
Simply NPM install the plugin using ‘npm install grunt-tsd –save-dev’

Add reference to the plugin inside your Grunt Script:
grunt.loadNpmTasks(‘grunt-tsd’);

Create a tsd.json file
In my opinion it is a bit cleaner to put your tsd configuration external to the grunt script, because of this I am following the path of creating a tds.json file. Make sure you create this file local to your gruntfile.js file. Below is my sample tsd.json file
tsdjson
Please note that the Path:typings entry in the tsd.json configuration is configurable. I wanted my d.ts files put into a ‘typings’ folder in my root. Of course you can change the name or location of this folder if you wish.

Download and install a Type Definition
In order to use a Type Definition you need to install it via TSD. To do this open your cmd prompt and CD into the directory which has your tsd.json file. Once there you can issue the following command ‘tsd query [package name] install -s -o’. This will install your package and update the tsd.json configuration files. For a full overview of the TSD syntax check out the TSD readme

Adding the TSD configuration to your Grunt file
After you have created your tsd.json file we need to create our configuration node inside of grunt. Below is my sample configuration.
tsd

Add the TSD task to a Registered Task
Once you have your TSD configuration node setup the last thing you will need to do is to call this from one of your Registered Tasks in your file.

Once you have all this setup you should be ready to roll. Simply issue a Grunt call to your configuration task (or use Grunt tsd) and watch the magic happen. To validate this worked as expected simply check you typings folder.

Till next time,

Posted in Grunt, TypeScript | Leave a comment

Using InvokeCommandAction in Winodws 8.1 Universal Applications

This is just a PSA posting.

If you are making the jump from Windows 8 or Windows Phone 8 XAML development and are used to use the EventToCommand helper which comes along w/ the MVVM Light framework, things have changed and it is ok. In fact Laurent has a nice post on how to use the new built-in EventTriggerBehior rather than the EventToCommand helper.

However, there is two key pieces of information missing from his examples.
1) In order to get the Interaction.Behaviors namespace included you reference the Behaviors SDK inside your Windows 8.1 project
2) You will need to add reference to the correct namespaces in your xaml (see below)

xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"

Once you have done these 2 things you should be good to go.

Till next time,

Posted in Uncategorized | Leave a comment