Tom 04:35, 1 June 2010

I will be presenting at the Avans Hogeschool Tilburg this week and wanted to apply a trick I first saw by Juval Lowy in his architecture master class: starting Visual Studio from within the presentation directly. Why would you want to do this? Because it looks cool of course!

After a bit of Googling around I found it all is very, very easy to do. Just download a suitable VS2010 / VS2008 icon. As I was lazy I went straight to Google images and found these:

VS2008 VS2010

I cleaned up the 2010 icon a bit in Paint as I will be presenting in VS2010 this week, if you know where to get the proper icons drop a line in the comments.

 

Now, in PowerPoint paste any of the icons. Select the image and go to Insert, Action => Run program.

Insert the path to your devenv.exe, typically this will be "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" on a Windows 7 machine.

This will start VS2010 but you can (and should) add the path to the solution file.

 

Like it, comments? Find the comment button and let me know!

Tom 06:56, 1 December 2009

Manipulating the DOM with Firebug

Currently I"m working more and more with jQuery and JavaScript to get behavior into my pages. This was quite painful in the beginning as I was depended a bit too much on alert"('this happens!').

But I guess this is where you get started and then find out about the excellent firebug. With the console you can then fire your JavaScript and jQuery commands to the page like so:

 

 image

 

I'm querying on of Holland's main news sites for their logo. Firebug conveniently comes up with the link to the element and when clicked it will show where it's located on the page.

This is all nice but let's change the boring logo of nu.nl to that of our own!

Easy enough, just use the following to change the picture in the page:

$('#sidemenu a img').attr('src', 'http://www.tjsolutions.nl/themes/tjs/images/headerbg.jpg')

 

 

image

 

But changing the elements in a page is just the beginning. You can just as easily add new functionality by binding a click event handler to one or more elements in the page.

 

Viewing registered events

You can also use the console to inspect what events are registered to an element on the page. All you need to do is use this syntax:

$(selector).data("events");

 

When we try that on the last input (randomly chosen) you get an overview of all the events bound (in this case only one).

 

events

 

If you the click on the object and hover over "function" you'll end up with the code itself:

 

function

 

This is a very neat trick that I wish I had stumbled upon earlier. Hope it helps.

Tom 08:56, 17 November 2009

I was pointed to the Passionate programmer by one of the blog posts at Los Techies. I'm about a third through the book and so far it has been a real joy to read!

It's full of good tips on how to alter your behavior to become something better as a programmer. I'm probably going to write some posts on what I've done with the various "act on it!", but in the meantime, go get it and start reading!

Tom 07:01, 16 November 2009

Just a quick update on my previous posting following one of the comments made by den Ben

 

just out of curiosity... why wouldn't you
dispatcher.Add<SaveDocumentRequest>(s =>
{
s.Document = document;
s.UserID = userID;
});

 

He's absolutely right. Using a Func forced me to (mis)use the params keyword as you are not allowed  to use the above syntax with the old code:

public virtual IDispatcher Add<TRequestType>(params Func<TRequestType, object>[] funcs)
    where TRequestType : Request, new()
{
    TRequestType request = new TRequestType();
    foreach (var func in funcs)
    {
        func.Invoke(request);
    }
    AddRequest(request, false);
    return this;
}

I actually had noticed the code not using the return value by the func but disregarded it as I was a bit too happy with the "elegance" of my inital solution.

