Tuesday, April 26, 2011

Using Moles with DLR (dynamic)

As several people have found, Moles does not work well with DLR. Check Cameron’s post for this issue.

In order to make it work do the following:

  1. Go to folder C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\
  2. Backup files Microsoft.Moles.VsHost.exe.Config / Microsoft.Moles.VsHost.x86.exe.Config (depending on your application’s platform)
  3. Modify the starup element and set the useLegacyV2RuntimeActivationPolicy to false in the .config file.
  4. Modify the legacyCasPolicy element and set the enabled to false the .config file.
Microsoft.Moles.VsHost.x86.exe
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="false">
    <supportedRuntime version="v4.0" />
    <supportedRuntime version="v2.0.50727" />
  </startup>
  <runtime>
     <legacyCasPolicy enabled="false" />
  </runtime>
</configuration>

I haven’t done further testing on changing the use of legacy CAS Policy when using Moles & VS Test Framework.

Let me know how it works for you.

Moles and Linq to SQL: Mocking Linq to SQL Behavior

In recent years there’s been major investments in developing tools in order to provide good quality assurance features and incorporate industry practices into them.

TDD, DDD, Unit Testing, Continuous Integration, etc.

Microsoft has recently (not so recently actually :)) ship some very nice features to help us improve our code quality by allowing us to create better tests over units of code.

Unit testing is all about proving individual units of code (positive and negative testing). Since a great deal of software is not always designed with this “unit independence” in mind, it can be a challenge to isolate dependencies for every piece of source code (specially legacy code).

Moles is an Isolation Framework that mocks/emulates the behavior of our components and external libraries, even for private members. You could even mock how a particular System.* class object in .NET behaves (check Pex & Moles site in Microsoft Research).

The following is a Repository object that uses Linq to Sql Data Context internally and doesn't provide a simple way of decoupling database access from its behavior. It means we cannot unit test the following class without a SQL database.

Customer Repository
public class CustomerRepository
{
    public IList<Customer> GetCustomers()
    {
        using (var db = new AdventureWorksDataContext())
        {
            return db.Customers.ToList();
        }
    }

    public Customer GetCustomer(int id)
    {
        using (var db = new AdventureWorksDataContext())
        {
            return db.Customers.FirstOrDefault(c => c.CustomerID == id);
        }
    }
}

By using Moles, we could replace inner behavior of this class.

Note: This is White Box Testing, meaning you need to have access to internal implementation in order to know how to mock it.

Mocking with Moles

Download and install Moles.

  1. Add Mole Assemblies for the project hosting the previous class (or the code you wish to test)
  2. Add Mole Assembly for System.Data.Linq
  3. Add Mole Assembly for System.Core

Check this tutorial about Pex & Moles for more information about the previous steps.

The following code fragment unit test our GetCustomers method:

Overriding Enumeration
[TestMethod()]
[HostType("Moles")]
public void GetCustomersTest()
{
    System.Data.Linq.Moles.MTable<Customer>.AllInstances.GetEnumerator =
        tc =>
        {
            var mockCustomers = new List<Customer>()
            {
                new Customer() { FirstName = "Javier" },
                new Customer() { FirstName = "Jorge" },
                new Customer() { FirstName = "Dario" }
            };

            return mockCustomers.GetEnumerator();
        };

    CustomerRepository target = new CustomerRepository();
    var customers = target.GetCustomers();
    Assert.IsNotNull(customers);
    Assert.IsTrue(customers.Count == 3);
    Assert.AreEqual("Javier", customers[0].FirstName);
}

Check out the use of Moles to specify the behavior of enumeration for the Table<Customer> (Customers) that Linq to Sql Provider uses to execute the query in the database. In the previous code, we avoid querying data from database and return an in-memory list of customers.

When executing a lambda expression using Linq to Sql, the source Linq provider must interpret the query and then issue a command to the database.

In order to intercept the query and return mock results, we must override default behavior for the expression evaluation logic of the Linq Provider.

