Mocking Base Class Methods with Moq

Moq does allow you to mock base class methods, via the use of the Moq.Protected namespace. You can read about it here.

Imagine you have the following scenario:


class Animal {
  private int timesTalked = 0;
  public void Talk() {
    timesTalked++;
  }
}

class Cat {
  public void Talk() {
    base.Talk();
    Console.WriteLine("meow!");
  }
}

class CatTest {
  public void TalkDoesntThrow() {
    var c = new Moq<Cat>().Setup(c => c.Talk()) ... // Cat.Talk

In this case, you want to test the Cat.Talk method by mocking out the base class method. How can you do this?

At first glance, you can’t, because the signatures match. But, if you can make your base class method protected instead, that gives you breathing room:


class Animal {
  protected void Talk() { .. }
}

class CatTest {
  public void TalkDoesntThrow() {
    var c = new Mock<Cat>();
    c.Protected().Setup("Talk") ... // Animal.Talk
}

If this doesn’t work, you need to change one of the method signatures, like so:


class Cat {
  public void Talk(string message) { ... }

The final caveat I noticed is that the mocking is sensitive to the use of the base keyword. It seems like the CLR knows the actual base type and calls that, instead of the one derived from Moq.

That is, in our Cat class, we call base.Talk. Instead of that, we should just invoke Talk.

This affects the runtime binding, since Moq dynamically subclasses our mocked classes.

Posted in Libraries, Web, Wndows Forms, WPF | Tagged | Leave a comment

Converting IronRuby’s MutableString to C#’s String

Continuing my experiments in IronRuby, I found that return "hi" in Ruby returned an instance of something called MutableString, which was not easily interchangable with C#’s string:


dynamic irString = Ruby.CreateEngine().Execute("return 'hi');
Console.WriteKine(irString.GetType().Name); // Prints out "MutableString"
Assert.True(irString == "hi"); // fails?!

This caused me much confusion and befuddlement. I can’t compare for equality, nor can I call Contains to see if MutableString contains the substring I want to check.

The solution, trivially, was to call ConvertToString(); this returns a plain, vanilla C# string object (since IronRuby is implemented in C#. This works:


dynamic irString = Ruby.CreateEngine().Execute("return 'moo!').ConvertToString();
Assert.True(irString == "moo!");

For reference, I used this set of DLR/Ruby documentation to find this method.

Posted in Libraries | Tagged | Leave a comment

Extending C# Classes in IronRuby

Ruby provides several ways to extend classes — subclassing, mixins, and monkey-patching. How can we send IronRuby a C# class and extend it?

I experimented with several approaches. Here’s a run-down of what worked, and what didn’t.

But first, the basics: I created a very simple C# class to experiment with:


namespace IronRubyTest {
  class Cat {
   public string Name { get; set; }
   public Cat(string name) { this.Name = name; }
    public string Talk() {
      return string.format("{0} meows", this.Name);
    }
  }
}

With that in mind, on to the (non-animal!) experimentation!

Monkey-Patching

Monkey-patching, in this context, means adding methods to a class when you don’t have the source. A simple example:


class String
  def say_hi
    return "HI!"
  end
end

puts "some string".say_hi # prints "HI!"

Monkey-patching doesn’t work, mysteriously; even if you use load_assembly to make the CLR types equivalent (as mentioned in a previous post), the new methods don’t appear:


load_assembly 'IronRubyTest'
class IronRubyTest::Cat
  def Meow
    return "MEOW!!!"
  end
end

return IronRubyTest::Cat.new('Snowball')

This code, paradoxially, returns the old type of IronRubyTest.Cat; even if I type it to dynamic, I get an error that IronRubyTest.Cat does not contain a definition for 'Meow'. Disappointing.

Even more disappointing, I couldn’t override the method in Ruby. It just ran the C# version.

Subclassing

This works:


class Cat < IronRubyTest::Cat
  def Meow
    return "MEOW from Ruby!"
  end
end

return Cat.new('Sapphire')
end

Not only did I get back a cat which responds to Talk and has a public Name field, but it responds to cat.Meow with MEOW from Ruby!

The only caveat is that the type returned is Cat$1, which is surprising (or maybe not so surprising considering it’s a subclass).

But it works. In fact, I’m sure I can define abstract classes and interfaces in C# and implement them in custom subclasses in Ruby.

But that’s an experiment for another day.

Conclusion

Extending C# classes in Ruby is not that easy, but it’s possible. One approach worked, one didn’t. Did you try a third approach? How did it pan out for you?

Posted in Libraries | Tagged | Leave a comment

Manually Rolling Back a TransactionScope

The standard way to manage exceptions in ASP.NET (and by extension, MVC) web applications is to use the System.Transactions.TransactionScope class. It contains some useful properties:

  • Auto Transaction Start: As soon as you instantiate the TransactionScope instance, it starts the transaction.
  • Database Level: By default, this affects all connections in and out of the database. This means you can use it even when you don’t have access to the connection instance.
  • Disposable: TransactionScope implements IDisposable, meaning if you wrap it in a using statement, it automatically commits the transaction (or rolls back if an exception occurs).

But the question is, how do you manually force a transaction to roll back? For example, in your integration/functional tests, you may want to start a transaction in the setup method, and roll it back in the tear-down method.

Oddly, there is no Rollback method (although there is a Complete method to force commiting the transaction). The answer, oddly enough, is to manually invoke Dispose.

I confirmed by decompiling the .NET 4.5 source that calling Dispose rolls back the transaction.

In my situation, this came with quite a cost: in a simple functional test, the runtime tripled (from 15s with manual clean-up, to 45s with a transaction). So be weary, and make sure you pick the solution that works for you.

Posted in Core .NET, Web | Tagged | Leave a comment

From C# To Javascript and Back Again, Via ClearScript

Note: This is the second of two articles on integrating C# and scripting languages. You can read the second part (for Ruby) here.

I recently created an engine (I know, I know) to create text-based Interactive Fiction games in C#. My requirement was simple: create a core engine with some core functionality (rooms, commands, and objects) in .NET, and allow end-users to write their games in Javascript. In the process, I picked up a little-known gem called ClearScript as the vehicle of interaction.

Let’s start with my requirements: I should be able to write core functionality classes in C#, instantiate and extend them in ClearScript, and return them back to C# for consumption by the game engine. I also need strong typing of objects (despite the dynamic nature of scripting languages), and the ability to create delegates or functions inside my scripting language (and return those to C#, too).

You can view the source code on GitHub. This post summarizes my implementation, and the challenges I ran though.

Why ClearScript?

ClearScript is far from the most popular Javascript library for C#. Why did I choose it? Because it had a simple syntax, and more importantly, it allowed me to return strongly-typed objects to C# (including Action instances) where Javascript.NET, Jurassic, could not.

JavascriptRunner Class

I created a core “JavascriptRunner” class which encapsulates all the Javascript-centric invocation. It contains a simple constructor, and a method public T Execute<T>(string script, IDictionary<string, object> parameters).

The first parameter (the script) is the easiest part. The second parameter contains any variables from C# that I want to expose to Ruby (this makes up my “API” which users write against).

One issue I ran into is that ClearScript doesn’t support the widely-supported console.log method. To get around this, I simply registered the Console class to it:

engine.AddHostType("Console", typeof(Console));

Here’s how that looks, as of writing:


public JavascriptRunner()
{
    this.engine = new V8ScriptEngine();
    var assembly = System.Reflection.Assembly.Load("MeltDown.Core");

    foreach (var type in assembly.GetTypes())
    {
        engine.AddHostType(type.Name, type);
    }

    // Used for anonymous functions
    engine.AddHostType("Action", typeof(Action));
    // JS doesn't support console.log (JS/V8/Chrome style)
    engine.AddHostType("Console", typeof(Console));
}

public T Execute<T>(string script, IDictionary<string, object> parameters)
{

    foreach (var kvp in parameters)
    {
        // TODO: these are engine-scope. It doesn't reset.
        engine.AddHostObject(kvp.Key, kvp.Value);
    }

    var toReturn = engine.Evaluate(script);

    if (toReturn is T)
    {
        return (T)toReturn;
    }
    else
    {
throw new ArgumentException("Expected " + typeof(T).FullName + " but got " + toReturn.GetType().FullName);
    }
}

Notice I can’t pass in parameters per script execution (unlike the Ruby version). That’s okay too; there’s room to improve.

Converting ClearScript Arrays to C# Lists

The second major hurdle is that ClearScript returns an Array instance instead of an enumeration if I use typical Javascript list syntax, like this: var x = ['a', 17, 2.0 / 3].

To get around this, I created a ScriptHelper class. This class contains two methods: IsArray and ToList<T>. In both methods, I rely on IronRuby-specific implementation, and since the object input is dynamic, I can just call Javascript methods and get back what I want. Here’s how that looks (Javascript only):


public static List<T> ToList<T>(dynamic source)
{
    for (int i = 0; i < source.length; i++)
    {
        object next = source[i];
        found.Add(GetAsType<T>(next));
    }

    return found;
}

public static bool IsArray(dynamic source) {
    return source.constructor.name == "Array";
}

This allows me to write “Javascript-like” code without worrying about types.

Returning Delegates/Functions

The last hurdle was related to functions; given a delegate or function type (like Action), how can I return an object which I can type to a delegate type?

The answer was two parts. First, I need to register the Action class with ClearScript, like so:

engine.AddHostType("Action", typeof(Action));</script>

The second was to wrap any functions into an <code>Action
constructor:


new Action(function() {
    this.Description = "A steaming, hand-burning potato";
})

Conclusion

Given my requirements, I achieved them, and have code that allows me to write very “Javascript-like” code. That’s great; I can leverage C# to take care of some of the leaky abstractions, and everything works.

I suggest you download and play with the full source code from GitHub. You can look at the ScriptRunner.Tests project to see working Ruby code coming back to C#.

Posted in Libraries, Wndows Forms | Tagged , | 1 Comment

From C# Ruby and Back Again, via IronRuby

Note: This is the first of two articles on integrating C# and scripting languages. You can read the second part (on Javascript) here.

I recently created an engine (I know, I know) to create text-based Interactive Fiction games in C#. My requirement was simple: create a core engine with some core functionality (rooms, commands, and objects) in .NET, and allow end-users to write their games in Ruby. In the process, I picked up IronRuby as the vehicle of interaction.

Let’s start with my requirements: I should be able to write core functionality classes in C#, instantiate and extend them in IronRuby, and return them back to C# for consumption by the game engine. I also need strong typing of objects (despite the dynamic nature of scripting languages), and the ability to create delegates or functions inside my scripting language (and return those to C#, too).

You can view the source code on GitHub. This post summarizes my implementation, and the challenges I ran though.

RubyRunner Class

I created a core “RubyRunner” class which encapsulates all the Ruby-centric invocation. It contains a simple constructor, and a method public T Execute<T>(string script, IDictionary<string, object> parameters).

The first parameter (the script) is the easiest part. The second parameter contains any variables from C# that I want to expose to Ruby (this makes up my “API” which users write against).

One issue I ran into is a little error that can't convert Meltdown.Core.Area to Meltdown.Core.Area.

Huh?

It’s a strange kink in IronRuby; I can include my assembly to instantiate objects from it, but they don’t have the same type as the CLR equivalents (despite being loaded from the same assembly). The solution was to call load_assembly 'Meltdown.Core' in every single Ruby code. I encapsulated this into a Common.rb script which is auto-included in every invocation of Execute.

Here’s how that looks, as of writing:


public RubyRunner()
{
    if (File.Exists(@"Ruby\Common.rb"))
    {
        this.commonHeaderScript = File.ReadAllText(@"Ruby\Common.rb");
    }
}

public T Execute<T>(string script, IDictionary<string, object> parameters)
{
    var scope = engine.Runtime.CreateScope();

    foreach (var kvp in parameters)
    {
        scope.SetVariable(kvp.Key, kvp.Value);
    }

    var finalScript = string.Format("{0}\n{1}", this.commonHeaderScript, script);
    var toReturn = engine.Execute(finalScript, scope);

    if (toReturn is T)
    {
        return (T)toReturn;
    }
    else
    {
       throw new ArgumentException("Expected an instance of " + typeof(T).FullName + " but got " + toReturn.GetType().FullName + " instead.");
    }
}

Converting IronRuby Arrays to C# Lists

The second major hurdle is that IronRuby returns a RubyArray instance instead of an enumeration if I use typical Ruby list syntax, like this: $x = ['a', 17, 2.0 / 3].

To get around this, I created a ScriptHelper class. This class contains two methods: IsArray and ToList<T>. In both methods, I rely on IronRuby-specific implementation, and since the object input is dynamic, I can just call Ruby methods and get back what I want. Here’s how that looks:


public static List<T> ToList<T>(dynamic source)
{
    var found = new List<T>();
    for (int i = 0; i < source.Count; i++)
    {
        object next = source[i];
        found.Add(GetAsType<T>(next));
    }
    
    return found;
}

public static bool IsArray(dynamic source) {
    return source.GetType().Name == "RubyArray";
}

This allows me to write “Ruby-like” code without worrying about types.

Returning Delegates/Functions

The last hurdle was related to functions; given a delegate or function type (like Action), how can I return an object which I can type to a delegate type?

The answer was surprisingly easy; I just need to return an instance of Proc from my Ruby code. Something like:


Proc.new {
    puts "Action invoked. Yay!"
}

Conclusion

Given my requirements, I achieved them, and have code that allows me to write very “Ruby-like” code. That’s great; I can leverage C# to take care of some of the leaky abstractions, and everything works.

I suggest you download and play with the full source code from GitHub. You can look at the ScriptRunner.Tests project to see working Ruby code coming back to C#.

Posted in Libraries, Wndows Forms | Tagged , | Leave a comment

ASP.NET MVC 4: Uncaught TypeError: Object [object Object] has no method ‘autocomplete’

I ran into this seemingly innocuous error in my MVC4 app:

Uncaught TypeError: Object [object Object] has no method 'autocomplete'

Googling mostly resulted in “you have multiple versions of jQuery referenced,” which was not my case.

How did I fix this?

  • Update jQuery: I had 1.7.1 running on my site. Auto-complete requires 1.8 or higher. Right-click on the solution, “Manage NuGet Packages …”, “Updates”, and update both jQuery and jQuery UI.
  • Use jQuery UI: Although I had the scripts specified in a bundle called jqueryui, they’re not rendered. So I added this line under the jQuery bundle rendering in _Layout.cshtml: @Scripts.Render("~/bundles/jqueryui")
  • Render the jQuery UI CSS: jQuery UI requires some CSS files to be included. They were bundled, but not rendered; so I rendered them by adding @Styles.Render("~/Content/themes/base/css") to my layout.

And that’s it! You’ll have to check that these bundles exist for you (see BundleConfig.cs) and have the required files included.

Posted in Libraries, Web | Tagged | 1 Comment

Powershell + InstallUtil: Unable to get installer types Error

While building a basic Powershell cmdlet using this tutorial, I ran into an error when trying to install the cmdlet with InstallUtil:

An exception occurred during the Install phase.
System.InvalidOperationException: Unable to get installer types in the D:SamplePowerShellProjectbinDebugMyCmdlets.dll assembly.
The inner exception System.Reflection.ReflectionTypeLoadException was thrown with the following error message: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..

Why did I run into this error? When building my solution in Visual Studio, I noticed that Add References didn’t have any references to the System.Management.Automation namespace. The usual solution, c/o Stack Overflow, is to find the right DLL in C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell.

In my case, I saw two subdirectories: v1.0 and 3.0. And to make it more confusing, my $PSVersionTable showed a version of 2.0!

The reason I saw this error is because I included the 3.0 version of the DLL instead of the 1.0 version. Once I switched the reference to the 1.0 version of the DLL, it installed without any issue.

Posted in Core .NET, Tools | Tagged , | Leave a comment

Deserializing to Dynamic with RestSharp

RestSharp is awesome. Go try it. I highly recommend it (it’s overall less code and simpler than WCF, at any rate).

Services may or may not provide a well-defined list of fields to you, the consumer, which doesn’t change. There are two design options with trade-offs:

  1. Wrapper Classes: Create wrapper classes that convert expected fields in the JSON to a simple C# object. (Eg. for twitter, create a class with CreatedAt and Text for tweets, which expects the API to send created_at and text back.)
  2. Dynamic Classes: Use the new DLR, don’t care about static typing and expecting fields at runtime. Take whatever you get, and expose it.

For the second option, you need to sort out how to make RestSharp deserialize to (in the case of Twitter tweets) List<dynamic>.

Assuming you already have this working with a wrapper class, you only need to make a couple of changes. First, add a handler with a deserializer, as per this gist:


namespace RestSharp.Deserializers
{
  public class DynamicJsonDeserializer : IDeserializer
  {
    public string RootElement { get; set; }
    public string Namespace { get; set; }
    public string DateFormat { get; set; }

    public T Deserialize<T>(IRestResponse response)
    {
      return JsonConvert.DeserializeObject<dynamic>(response.Content);
    }
  }
}

(You need JSON.NET for this.) When you build your RestClient instance, add the handler to it:


client.AddHandler("application/json", new DynamicJsonDeserializer());

Finally, deserialize it. The tricky part is deserializing. The DynamicJsonDeserializer class actually returns (in this case) a JArray instance. To convert that to List<dynamic>, you need to do this:


var response = client.Execute<JArray>(request).Data.ToObject<List<dynamic>>();

Et voila, you’re done! You now have a list of dynamic objects, and you can dynamically access their fields!

Posted in Libraries, Silverlight, Web, Wndows Forms, WPF | Tagged , | 2 Comments

Writing Automated Performance Tests

I recently found out how easy it is to see how much total RAM your .NET app uses: `GC.GetTotalMemory(false)`. This gives you a simple total number of bytes that your app is using.

Throwing this into the trace that outputs the game FPS every second, I noticed a repetitive workflow where my game’s RAM usage kept climbing, from around 10MB (baseline) to over 30MB!

Having a qualified, quantified problem (potentially unlimited growth of memory usage, i.e. a memory leak) I sat out to answer an important question: could I somehow write an automated test that would check if this workflow leaked memory?

The answer was a resounding yes. Using the very powerful Moq framework, I was able to rip out most external dependencies and isolate my workflow to two calls: a constructor and Initialize method on one of my Screen subclasses.

Once I did this, simply creating and disposing 10k objects and checking the memory usage (before and after) indicated whether the usage shot up. A small rise (10k? 100k?) was probably insignificant; in my case, I saw more than a 20MB increase in RAM usage.

Also, one key here is to run GC.GetTotalMemory(true). This forces the GC to collect anything immediately, which is slower, but necessary. Without it, we can’t tell if the memory increase is due to disposed objects that the GC didn’t get around to disposing yet.

The culprit? Appending event handlers in the constructor which should have been removed on subsequent calls to dispose (but weren’t).

The conclusion? Testing for memory leaks is not hard, and can be very useful under certain circumstances, provided you have enough infrastructure in place to mock out dependencies.

Posted in Core .NET, Silverlight, Wndows Forms, WPF | Tagged , | Leave a comment