Wednesday 30 June 2010

T4 error: Compiling transformation: Invalid token 'this' in class, struct, or interface member

If you have a T4 Template .tt file that throws a weird Compiling transformation: Invalid token 'this' in class, struct, or interface member error that seems to come out of nowhere, try to delete extraneous spaces.

In my case, I has copied/pasted the .tt content from a web page and I was trying to understand why it wouldn't work. I right clicked on the source, went to Advanced, chose Convert all spaces to tabs, then back to Convert all tabs to spaces. Then it worked. I guess some white spaces where not really spaces or some other formatting issue.

If you don't have the options when you right click, it might be that they are features of the Tangible T4 Editor.

Sunday 20 June 2010

The Warrior's Apprentice by Lois McMaster Bujold

The word that I think best describes the book is "naive". That's not necessarily a bad thing; people have been hooked by naive stories since forever. Isaac Asimov had some very simplistic plots where everything was going well for the main character. The Harry Potter series was also what I could call naive; didn't hurt it much. From the same perspective I can say that The Vorkosigan Saga, which now spans about twenty novels and short stories, had its share of success (and three Hugo awards) no matter what the writing style. That writing style should have evolved anyhow as each book was written.

Back to The Warrior's Apprentice, though. It's about a kid, son of royalty on his home backward planet, who singlehandedly buys a spaceship, runs a blockade, creates a mercenary force, fools everybody that he is older, is smarter than anyone and also foils a ploy to destroy his father. And the drama is, as teenagers go, that he doesn't get the girl. Now see why I call it naive?

However, I am sure I would have gobbled the whole series up when I was fifteen, so, even if I have decided to not read the other books in the series, it depends on what your tastes are. The Warrior's Apprentice is an easy to read, easy to follow, shortish book. As a travel book I guess it would be decent.

Thursday 17 June 2010

Working with the T4

Update: Thanks to Tim Fischer from Tangible, I got to solve all the problems described in the post below using VolatileAssembly and macros like $(SolutionDir) or $(ProjectDir).

When T4 (Text Template Transformation Toolkit) appeared as a third party toolkit that you could install on Visual Studio 2008, I thought to myself that it is a cool concept, but I didn't get to actually use it. Now it is included in Visual Studio 2010 and I had the opportunity to use it in a project.

The idea is to automatically create code classes and other files directly in Visual Studio, integrated so that the files are generated when saving the template. All in all a wonderful idea... but it doesn't work. Well, I may be exagerating a bit, but my beginning experience has been offputting. I did manage to solve all the problems, though, and this is what this blog post is about.

First of all, there is the issue of intellisense. I am using ReSharper with my Visual Studio, so the expectations for the computer knowing what I am doing are pretty high. In the .tt (the default extension for T4) files you don't have any. The solution for this is to use the Tangible T4 editor (I think they were going for a fifth T here) that comes as a Visual Studio addon for VS2008 and VS2010. Fortunately, there is a free version. Unfortunately, it doesn't do intellisense on your own libraries unless you buy the priced one. Also, the intellisense is years behind the one provided by ReSharper or even the default Visual Studio one and the actions one can do automatically on code in a T4 template are pretty limited.

The second problem was when trying to link to an assembly using a relative path to the .tt file. The Assembly directive supports either the name of an assembly loaded in the GAC or a rooted path. Fortunately, the VS2010 version of the T4 engine supports macros like $(SolutionDir). I don't know if it supports all Visual Studio build macros in the link, but the path ones are certainly there.

Here is how you use it. Instead of

<#@ Assembly Name="Siderite.Contract.dll" #>
use

<#@ Assembly Name="$(SolutionDir)/Assemblies/Siderite.Contract.dll" #>


The third problem was that using an assembly directive locked the assembly used until you either reopened the solution or renamed the assembly file. That proved very limiting when using assemblies that needed compiling in the same solution.

This can be solved by installing the T4 Toolbox and using the VolatileAssembly directive. Actually, on the link above from Oleg Sych you can also find a bit advising using the T4 toolbox VolatileAssembly directive in the Assembly Locking section.

Here is how you use it. Instead of

<#@ Assembly Name="$(SolutionDir)/Assemblies/Siderite.Contract.dll" #>
use

