Keep in touch

Archive

Meta

My first conference at microsoft argentina

You can register for the event here. Thanks Miguel for this opportunity.

event details (spanish):

Towebs & MSDN lo invitan a conocer las herramientas más innovadoras para el desarrollo web en plataforma Windows. Las charlas, están orientadas a programadores y desarrolladores. Queremos brindarle la posibilidad de que sus sitios web se diferencien del resto. Para lograrlo lo invitamos a capacitarse en el uso de tecnologías de última generación como ASP.NET, AJAX y Silverlight.

Fecha: Jueves, 5 de Junio

Inicio

Presentación

Orador

14:00

Acreditación

14:30

Introducción a desarrollo web en .NET

Miguel Sáez

14:55

Acceso a Datos en .NET

Miguel Sáez & Pablo Listingart

15:40

Intervalo

16:00

Creando aplicaciones AJAX con ASP.NET

Brian Cardiff & Miguel Sáez

17:00

Creando aplicaciones RIA ( Rich Interface Applications)
con Silverlight

Martin Salias

17:30

Fin del evento

Slides and Source Code

SQL Server vs. Firefox?

sql-express-waiting-firefox.PNG

Improved argument matchers in Moq

The new feature encapsulated by MatcherAttibute in Moq allows developers to create quite easy argument matchers.

In a scenario with a Customer class and a IFooService:

public class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
    // …
}

public interface IFooService
{
    void Bar(Customer c);
}
 

If in a test you need an expectation on Bar method that stands for a Customer c where c.Age >= 18 you
needed to do something like this:

[Test]
public void Test1()
{
    var mock = new Mock<IFooService>(MockBehavior.Strict);
    mock.Expect(x => x.Bar(It.Is<Customer>(c => c.Age >= 18)));
    // …
}
 

but from now on, using the MatcherAttribute the same expectation could be written as follows:

[Test]
public void Test1()
{
    var mock = new Mock<IFooService>(MockBehavior.Strict);
    mock.Expect(x => x.Bar(GrownUp()));
    // …
}

[Matcher]
public static Customer GrownUp() { return null; }
public static bool GrownUp(Customer c)
{
    return c.Age >= 18;
}

Lets call the first GrownUp method as Matcher declaration, and the second Matcher implementation.

  • Matcher declaration must has return type Customer in order to allow the expectation to compile, and be applied the MatcherAttribute.
  • Matcher implementation is used in the actual match, receiving the Customer to be matched and returning the result of the match.
  • Matcher declaration is never executed by Moq, it is used to have clear syntax.

More arguments

Also you could have more arguments involved in the matching, just add the at the end of both declaration and implementation.
For example to match older than a certain age:

[Test]
public void Test1()
{
    var mock = new Mock<IFooService>(MockBehavior.Strict);
    mock.Expect(x => x.Bar(OlderThan(18)));
    // …
}

[Matcher]
public static Customer OlderThan(int minimumAge) { return null; }
public static bool OlderThan(Customer c, int minimumAge)
{
    return c.Age >= minimumAge;
}

Your own helper class

To reuse some matchers, you could define them in a separate a class instead of inside the fixture.

[Test]
public void Test1()
{
    var mock = new Mock<IFooService>(MockBehavior.Strict);
    mock.Expect(x => x.Bar(An.OlderThan(18)));
    // …
}

static class An
{
    [Matcher]
    public static Customer OlderThan(int minimumAge) { return null; }
    public static bool OlderThan(Customer c, int minimumAge)
    {
        return c.Age >= minimumAge;
    }
}
 

Non static method

Finally, the matchers declaration and implementation don’t need to be static. So you could have additional context of matching.
Although I suggest this last only in certain scenarios, for example, match enumeration of values:

[Test]
public void Test2()
{
    var mock = new Mock<IFooService>(MockBehavior.Strict);
    var names = new E(new [] { “John Doe”, “Brian Cardiff” });
    mock.Expect(x => x.Bar(names.Some()));

    // this will success
    // mock.Object.Bar(new Customer { Name = “Brian Cardiff” });

    // this will fail
    // mock.Object.Bar(new Customer { Name = “Sandy” });
}

public class E
{
    IEnumerable<string> names;
    public E(IEnumerable<string> names)
    {
        this.names = names;
    }

    [Matcher]
    public Customer Some() { return null; }
    public bool Some(Customer s)
    {
        return names.Contains(s.Name);
    }
}

Upgraded jQuery Tag Suggestions

Yesterday remy sharp update jQuert Tag Suggestions plugin a list of fixes can be found here.

The new features are really good:

  • Be able to use multi words tags by specifying the separator. (my contribution)
  • Added filtering to prevent already selected tags appearing in the suggestions.

Some plugins are really nice….

GuardQ: Guard class meets Linq

In the task of validating function arguments, usually a sealed class Guard is created. For example, if we want to validate for null value the usual code is:

    public sealed class Guard
    {
        public static void ArgumentNotNull(object val, string argName)
        {
            if (val == null)
                throw new ArgumentNullException(argName);
        }
    }
    public class Bank
    {
        public void Transfer(Account source, Account destination, decimal amount)
        {
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(destination, "destination");
            // TODO ... actual founds transfer
        }
    }

I never like to pass the parameter and it’s name in the same argument call, specially because while refactoring, the argName argument won’t be changed by default.

To eliminate that hack, we could use GuardQ (C# 3.0), which will be consumed, for the same example of above as:

    public sealed class GuardQ
    {
        public static void ArgumentNotNull<TResult>(Expression<Func<TResult>> expression)
        {
            if (expression.Compile().Invoke() == null)
            {
                PrettyPrinter printer = new PrettyPrinter();
                string argName = printer.Print(expression.Body);
                throw new ArgumentNullException(argName);
            }
        }
    }
    public class Bank
    {
        public void Transfer(Account source, Account destination, decimal amount)
        {
            GuardQ.ArgumentNotNull(() => source);
            GuardQ.ArgumentNotNull(() => destination);
            // TODO ... actual founds transfer
        }
    }

Only one argument per validation: a lambda expression with no parameters and the parameter to validate in the body. From the expression’s body, using a kind of ExpressionPrinter we could get the argument name: hack removed!. And refactoring is 100% supported.

Since the ToString method of the body of () => source, would return something like “value(GuardQ.Tests.Demo+Bank+<>c__DisplayClass0).source”, I start to develop a PrettyPrinter, to get a string representation of the expression that the user input in the source code (currently, don’t printing the context nodes).In the following weeks some additions will appear, and a non-spike code would be available in MoQ.

Current source: https://moq.googlecode.com/svn/spikes/GuardQ/

Download Source Code Snapshot

Installing .NET Framework 3.5

Nice… of course I told it to ignore it ;-).

installing_net35

Build Xml files in Ruby

If you have to generate xml in ruby I suggest take a look at builder gems. It has really little overhead to generate xml. Take a look to this example:

require 'Builder'

xm = Builder::XmlMarkup.new( :target => $stdout , :indent => 2 )
xm.instruct!
xm.people do | p |
  p.person(:firstname => "brian", :lastname => "cardiff") do | a |
    a.cdata!("it's me!")
  end
  p.person(:firstname => "ary", :lastname => "borenszweig")
end

will print in stdout

<people>
  <person lastname="cardiff" firstname="brian">
    <!--[CDATA[it's me!]]–>
  </person>
  <person lastname=”borenszweig” firstname=”ary” />
</people>

the target parameter could be a string or file (or anything with << method).

self.begin

OK, let see how this evolves. Hope to start blogging regarding my main interests topics (list here).