But I think (and I think you'll agree) that using an Action is much cleaner here:

public virtual IDispatcher Add<TRequestType>(Action<TRequestType> action)
    where TRequestType : Request, new()
{
    TRequestType request = new TRequestType();
    action(request);
    AddRequest(request, false);
    return this;
}

 

Thanks den Ben!

Tom 08:14, 12 November 2009

One of my colleagues asked me today if I could write a utility function that would make his life more easy.

The objective was to call a stored procedure n-times for every item in a list. Of course some of the properties on every item had to be mapped to parameters in the stored procedure.

 

The desired syntax would be something like:

builder.SetStoredProcedureNameTo( " some sproc name ")
        .Execute ( customerList ,
            (s,t) => s.AddParameterWIthValue( parameterName, t.PROPERTY_NAME_1) ,
            (s,t) => s.AddParameterWIthValue( parameterName, t.PROPERTY_NAME_2) ,
             (s,t) => s.AddParameterWIthValue( parameterName, t.PROPERTY_NAME_3)
      );

 

I already have a fluent wrapper class to make our ADO.Net a bit more friendly, the interface looks like:

public interface ICustomSqlCommandBuilder
{
    ICustomSqlCommandBuilder SetStoredProcedureNameTo(string storedProcedureName);
    ICustomSqlCommandBuilder AddParameterWithValue(string parameterNameInDatabase, object value);
    ICustomSqlCommandBuilder AddExlicitOutputIntParameterToTheCommandFor(string parameterName);
    ICustomSqlCommandBuilder AddExlicitOutputDateTimeParameterToTheCommandFor(string parameterName);

    IList<TReturnType> ExecuteReaderFor<TReturnType>()
        where TReturnType : new();
}

Nothing special except for the ExecuteReaderFor<TReturnType>() but that's for another post.

 

Having the fluent interface on ICustomSqlCommandBuilder combined with the lambda magic explained in this post I came up with the following signature:

ICustomSqlCommandBuilder ExecuteScalarForThisList<T>(
    IList<T> list,
    params Action<ICustomSqlCommandBuilder, T>[] actionList);
The general idea is to apply
(s, t) => s.AddParameterWithValue("parameterName", t.PROPERTY_NAME)

to every property in the object<T> that needs to be mapped against a parameter in the stored procedure. Having the params allows us to map as many properties to parameters in the stored procedure as we like. If we then loop through all the items in the list first and apply all actions in the actionList per item, we can then call ExecuteScalar on the stored procedure.

foreach (var item in list)
{
    foreach (var action in actionList)
    {
        action.Invoke(this, item);
    }
    var result = sqlCommand.ExecuteScalar();
    sqlCommand.Parameters.Clear();
}

Now, another requirement was to wrap it in a transaction and also to have the verification of the result a bit more flexible. All in all not too complicated, just a matter of introducing another Action:

public ICustomSqlCommandBuilder ExecuteScalarForThisList<T>(
    IList<T> list, 
    Action<object> verify, 
    params Action<ICustomSqlCommandBuilder, T>[] actionList)
{
    sqlCommand.Connection.Open();
    SqlTransaction transaction = sqlCommand.Connection.BeginTransaction();
    sqlCommand.Transaction = transaction;

    try
    {
        foreach (var item in list)
        {
            foreach (var action in actionList)
            {
                action.Invoke(this, item);
            }
            var result = sqlCommand.ExecuteScalar();
            verify(result);
            sqlCommand.Parameters.Clear();
        }
        transaction.Commit();
    }
    catch (SqlException)
    {
        transaction.Rollback();
        throw;
    }
    catch (Exception)
    {
        transaction.Rollback();
        throw;
    }
    return this;
}

 

Including a bit of exceptionally brittle exception handling and calling the stored procedure on a list of Customers now resolves to:

Action<object> resultConstraint = result =>
{
    if (result != null)
    {
        if ((int)result > 1000)
        {
            throw new Exception("result should be less than 1000!");
        }
    }
};

builder
    .SetStoredProcedureNameTo("sens_sp_modifyCustomerIncome")
    .ExecuteScalarForThisList(
        customerList, 
        resultConstraint,
        (s, t) => s.AddParameterWithValue("id", t.ID),
        (s, t) => s.AddParameterWithValue("income", t.Income)
        //etc for the rest of the properties
    );
I really, really like this syntax!
Tom 05:54, 31 October 2009

At my current project we are using a dispatcher class to batch requests to our WCF layer based on the Request/Response Service Layer created by Davy Brion. Once you call the Get<TResponseType>() on the dispatcher the WCF layer starts working on the requests one by one and return them in one roundtrip.

Adding requests to the dispatcher is easy:

var saveDocumentRequest = new SaveDocumentRequest();
var getRemainingDocuments = new GetRemainingDocumentsRequest();
dispatcher.Add(saveDocumentRequest, getRemainingDocuments);

 

Where the signature of the Add method in Dispatcher is like;

public void Add(params Request[] requests)

Although this syntax is not bad, it feels like so much like code from last month: not very sexy. Wouldn't be more fun if we could spice it up a bit using generics and a bit of Func?

I'd love to get rid of instantiating a variable just for the sake of adding it to my dispatcher. After a bit of fiddling around with my unit tests I came up with the following solution.

What I want is to call the Add method in a generic way and set the parameters on my request object inline, using a Func. This is best illustrated with a test:

[Test]
public void can_assign_value_using_a_func_in_a_generic_method_call()
{
    Guid id = Guid.NewGuid();
    var dispatcher = new Dispatcher();
    
    dispatcher.Add<GetPersonsRequest>(s => s.ID = id);
    
    
    //disregard ugly cast; this is only for test purposes
    var request = (GetPersonsRequest)dispatcher.Requests.First();
    request.ID.ShouldEqual(id);
}
Where the Request and dispatcher have these signatures:
public class GetPersonsRequest:Request
{
    public Guid ID { get; set; }
}

public class Dispatcher
{
    public Dispatcher()
    {
        Requests = new List<Request>();
    }

    public void Add<TRequestType>(params Func<TRequestType, object>[] funcs)
where TRequestType : Request, new() { var request = new TRequestType(); foreach (var func in funcs) { func(request); } Requests.Add(request); } public IList<Request> Requests { get; set; } }

I can now set only property in my Request type, what if it has more properties that need to be set? Just introduce the infamous params to the method signature like so:

public void Add<TRequestType>(params Func<TRequestType, object>[] funcs) 
where TRequestType:Request, new() { var request = new TRequestType(); foreach (var func in funcs) { func(request); } Requests.Add(request); }

And again the test:

[Test]
public void can_assign_two_values_using_a_func_in_a_generic_method_call()
{
    var dispatcher = new Dispatcher();
    Guid id = Guid.NewGuid();

    dispatcher.Add<GetPersonsRequest>(s => s.ID = id, t=> t.GetAllDetails = true);

    //disregard ugly cast; this is only for test purposes
    var request = (GetPersonsRequest)dispatcher.Requests.First();
    request.ID.ShouldEqual(id);
    request.GetAllDetails.ShouldBeTrue();
}

When we change the return type of the Add method to the dispatcher itself, we can then use a fluent interface to get a very friendly syntax  for making calls:

 

//input parameters for first request
var document = new object();
var userID = Guid.NewGuid();

//input parameters for second request
var dossierID = Guid.NewGuid();

dispatcher
    .Add<SaveDocumentRequest>(s => s.Document = document, t => t.UserID = userID)
    .Add<GetZaakRequest>(s => s.DossierId = dossierID);

I really like the fact that I don't have to initialize a variable and still have access to all the properties in the request object..

Tom 06:15, 20 October 2009

I'm always trying to improve on my speed in development. Yesterday I noticed Udi Dahan using the In-proc test feature of TestDriven.Net in one of his presentations at the SDC - Netherlands, like so:

 

image

 

 

I had seen this option before but as it was hidden in some submenu and the regular test method worked just fine, there seemed no benefit in using it.

 

However.

Running your tests using In-proc makes for about 25% speed difference on average! To me, this is very noticeable but the function is hidden in some context submenu, hence still slow to use. After a bit of emailing with TestDriven.Net, it appears that you can run In-proc using the DTE runner.

To map it to a shortcut key, use the following screenshot:

 

image

Tom 02:23, 20 October 2009

I have converted quite a few to Resharper recently. I'm quite the addict myself and I can't see myself using Visual Studio productively without it anymore.

Resharper does have a learning curve however since there are just because of the sheer amount of enhancements it brings to working with VS.

 

To get you up to speed using Resharper, perform these settings in Visual studio after installing:
Within Visual studio: ALT - R - O => intellisense, completion behavior =>
Automatically show completion list in 0 milliseconds
"Check" all options except Case-sensitive prefix matching
Finally, "Only those that are at least": set this to 1

 

You can watch the following screencasts:
- James Kovacs screencasts on Resharper
- My own MVP coding demo using Resharper and Rhino mocks
- Ayende demoing Rhino mocks

(pls note that you'll need the Camtasia TSCC codec to view the last two)

 

You can use keyjedi to display the shortcuts used when someone else is looking over your shoulder. This will greatly enhance the introduction within your team. This only works on x86 systems, I have compiled the code into an x64 assembly that works on my win7 machine, let me know if you need it.

Lastly, have the developers print out the Resharper keymapping (in plastic cover preferably, in case of any coffee, tea and all that :-) )

 

If you have any further questions, please let me know.

Tijmen 09:53, 15 October 2009

One of my machines refused to install updates to the .NET Framework 3.5 sp1, both through auto-update and when installing manually. I finally fixed it by using Aaron Stebner's .NET framework cleanup tool and re-installing .NET. This tool radically removes all versions of the .NET framework, including IIS artefacts, registry entries, the works. I found this tool through a post on raymond.cc.

Note that this tool should probably not be the first thing to try; uninstalling and re-installing the .NET framework versions would probably a safer bet to try first.

Tijmen 07:36, 1 October 2009
Just a quick note: there is an update out for the latest .NET framework version, that addresses issues with ASP.NET dynamic data. Amongst others, the site will not display foreign key fields in a one-to-one relationship. This KB article contains all the download links to the various versions.
Not a new issue by any means (the fix is dated January 2009), but good to know nonetheless.