<#@ VolatileAssembly
processor="T4Toolbox.VolatileAssemblyProcessor"
name="$(SolutionDir)/Assemblies/Siderite.Contract.dll" #>
As you can see you need to specify the processor (the VolatileAssemblyProcessor would have been installed by the T4 Toolbox) and you can use macros to get to a relative rooted path.

So thanks to the eforts of Oleg and Tim here, we can actually use T4. It would have been terribly akward to work with the solution in the obsolete section below. The Tangible guys have a learning T4 section on their site as well. I guess that using the resources there would have spared me from a day and a half wasted on this.

The following is obsolete due to the solutions described above, but it is still an informative read and may provide solutions for similar problems.

Click to expand.


Tips And Tricks:
Problem: the T4 generated file has some unexplained empty lines before the start of the text.
Solution: Remove any spaces from the end of lines. Amazingly so, some white space at the end of some of the lines were translated as empty lines in the resulting .tt.

Problem: The code is not aligned properly
Solution: Well, it should be obvious, but empty spaces before the T4 tags are translated as empty spaces in the resulting .tt file. In other words, stuff like <# ... should not be preceded by any indenting. It will make the template look a bit funny, but the resulting template will look ok. If you dislike the way the intending looks in the template, move the indent space in the tag, where it will be treated as empty space in the T4 code.

Wednesday 16 June 2010

WPF in Action with Visual Studio 2008

I've finally finished the book WPF in Action with Visual Studio 2008 by Arlen Feldman and Maxx Daymon. Simply put, it was a great book. Most of the programming books focus too much on structure, resulting in very comprehensive information, but giving one little in the way of actual work. WPF in Action is describing features while using them in a few applications that are built almost entirely out of code printed in the book. I think this is the second book any beginner in WPF should read, the first being one of those boring comprehensive ones :)

Book coverThe book goes from a brief history of Windows Forms and WPF to Hello World in part one, then to describing layouts, styles, triggers, events and animations in the second part. The third goes to create a wiki application using commands and binding, datatemplates, converters, triggers, validation, then custom controls and drawing (including 3D!). I am a big fan of the MVVM pattern, but I liked that in this book, while it got described, it didn't suffocate the other topics, getting only a small subchapter in the binding section. The fourth part explains navigation, XBAP, goes briefly through ClickOnce and Silverlight, then has a large chapter about printing (too large, I believe). The book finishes with transition effects, interoperability with Windows Forms and threading.

All in all I think it was a very nice read. The authors clearly have a lot of experience and are quite qualified to talk not only about the features in WPF, but also the gotchas and some of the problematic implementations or even bugs. The fourth part of the book was a bit of a bore, though. After a pretty heavy 3D drawing ending of part three, I get to read a whole lot about really boring stuff like printing. I am sure that when need arises, though, this is the first book I will open to see what they did.

Bottom line: First three chapters are a must read. Maybe skip the 3D drawing part the the end of part three. The fourth is optional. The authors themselves said that they intended to write something that could be used as a reference, and I think they succeeded. So read the table of contents and see which parts of WPF you are really interested in in those optional parts.

The WPF in Action with Visual Studio 2008 link goes to the publishers site, where you can download the source code and even read some sample chapters.

Thursday 10 June 2010

Fullmetal Alchemist manga ended

Edward and Alphonse Elric are two alchemist brothers searching for the legendary stone called the Philosopher's Stone The final chapter of the Fullmetal Alchemist story has been released today. Have the Elric brothers regained their bodies? Have they sacrificed everything in that Japanese way we so love? Did they get to yet another place filled with Nazis, turned vampire and got to be characters in an Uwe Boll movie? You will have to read the manga to find out! :) The good news it that following the link above you can do just that!

As you may know, the anime finished abruptly a while ago with the two brothers teleporting to our world in the middle of World War 2 and ended up in a ridiculous story. Luckily enough, the manga had none of that bullshit and continued on its merry way. Picking on that, another anime was started, Fullmetal Alchemist Brotherhood, which was supposed to delete from our memory the shame of the ending of the first anime. It is now pretty close to ending itself.

My opinion about the whole story is that it was a pretty imaginative concept, a kind of alchemic steampunk universe, filled with wonder, horror and fun stories. I hope you Read/watch it with just as much fun as I have.

