OdeToCode IC Logo

Make the JavaScript Test Pass

Thursday, June 17, 2010 by K. Scott Allen

Add code on the commented line:

var f = function () {       
    var value = // ???
    return f.sum = (f.sum || 0) + value;
}

... to make the following QUnit test pass:

test("Running sum", function () {

    equals(f(3), 3);
    equals(f(3), 6);
    equals(f(4), 10);

    jQuery([1, 2, 3]).each(f);
    equals(f(0), 16);

});

Possible Answer

It's a goofy scenario, but one possible solution uses a technique you'll see frequently inside today's JavaScript libraries. First, we'll need to use the implicit arguments parameter inside the function f, and take (pop) just the last value. This would be trivially easy if the arguments parameter was an array, but arguments doesn't have any of the Array methods like pop, push, and slice. However, we can still use Array's pop method like this:

var value = Array().pop.call(arguments);

... or ...

var value = Array.prototype.pop.call(arguments);

... or ...

var value = [].pop.call(arguments);

When Your ASP.NET MVC Custom Error Doesn't Render...

Wednesday, June 16, 2010 by K. Scott Allen

The so-called Yellow Screen of DeathYou've put [HandleError] on your controller and you've set <customErrors mode="On"> in the web.config file. So why do you still see the yellow screen of death?

I've heard various wrong explanations for this phenomena, including "it only works under IIS" and "it only works in release mode". But the custom error view does work in debug mode and it does work with the Visual Studio WebDev web server. I think the most common reason for the error view not to display is because the error view throws an uncaught exception.

The first place to check when the error view doesn't render is in the error view itself. Make sure there isn't any code that might dereference a null reference, for instance, and run with debugging enabled to make sure.

Testability &amp; Entity Framework 4.0

Tuesday, June 15, 2010 by K. Scott Allen

This white paper describes and demonstrates how to write testable code with the ADO.NET Entity Framework 4.0 and Visual Studio 2010. This paper does not try to focus on a specific testing methodology, like test-driven design (TDD) or behavior-driven design (BDD). Instead this paper will focus on how to write code that uses the ADO.NET Entity Framework yet remains easy to isolate and test in an automated fashion. We’ll look at common design patterns that facilitate testing in data access scenarios and see how to apply those patterns when using the framework. We’ll also look at specific features of the framework to see how those features can work in testable code.

Read the entire paper on MSDN.

Visual Studio 2010 JavaScript Intellisense Behavior

Monday, June 14, 2010 by K. Scott Allen

JavaScript Intellisense

After I installed Visual Studio 2010 I was having a difficult time editing .js files in Visual Studio. I habitually type the "(" character as soon as the function I want to call is highlighted in the Intellisense window, but in 2010 this behavior was no longer auto-completing the function name.

At first I thought this behavior was due to the new "suggestion mode" in Intellisense, but no amount of toggling with CTRL+ALT+SPACE would bring back the auto-complete behavior.

It turns out the two Intellisense modes (completion mode and suggestion mode) are not included for every editor ("JScript" being a notable omission). After some digging I found I could change this behavior by going to Tools -> Options -> Text Editor -> JScript -> Miscellaneous and unchecking the "Only use Tab or Enter to complete" option.

Hope that helps.

Repositories and the Save Method

Sunday, June 13, 2010 by K. Scott Allen

One of the questions I've been getting lately goes like this:

Should a Repository class have a Save method?

And the standard answer:

It depends.

It's hard to keep track of all the different approaches to implementing the repository pattern these days, but I assume when someone asks me this type of question they are thinking of using code like this:

var employee = new Employee();
employeeRepository.Save(employee);

var account = new Account();
accountRepository.Save(account);

This style always strikes me as odd. It looks like code that wants to move away from an active record approach, but the code hasn't quite reached escape velocity. That's not to say the approach doesn't work. I can think of a couple scenarios where this approach can work well:

  • Applications using a single screen to edit each entity type (straight up CRUD).
  • Applications using the concept of aggregate roots from domain-driven design.

In other scenarios I think this approach only creates additional complications in sharing connections, transaction management, and maintaining entity identities. That's why I expect most repositories to work in conjunction with a unit of work object.

