Thursday, November 17, 2011

TFS Build 2010: BuildNumber and DropLocation

Automatic Builds for Application Release is a current practice in every major development factory nowadays.

Using Team Foundation Server Build 2010 to accomplish this offers many opportunities to improve quality of your releases.

The following approach allow us to generate build drop folders including the BuildNumber and the Changeset or Label provided. Using this procedure we can quickly identify the generated binaries in the Drop Server with the corresponding Version.

  1. Branch the DefaultTemplate.xaml and renamed it with CustomDefaultTemplate.xaml

image

  1. Open it for edit (check out)
  2. Go to the Set Drop Location Activity and edit the DropLocation property.

image

  1. Write the following expression:

BuildDetail.DropLocationRoot + "\" + BuildDetail.BuildDefinition.Name + "\" + If(String.IsNullOrWhiteSpace(GetVersion), BuildDetail.SourceGetVersion, GetVersion) + "_" + BuildDetail.BuildNumber

  1. Check in the branched template.
  2. Now create a build definition named TestBuildForDev using the new template.

The previous expression sets the DropLocation with the following format: (ChangesetNumber|LabelName)_BuildName_BuildNumber

The first part of the folder name will be the changeset number or the label name (if triggered using labels). Folder names will be generated as following:

  1. C1850_TestBuildForDev_20111117.1 (changesets start with letter C)
  2. LLabelname_TestBuildForDev_20111117.1 (labels start with letter L)

Try launching a build from a Changeset and from a Label. You can specify a Label in the GetVersion parameter in the Queue new Build Wizard, going to the Parameters tab (for labels add the “L” prefix):

image

Evento Gratuito de Arquitectura / Architecture Event

El próximo 29 de noviembre voy a participar como orador en Microsoft en este evento gratuito sobre Herramientas de desarrollo y patrones de Arquitectura. Vamos a tomar varios temas interesantes sobre Arquitectura y construcción de Frameworks de Desarrollo.

Si están interesados en asistir, se pueden comunicar conmigo a través de un comentario en este blog.

English: Next November 29th I will be participating as a speaker in a free admission event at Microsoft México offices. We will be discussing very interesting topics about Architecture and the development of Technical Frameworks.

image

Sunday, May 22, 2011

Load Test in Windows Azure with Visual Studio Test Agents

Tomorrow I will be presenting “Load Test in Windows Azure with Visual Studio Test Agents” on MSDN. Hope to see you there.

Register here.

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.