Update 4th of July: The anime (Fullmetal Alchemist: Brotherhood) has also ended. It covered the exact same things as the manga this time.

I also forgot to mention that the story ends with a few loose ends: Al goes to explore the East and learn Alkahestry, accompanied by the two chimera men that want their original bodies back as well; Ed is going West, trying to learn as much as possible so that he can return and complete his brother's research and then help people together; Mrs Bradley is raising the last homunculus, Selim, as her son, trying to infuse him with love and make him a good person. These three threads can lead to a possible continuation of the Alchemist story. At least, I hope they do.

Tuesday 8 June 2010

Using the dynamic keyword to select behavior

I won't get into explaining in detail what the dynamic keyword does in .Net 4.0, enough to say that it is enabled by the DLR (Dynamic Language Runtime) and it allows an object to have a type determined at runtime, not at compile time. I will use this feature to select the appropriate method for a specific type.

I've long had this problem with the object oriented principles that stated that methods with different signatures should be chosen based on the type of their parameters, but if the type of the parameter was unknown at compile time (let's say it was boxed in an object type) the method executed was always the one with the object parameter:

void DoSomething(object o) {
Console.WriteLine("I'm an object");
}

void DoSomething(int o) {
Console.WriteLine("I'm an int");
}

void Test() {
int i=1;
object o=i;
DoSomething(i);
DoSomething(o);
}

The result of this would be "I'm an int" followed by "I'm an object".

