Wednesday, April 30, 2014

How to make a Private Method in to a Public Method in .NET

Disclaimer: I actually recommend that you try to use this technique as little as possible.

Once and a while we all have to work with a poorly designed API, and sometimes you just really need to access to a private method inside of their code. So when you are out of other options, what can you do to access a private method?

You can try to decompile the code and fork it or extend it, but that might not work due to type constraints, and even if it does then you have to maintain multiple versions. The most common thing to do is use reflection to access the private methods or members, but then you have to share that ugly reflection code everywhere.

Just make an extension method.

Use reflection, but expose it as a extension method. This gives the illusion that the method you are exposing is natively public. This solution is simple and reusable, but please do not abuse it!

Tuesday, April 29, 2014

Should you use NuGet Package Restore on your Build Server?

In my opinion, no.

Recently, Mark Seemann wrote a terrific article regarding the dangers of using NuGet package restores on a build server. I highly recommend that you take a moment to read the whole article, but here are the major pros and cons that Mark offers to summarize the argument:

  • The Package Restore feature solves these problems:
    • It saves a nickel per repository in storage costs.
    • It saves time when you clone a new repository, which you shouldn't be doing that often.
  • On the other hand, it
    • adds complexity
    • makes it harder to use custom package sources
    • couples your ability to compile to having a network connection
    • makes it more difficult to copy a code base
    • makes it more difficult to set up your development environment
    • uses more bandwidth
    • leads to slower build times
    • just overall wastes your time

Having recently had this exact same debate at work I feel the need to chime in! I think that Mark's list really address the larger issue at core of this debate:

Sunday, April 6, 2014

Deserialize Abstract Classes with Json.NET

Here is a fun problem: how do you deserialize an array of objects with different types, but all of which inherit from the same super class?

If you are using Newtonsoft's Json.NET, then this is actually rather easy to implement!

Example

Here are three classes...

public abstract class Pet { public string Name { get; set; } }
public class Dog : Pet { public string FavoriteToy { get; set; } }
public class Cat : Pet { public bool WantsToKillYou { get; set; } }

...here is an array with instances of those objects mixed together...

new Pet[]
{
    new Cat { Name = "Sql", WantsToKillYou = true },
    new Cat { Name = "Linq", WantsToKillYou = false },
    new Dog { Name = "Taboo", FavoriteToy = "Sql" }
}

...and now let's make it serialize and deseriailze! :)

Extending the JsonConverter

This tactic is actually quite simple! You need to extend a JsonConverter for your specific super class that is able to somehow uniquely identify each child class. In this example we look for a specific property that only exists on the child class, and Newtonsoft's JObjects and JTokens make this very easy to do!

Tuesday, April 1, 2014

TypeScript Definition Files on NuGet: Always have the latest and greatest IntelliSense!

The strongly typed nature of TypeScript offers the potential for amazing IntelliSense!

Open Source TypeScript Definitions

Some people do not realize that there is already a vast library of community authored definition files for just about every JavaScript framework out there. By including these definition files in your project, you can unlock the full potential TypeScript's IntelliSense.

The Original DefinitelyTyped Repository on GitHub

TypeScript Definitions on NuGet

The best thing about the open source community: whenever someone has a great idea, other people gladly line up to help improve it. To that end people have forked Boris's DefinitelyTyped, created NuGet packages, and automated their deployment!

DefinitelyTyped NuGet Repository on GitHub
jquery.TypeScript.DefinitelyTyped on NuGet

jQuery Example

If you want to use jQuery, just install the jquery.TypeScript.DefinitelyTyped NuGet package...

Saturday, March 15, 2014

String.Concat vs StringBuilder Performance

Time for yet another micro-optimization!

Everyone knows that Strings are immutable in .NET, thus the StringBuilder class is very important for saving memory when dealing with manipulating large strings.

...but what about performance?

Interestingly, StringBuilder is just an all around better way to combine strings! It is more memory efficient, and less processor intensive; but not by much. Below is a comparison of performance between different ways of combine strings.

Tuesday, March 11, 2014

Migrating from Moq to NSubstitute

Mocking is a necessary evil for unit testing.

Fortunately frameworks like NSubstitute make it painless setup your mock services. NSubstitute offers a fluent API that requires few lambdas and no calls to an Object property. You just get back the interface that you are substituting and work with it directly. Frankly, NSubstitute is so easy to work with that it almost seems like magic!

Below is a visual representation of equivalent commands between Moq and NSubstitute:

NSubstitute

[Fact]
public void NSubstitute()
{
    var tester = Substitute.For<ITester>();
 
--------------------------------------------
            
    var voidArg = String.Empty;
 
    tester
        .When(t => t.Void(Arg.Any<string>()))
        .Do(i => voidArg = i.Arg<string>());
 
    tester.Void("A");
    Assert.Equal("A", voidArg);
 
--------------------------------------------
 
    tester
        .Bool()
        .Returns(true);
                
    var boolResult = tester.Bool();
    Assert.Equal(true, boolResult);
 
--------------------------------------------
 
    tester
        .Int
        .Returns(1);
 
    var intResult = tester.Int;
    Assert.Equal(1, intResult);
 
--------------------------------------------
 
    tester.Received(1).Void("A");
 
--------------------------------------------
 
    tester.DidNotReceive().Void("B");
}

Moq

[Fact]
public void Moq()
{
    var tester = new Mock<ITester>();
            
    // Setup a callback for a void method. -------
 
    var voidArg = String.Empty;
 
    tester
        .Setup(t => t.Void(It.IsAny<string>()))
        .Callback<string>(s => voidArg = s);
 
    tester.Object.Void("A");
    Assert.Equal("A", voidArg);
 
    // Setup the result of a method. -------------
 
    tester
        .Setup(t => t.Bool())
        .Returns(true);
 
    var boolResult = tester.Object.Bool();
    Assert.Equal(true, boolResult);
 
    // Setup the result of a property. -----------
 
    tester
        .SetupGet(t => t.Int)
        .Returns(1);
 
    var intResult = tester.Object.Int;
    Assert.Equal(1, intResult);
 
    // Ensure that a function was called. --------
 
    tester.Verify(m => m.Void("A"), Times.Once);
 
    // Ensure that a function was NOT called. ----
 
    tester.Verify(m => m.Void("B"), Times.Never);
}

Enjoy,
Tom

Saturday, March 8, 2014

String.Concat vs String.Format Performance

Time for another micro-optimization!

When building strings it is almost always easiest to write and maintain a typical format statement. However, what is the cost of that over just concatenating strings? When building strings for cache keys (which I know are going to get called a lot) I try to use String.Concat instead of String.Format. Let's look at why!

Below is a table showing a comparison the performance difference between String.Concat and String.Format. The Y axis is the number of arguments being concatenated. The X axis is the number of milliseconds it takes to complete 100,000 runs.

Number
of Args
String.Concat
Milliseconds
String.Format
Milliseconds
Concat
Percent Faster
2 4ms 10ms 150%
3 3ms 13ms 333%
4 4ms 16ms 300%
5 12ms 21ms 75%
6 14ms 24ms 71%
7 16ms 28ms 75%
8 18ms 31ms 72%
Real Time Web Analytics