Bower in Visual Studio 2015 inside a corporate network

While playing with Aspnet 5 (vnext) I created a new project and wanted to add a few javascript packages to it. In VS2015 we are expected to use bower for client side packages instead of nuget. I added the bower.json file and included bootstrap and tried to restore, and got some git exceptions.

It took me a while googling and playing before I got bower to restore packages inside our corporate network. In the end I configured bower to use cntlm.

This is my .bowerrc file

{
    "directory": "wwwroot/Scripts/3rdParty",
    "registry": "http://bower.herokuapp.com",
    "proxy": "http://localhost:3128",
    "https-proxy": "http://localhost:3128",
    "strict-ssl": false
}

Assembly Neutral Interface Performance

I already wrote how impressed I was by the new Assembly Neutral Interface feature in aspnet vNext. So I decided to continue my experiment and test the performance.

In order to have something to compare to, I wrote an identical interface to the one I wrote for the previous post.

public interface ITestType
{
    string Get();
}

public class TestType : ITestType
{
    public string Get()
    {
        return "Got";
    }
}

I then wrote this test code, and ran it a few times in release mode.

public void Main(string[] args)
{
    var myTypeTime = TimedExecution(() => { IMyType t = new MyType(); } , 1);
    var testTypeTime = TimedExecution(() => { ITestType t = new TestType(); }, 1);

    Console.WriteLine("Assembly Neutral Interface first create time: " + myTypeTime.Ticks + "ticks");
    Console.WriteLine("Normal Interface first create time: " + testTypeTime.Ticks + "ticks");

    IMyType myType = new MyType();
    ITestType testType = new TestType();
    
    myTypeTime = TimedExecution(() => myType.Get(), 1);
    testTypeTime = TimedExecution(() => testType.Get(), 1);

    Console.WriteLine("Assembly Neutral Interface first execution time: " + myTypeTime.Ticks + "ticks");
    Console.WriteLine("Normal Interface execution first time: " + testTypeTime.Ticks + "ticks");

    myTypeTime = TimedExecution(() => myType.Get(), 10000000);
    testTypeTime = TimedExecution(() => testType.Get(), 10000000);

    Console.WriteLine("Assembly Neutral Interface execution time after warmup: " + myTypeTime.TotalMilliseconds + "ms");
    Console.WriteLine("Normal Interface execution time after warmup: " + testTypeTime.TotalMilliseconds + "ms");

    myTypeTime = TimedExecution(() =>
    {
        IMyType m = new MyType();
        m.Get();
    }, 10000000);

    testTypeTime = TimedExecution(() =>
    {
        ITestType t = new TestType();
        t.Get();
    }, 10000000);

    Console.WriteLine("Assembly Neutral Interface creation and execution time: " + myTypeTime.TotalMilliseconds + "ms");
    Console.WriteLine("Normal Interface creation and execution time: " + testTypeTime.TotalMilliseconds + "ms");
    
    Console.ReadLine();
}

The results show that the performance is a bit more expensive for instantiation but practically identical for execution. However it seems that there is a small warmup cost.

Assembly_Neutral_Interface_PerfTest_1

Assembly_Neutral_Interface_PerfTest_2

Assembly_Neutral_Interface_PerfTest_3

Duck Typing in Aspnet vNext

One of the cool new features announced as part of aspnet vnext is Assembly Neutral Interfaces. Assembly Neutral Interfaces allow you to define identical interfaces in multiple assemblies and then treat then as one interface. In other words Duck Typing.

Many people say that seeing is believing, but of course as developers we know that playing is believing, So I decided to play with it.

I created a new Aspnet vNext console application and 2 Aspnet vNext class libraries. In each library I put the following code file.

namespace DuckTypes.Types
{
    [AssemblyNeutral]
    public class AssemblyNeutralAttribute : Attribute { }

    [AssemblyNeutral]
    public interface IMyType
    {
        string Get();
    }