var employee = new Employee();
employeeRepository.Add(employee);

var account = new Account();
accountRepository.Add(account);

uow.Commit();

It's a small difference in code, but a considerable difference in philosophy. No entities are persisted until the unit of work commits. Behind the scenes, each repository working inside the same logical transaction is associated with the same unit of work. This approach simplifies the issues revolving around connections, transactions, and identity. 

The Grand Unified Framework Theory

Tuesday, May 4, 2010 by K. Scott Allen

Tom Janssens left a comment:

What still bugs me is that we do not have a unified pattern for all .net dev (using modelbinders and icommand for example...)

But, Tom – we are pretty close. At least as close as we should be, I think. With .NET there are plenty of low level patterns we can reuse regardless of the application platform or architecture. Stuff like:

  • Asynchronous programming with events or the TPL.
  • Object queries with LINQ.
  • Resource management with IDispose.

 

At a higher level, XAML {Binding} and friends are taking over client-side development. WPF runs on the desktop, while Silverlight runs in the browser, on phones, and on the desktop, too. The only formality left for total unification is the merge of Silverlight and WPF into a single product.

On the server side things are different, but maybe not as different as they first seem. Take, for example, the following method:

public int Create(Employee newEmployee)
{
    // ....
    return newEmployee.Id;
}

This method might belong to an ASP.NET MVC controller, or it might belong to a WFC web service. We can’t really tell without more context. If the method belongs to a controller, than a model binder will go out and search the HTTP payload for information it can use to put together an Employee. If the method belongs to a service than a serializer will use information gathered from the payload to form an Employee. Underneath the covers one recognizes the soap:mustUnderstand attribute and one doesn’t, but there isn’t a significant difference in the programming model.

And I think this is about as far as we should go. The “one size fits all” framework never fits anyone well. 

 

onesizefitsall

What&rsquo;s Wrong With This Code (#25)

Monday, May 3, 2010 by K. Scott Allen

The goal: create an extension method that will make it easy to create FormCollection objects. The method is a helper for unit testing ASP.NET MVC code.

public static FormCollection ToFormCollection(this object data)
{
    var namesAndValues =
        data.GetType()
            .GetProperties()
            .WhereValueIsNotDefaultValue(data)
            .ToNameValueCollection(data);
    
    return new FormCollection(namesAndValues);
}

The extension method itself relies on a couple private extension methods:

static IEnumerable<PropertyInfo> WhereValueIsNotDefaultValue(
    this IEnumerable<PropertyInfo> properties, object source)
{
    foreach(var p in properties)
    {
        var value = p.GetValue(source, null);
        if(value != (p.PropertyType.IsValueType ? 
                     Activator.CreateInstance(p.PropertyType)
                     : null))
        {
            yield return p;
        }
    }
}

static NameValueCollection ToNameValueCollection(
    this IEnumerable<PropertyInfo> properties, object source)
{
    return properties.Aggregate(
            new NameValueCollection(),
            (nvc,pi) =>
                {
                    var value = pi.GetValue(source, null);
                    nvc.Add(pi.Name, value.ToString());
                    return nvc;
                });
}

The code mostly works. This test passes:

public void should_copy_property_values()
{
    var expectedName = "Scott";
    var expectedHireDate = new DateTime(2010, 1, 1);

    var data = new Employee
    {
        Name = expectedName,
        HireDate = expectedHireDate
    }.ToFormCollection();

    Assert.IsTrue(data["Name"] == expectedName);
    Assert.IsTrue(data["HireDate"] == expectedHireDate.ToString());
}

However, the helper should not put entries in the FormCollection for properties holding a default value, and this test fails:

public void should_not_copy_default_values()
{
    var data = new Employee
    {
        Name = "",
        HireDate = DateTime.Now
    }.ToFormCollection();

    Assert.IsNull(data["Tags"]);
    Assert.IsNull(data["Id"]);
}

Employee is defined as:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime HireDate { get; set; }
    public string Tags { get; set; }
}

Hint: the first assert passes – it’s the assert on data[“Id”] that fails.