Solutions for this range from having a type casting cascade (because the switch statement doesn't work with Type) or using a Dictionary<Type,Action> or even using reflection to get the method with a specific signature and execute it.

A typical OOP solution that is correct, but really cumbersome to use is the double dispatch pattern. You can read an interesting article about it here.

The worst thing about this is that o.GetType() is System.Int32. It's like it's mocking us (and not in a unit testing way either).

Here comes dynamic:

void DoSomething(object o) {
Console.WriteLine("I'm an object");
}

void DoSomething(int o) {
Console.WriteLine("I'm an int");
}

void Test() {
int i=1;
object o=i;
dynamic d=o;
DoSomething(i);
DoSomething(o);
DoSomething(d);
}

This will have the same result as before followed by "I'm an int"! Pay attention to the fact that I did not set the value of d to the int, but to the object! What is ever cooler is that one can use only the methods that make sense, without the need of a general method that received a parameter of type object (unless, of course, you want to catch it and throw some meaningful error). No more casting insanity!

I use this technique to get an object that inherits from a base class, without knowing what the object is, then passing it to private methods that have the same name but different parameter types. All I have to do is cast my object to dynamic and pass it to the private method and the DLR does the rest for me.

I have not yet tested the performance aspect of this, but, considering that the DLR is the base for all dynamic languages in .Net like Ruby and Python, I bet it is faster than dictionaries with Actions in them.

So, to recap, if you ever want that a boxed object behave differently based on its true type, use myMethod((dynamic)obj) rather than myMethod(obj) and you are set.

Update: I have implemented this pattern in an application I am working on and I am very satisfied with it. I've created a separate assembly that adds the DynamicPatternAttribute and DynamicPatternIgnoreAttribute classes, which help decorate the methods I am using and also a PatternChecker class that can be used to check that there is a method implementation for each type inheriting from a specific base type. Here are some details on how it works.

First of all, we must define the purpose of such a pattern. As I said above, one can use it to specify behavior based on specific types that inherit from a base type. This can be desirable when the types in question cannot be changed to add new behavior. Even if they can be changed, it may not be desired to add a reference from the project containing our classes to the project containing the behavior. It is almost like defining static extension methods.

Then there are the elements:
  • The base class from which all classes that determine behavior inherit (object if nothing specific)
  • The routing method that receives at least a base class parameter
  • The behavior methods that have as a parameter the subclasses of the base type
  • The pattern implementation checker class


So far I've used it in the following way:
  • The new behavior is encapsulated in methods in a static class
  • The routing method receives as the first parameter the base type for the classes that should determine behavior
  • The only code in the routing method is calling the private behavior method(s) using the same parameters as itself, except the first which is cast to dynamic
  • The behavior methods usually are private methods having the same name as the routing methods, but ending in "handle"
  • The routing method is decorated with [DynamicPattern("nameOfTheBehaviorMethods")]
  • The routing method is decorated with [DynamicPatternIgnore(typeof(subClassToIgnore))] which tells the checker which classes do not need behavior implementations
  • The static class containing the pattern has a static constructor that calls a method to check the implementation of the pattern
  • The checker method is decorated with [Conditional("DEBUG")] so that it doesn't hinder the functionality of the program with slow reflection checks
  • The checker method calls PatternChecker.CheckImplementation(typeof(staticClass)) or PatternChecker.CheckImplementation(typeof(class).Assembly)


The PatternChecker class only checks if there is a method with the name specified in the DynamicPattern contructor for each of the subclasses of the base type of the first parameter in the routing method.

I hope you like this pattern. I certainly do. I leave you with an actual implementation example:

public static class RequestHandler
{

static RequestHandler()
{
checkDynamicPattern();
}

[Conditional("DEBUG")]
private static void checkDynamicPattern()
{
PatternChecker.CheckImplementation(typeof(RequestHandler));
}

[DynamicPattern("getObjectsHandle")]
[DynamicPatternIgnore(typeof(BaseDeleteRequest))]
[DynamicPatternIgnore(typeof(DeleteUsersRequest))]
[DynamicPatternIgnore(typeof(DeleteCategoriesRequest))]
[DynamicPatternIgnore(typeof(DeleteDataRequest))]
[DynamicPatternIgnore(typeof(DeleteApplicationsRequest))]
[DynamicPatternIgnore(typeof(GetEntityRequest))]
[DynamicPatternIgnore(typeof(BaseObjectActionRequest))]
[DynamicPatternIgnore(typeof(GetEntitiesRequest))]
[DynamicPatternIgnore(typeof(GetEntityByIdRequest))]
[DynamicPatternIgnore(typeof(BatchOperationRequest))]
public static BaseEntitiesResponse GetObjects(BaseRequest request, Coordinator coordinator)
{
return getObjectsHandle((dynamic)request, coordinator);
}

private static BaseEntitiesResponse getObjectsHandle(BaseRequest request, Coordinator coordinator)
{
throw new ArgumentException("Cannot find a suitable getObjects method for type of request " +
request.GetType());
}

private static BaseEntitiesResponse getObjectsHandle(GetApplicationRequest request,
Coordinator coordinator)
{
DataObject entity = coordinator.ApplicationManager.GetObject(request.Id,
request.IncludeOptions);
return getEntitiesResponse(entity);
}



Update: There is an wonderful unintended side-effect of the dynamic pattern when casting to generic types. Imagine you have a generic interface like ICustom<T> and you want to use the standard model of checking the type and selecting behaviour. You can't do it with as! There is no valid method of doing
var custom=obj as ICustom<T>;
so you are forced to use GetType() and then some weird methods that interogate the Type object. You can do it with the dynamic pattern.



checkIfCustom(obj);

private void checkIfCustom(object obj) {
dynamicCheckIfCustom((dynamic)obj);
}

private void dynamicCheckIfCustom(object obj) {
//do nothing
}

private void dynamicCheckIfCustom<T>(ICustom<T> iCustom) {
doSomethingWith(iCustom);
}


This thing works! If anything than an ICustom<T> is given, nothing happends. If it is the correct type, then doSomething is executed with it. Pretty neat, huh?

Tuesday 1 June 2010

Entity Framework 4 POCO Exclude !

This will be a short post to describe my own stupidity. I was testing the new Entity Framework Plain Old CLR Objects (POCO) support and so I made a small test to:
  • Clear the database
  • Insert new items in the database
  • Select the items from the database, with and without related items

Every time I got the entire object tree, with child collection and parent objects, thus making me think that in this implementation of EF, the need to use Include was gone, instead an Exclude method was needed in order to tell the framework to NOT LOAD related objects! Insane!
After looking everywhere to find the answer, I finally turned to profiling SQL only to see that the database was not accessed with related items, but only what I had asked for. Then I had my "I'm an idiot!" moment. I was using the same context and EF knew the entire hierarchy of objects because (duh!) I had just inserted it a few code lines above. Using different contexts solved the "problem" and only returned the requested objects, making Include a necessity again.