    public class MyType : IMyType
    {
        public string Get()
        {
            return "Got";
        }
    }
}

Except that in the second file I called the class MyType2 and the Get method returned “Got2”. I then created an array of IMyType and put and instance of each in it, and output type.Get() to the console.

IMyType[] types = new IMyType[] { new MyType(), new MyType2() };

foreach (var type in types)
{
    Console.WriteLine(type.Get());
}

 

Visual Studio had a fit about this

vs_errors_assembly_neutral_interfaces

But it works

console_assembly_neutral_interfaces

I think I’ll run some performance tests to see how it compares to regular referenced interfaces.

Contravariance and Acyclic Vistor Pattern

Yesterday a friend of mine showed me this post that discusses the Acyclic Visitor Pattern. In the post the author shows how to use generics to create a visitor interface that does not need to know each implementation type. Instead the accepting element (or visitee) tries to downcast the visitor to its own type. Although this requires a type check within each element it still keeps the visitor interface agnostic of the implementations.

Example (base on post from above)

Classic Visitor

public interface IClassicFruit
{
    void Accept(IClassicFruitVistor visitor);
}

public interface IClassicFruitVistor
{
    void Visit(ClassicOrange lemon);
    void Visit(ClassicApple apple);
}

public class ClassicApple : IClassicFruit
{
    public void Accept(IClassicFruitVistor visitor)
    {
        visitor.Visit(this);
    }
}

public class ClassicOrange : IClassicFruit
{
    public void Accept(IClassicFruitVistor visitor)
    {
        visitor.Visit(this);
    }
}

Acyclic Visitor

public interface IFruit
{
    void Accept(IFruitVisitor visitor);
}

public interface IFruitVisitor
{
}

public interface IFruitVisitor<TFruit> : IFruitVisitor where TFruit : IFruit
{
    void Visit(TFruit fruit);
}

public class Apple : IFruit
{
    public void Accept(IFruitVisitor visitor)
    {
        if (visitor is IFruitVisitor<Apple>)
            ((IFruitVisitor<Apple>)visitor).Visit(this);
    }
}

public class Orange : IFruit
{
    public void Accept(IFruitVisitor visitor)
    {
        if (visitor is IFruitVisitor<Orange>)
            ((IFruitVisitor<Orange>)visitor).Visit(this);
    }
}

The friend who showed this to me had an objection. He said that although this removed the need for the visitor interface to know all implementation types, it remove the ability to handle inheritance without extra (not very pretty code)

In a classic visitor I can do this

public interface IClassicFruitVistor
{
    void Visit(ClassicOrange lemon);
    void Visit(ClassicApple apple);
    void Visit(IClassicFruit fruit);
}

public class ClassicLemon : IClassicFruit
{
    public void Accept(IClassicFruitVistor visitor)
    {
        visitor.Visit(this);
    }
}

Although there is no Visit for ClassicLemon it will get picked up by Visit(IFruit),

But in the generic visitor I would need to do this.

public class Lemon : IFruit
{
    public void Accept(IFruitVisitor visitor)
    {
        if (visitor is IFruitVisitor<Lemon>)
            ((IFruitVisitor<Lemon>)visitor).Visit(this);
        else if (visitor is IFruitVisitor<IFruit>)
            ((IFruitVisitor<IFruit>)visitor).Visit(this);
    }
}

And It would be worse if I added and ICitrusFruit into the mix.

C# to the Rescue

The good news is that there is a simple solution for this problem build right into C# and all it take is 3 characters

If we make IFruitVisitor Contravariant we don’t need the extra type check anymore and we can do this for any depth of inheritance.

I made these changes to the above generic sample

public abstract class CitrusFruit : IFruit
{
    public abstract void Accept(IFruitVisitor visitor);
    public decimal Weight { get; set; }
}