Overriding Expression Eval
[TestMethod()]
[HostType("Moles")]
public void GetCustomerTest()
{
    var expectedCustomer = new Customer() { FirstName = "Javier", CustomerID = 1 };

    System.Data.Linq.Moles.MTable<Customer>.AllInstances.ProviderSystemLinqIQueryableget =
        tc =>
        {
            var qp = new System.Linq.Moles.SIQueryProvider();
            qp.ExecuteExpression01(exp => expectedCustomer);
            return qp;
        };

    CustomerRepository target = new CustomerRepository();

    var actualCustomer = target.GetCustomer(expectedCustomer.CustomerID);
    Assert.IsNotNull(actualCustomer);
    Assert.AreEqual(expectedCustomer.CustomerID, actualCustomer.CustomerID);
    Assert.AreEqual(expectedCustomer.FirstName, actualCustomer.FirstName);
}

The previous mocking code returns a Mock QueryProvider that does not evaluate the expression, it simply returns the in-memory customer reference.

I encourage you that read more about Moles here.

PS: This cool framework intercepts any managed operation by creating a CLR Host for the application.

Monday, April 25, 2011

Visual Studio 2010 crashes with “Exception has been thrown by the target of an invocation”

If you haven´t installed Visual Studio 2010 SP1 yet and you’ve enabled automatic Windows Update, chances are you end up getting the following error when starting VS2010: Exception has been thrown by the target of an invocation.

There is a .NET 4 Framework in Windows update distributed recently that generates this conflict.

Solution: Install VS2010 Sp1.

Webcast MSDN: Parallel LINQ

Next Wednesday (April 27th) I will presenting Parallel LINQ and showing some not trivial stuff to optimize performance in parallel algorithms. Register here.

.NET Community Mexico City

I will be participating as an invited speaker in “Comunidad.NET” in Mexico City next Tuesday (April 26th). My presentation will be focusing code quality using Visual Studio Tools.

Agenda:

  1. Code Metrics
  2. Code Analysis
  3. Profiling
  4. IntelliTrace
  5. Pex & Moles

You can get more info from Raul’s blog.

Tuesday, April 12, 2011

Async C# 5: Using Async Pattern with WCF and Silverlight

Sometime ago I published a way to use WCF service with the new Async Pattern in C#. The problem is that this approach won’t work with Silverlight. More specifically, TaskFactory is not available in Silverlight.

So.. here is one solution (it does not provide full functionality as in TaskFactory, but you can manage 90% of use cases):

MyTaskFactory
public static class MyTaskFactory
{
    public static Task<TResult> FromAsync<TResult>(
        IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
    {
        var completionSource = new TaskCompletionSource<TResult>();
        if (asyncResult.IsCompleted)
        {
            completionSource.TrySetResult(asyncResult, endMethod);
        }
        else
        {
            System.Threading.ThreadPool.RegisterWaitForSingleObject(
                asyncResult.AsyncWaitHandle,
                (state, timeOut) =>
                {
                    completionSource.TrySetResult(asyncResult, endMethod);
                }, null, -1, true);
        }

        return completionSource.Task;
    }

    static void TrySetResult<TResult>(
        this TaskCompletionSource<TResult> completionSource,
        IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
    {
        try
        {
            var result = endMethod(asyncResult);
            completionSource.TrySetResult(result);
        }
        catch (OperationCanceledException)
        {
            completionSource.TrySetCanceled();
        }
        catch (Exception genericException)
        {
            completionSource.TrySetException(genericException);
        }
    }
}

The previous code fragment defines a helper method that behaves similar to TaskFactory.

Usage example:

Usage:
var client = new MyServiceClient();
// EchoTaskAsync is an extension method
var result = await client.EchoTaskAsync("zzzz");

And here is the service extension for MyServiceClient (Note that I use the service interface contract instead of the ClientBase<> as parameter since we need access to Begin/End methods):

Service Async Extensions
public static class ServiceExtensions
{
    public static Task<string> EchoTaskAsync(
        this IMyService client, string text)
    {
        return MyTaskFactory.FromAsync<string>(
            client.BeginEcho(text, null, null),
            ar => client.EndEcho(ar));
    }
}

Try it and let me know if it works for you..

Sunday, April 10, 2011

We are recruiting..

We are looking for smart and young .NET software developers, passionate about technology for our Mexico City office. If your are interested send us an email with your CV to rrhh@lagash.com specifying you are interested in Mexico City positions.

Thanks!