public class Orange : CitrusFruit
{
    public override void Accept(IFruitVisitor visitor)
    {
        if (visitor is IFruitVisitor<Orange>)
            ((IFruitVisitor<Orange>)visitor).Visit(this);
    }
}

public class Lemon : CitrusFruit
{
    public override void Accept(IFruitVisitor visitor)
    {
        if (visitor is IFruitVisitor<Lemon>)
            ((IFruitVisitor<Lemon>)visitor).Visit(this);
    }
}

And added three visitors (Apple, Orange, CitrusFruit) that look like this

public class CitrusVisitor : IFruitVisitor<CitrusFruit>
{
    public int Count;

    public void Visit(CitrusFruit fruit)
    {
        Count++;
    }
}

And then I wrote this test to prove it.

[TestMethod]
public void TestVisitors()
{
    var citrusVisitor = new CitrusVisitor();
    var fruitVisitor = new FruitVisitor();
    var appleVisitor = new AppleVisitor();

    var vistors = new IFruitVisitor[] {citrusVisitor, appleVisitor, fruitVisitor};
    var fruits = new IFruit[] {new Orange(), new Lemon(), new Apple()};

    foreach (var visitor in vistors)
    {
        foreach (var fruit in fruits)
        {
            fruit.Accept(visitor);
        }
    }

    Assert.AreEqual(1, appleVisitor.Count);
    Assert.AreEqual(2, citrusVisitor.Count);
    Assert.AreEqual(3, fruitVisitor.Count);
}

As long as the IFruitObserver<TFruit> looks like it does above, this test will fail.

As soon as we make this minor (3 char) change to the interface

public interface IFruitVisitor<in TFruit> : IFruitVisitor where TFruit : IFruit
{
    void Visit(TFruit fruit);
}

The test passes.

Did I mention that I like Generics?

Summary

I don’t know if I would recommend this pattern in this form since it still requires a down cast to the generic version of the IFruitVisitor but it is a nice demonstration of Contravariance

Why we don’t validate incoming xml

Often people ask me why we don’t validate the incoming xml against our xsd contracts at runtime.

It seems like a logical idea, why write an xsd and then ignore it at runtime.

Below I will give 3 reasons.

1) Performance

This is the simplest of all the reasons, yet it is not unimportant. Validation with an xsd is not a cheap operation and doing it for each request when most of the requests are valid is a waste of time. CPU cycles isn’t the only consideration here, In order to validate against an xsd you need the xsd. For that you need to either include the xsds as embedded resources or deploy the xsds with the binaries and load them at runtime. In both cases this will enlarge the memory footprint which is something we can’t afford on low-spec machines.

2) Tolerance

There is a general concept in api design that says you should be strict with your output but liberal with your inputs. Basically anything you can tolerate without crashing you should agree to work with even if it violates the spec a bit. Here as well, there may be certain elements that violate the schema but that you don’t really have an issue with, there is no reason, in such a scenario, to throw an exception just because it is in the xsd.

You may wonder how such a thing can happen? How is it that the code doesn’t really require what the xsd says. I can imagine a few simple scenarios where this can happen.

The simplest is that you didn’t write the contract. The contract may have been written by a third party and we implement it and don’t really care about all the things they care about. Another scenario is element reuse, In most of the use cases a certain field is required so it is marked as such, but in certain scenarios it is not. There may also be elements that are conceptually required but you can live without them (maybe header info). You may also have a regex restriction to prevent illegal characters (maybe for security reasons) that can be resolved by sanitizing the input rather that throwing an exception.

3) Forward Compatibility

This is the biggest and the only unsolvable issues that I can think of. Lets say that In version 1 we had 3 elements and in version 1.1 we added an optional 4th element. This is a fully backwards compatible change so we only incremented the minor version. Now what if a customer has both versions deployed and he upgraded his requests to work with the new optional field?. If we validate against the xsd and the customer sends version 1.1 to version 1.0 (which should be ok) it will fail xsd validation.