Archive for the ‘Tools’ Category

ReSharper goodness

Tuesday, April 28th, 2009

I upgraded to ReSharper 4.5 recently, and when work­ing with it I dis­cov­ered new, cool feature.

Hav­ing this (notice class Per­son does not exists yet, hence the red):

rs_1

You can do this:

rs_2

And get this:

rs_3

I’m pretty sure older ver­sion would say pri­vate sta­tic object person;

And even if it’s not new, it’s still a nice lit­tle smart feature.

I only wish that doing this…

rs_4

… would also gen­er­ate the con­struc­tor and prop­erty in one go.

Tech­no­rati Tags:

Productivity tip of the week, part 3

Friday, March 27th, 2009

This time it’s not a sin­gle key­board short­cut. There’s a lit­tle known fea­ture of ReSharper, called To-Do Items. It’s a series of tags, you can define, and when you put them in your com­ments some­where in the code, ReSharper will pick the com­ment up and put it, in the To-Do Explorer Window.

There are 3 pre­de­fined tags: TODO, BUG, NOTE and NotIm­ple­mented which picks up the NotIm­ple­ment­edEx­cep­tion occur­rences in your code. Yes, this is not a code com­ment, but most of the time you’ll use com­ments only.

So how is this use­ful and boosts productivity?

As you code your way, you can tag it with such com­ments, mostly for later review or to fix later.

productivity_3_code

You can then imme­di­ately view all of them in To-Do Explorer, and jump to any of them.

productivity_3_explorer

One thing I do how­ever, is I redid the tags (defined via reg­u­lar expres­sions), because the default ones used to pick up false positives.

productivity_3_pattern

I changed the pat­tern to be case sen­si­tive and to include a colon after a tag. To make use of this fea­ture, I also keep my To-Do Explorer win­dow always vis­i­ble, to ensure that I do pick up the com­ments I, or any other devel­oper on the team puts in the code.

Tech­no­rati Tags:

Writing Launchy plugin in C# with Launchy#

Friday, March 13th, 2009

Today I learned about Launchy# – C# bind­ing for Launchy exten­si­bil­ity API, that allows devel­op­ers to write Launchy plu­g­ins in man­aged code. I once wrote… a hack more than exten­sions, that enabled users to tweet from Launchy. I was reluc­tant to extend it fur­ther, because then I’d have to write unman­aged code, which is far from my def­i­n­i­tion of fun.

How­ever, now I’m think­ing about play­ing a lit­tle bit with Launchy# and build­ing a proper Twitter-Launchy plug­ing (Twitty?).

So now I’m gath­er­ing ideas. What would you like to see in  Twitty?

UPDATE

It looks like the name Twitty is already taken (I should have googled that first). So now I’m look­ing for ideas and name.

Tech­no­rati Tags: ,

Working effectively with Reflection.Emit

Monday, January 19th, 2009

I’ve been work­ing a lit­tle bit with dynamic code gen­er­a­tion at run­time (classes in Reflection.Emit name­space, col­lec­tively referred to as Reflection.Emit). It’s a low level API, that requires you to work with IL oper­a­tions, keep track of what is on the stack, and requires quite a bit of knowl­edge about IL and CLR.

I’m no expert in IL, as prob­a­bly most of devel­op­ers, but there are ways to make this things easier.

To work my way through gen­er­at­ing code, I use iter­a­tive approach.

  1. Write a class/method in C# that exactly (or as closely as pos­si­ble) reassem­bles a sin­gle small part of what I want my dynamic method to look like. If my dynamic method is a sta­tic method – I write a sta­tic method. If it has a value type para­me­ter, I write a method with value type para­me­ter. I think you get the pic­ture. The impor­tant thing is to really get as close to what you want to achieve with dynamic method as pos­si­ble, and under­stand influ­ence of those parts you can’t get exactly the same (for exam­ple because of C# limitations).
  2. I com­pile the class (also notice dif­fer­ences between mode you com­pile in – you usu­ally want Release ver­sion, not Debug), and open it up in Reflec­tor to see its IL.
  3. I write my code that does code gen­er­a­tion, to gen­er­ate IL iden­ti­cal to the one of my sta­t­i­cally wrote method (tak­ing into account all the variability).
  4. I save gen­er­ated assem­bly, open it up in Reflec­tor, and com­pare the IL, to the one cre­ated ear­lier, to see if they match. I often switch in Reflec­tor to C# view, to bet­ter see some kinds of errors (pass­ing wrong para­me­ters, or call­ing method on wrong object). If you can’t save your gen­er­ated code to phys­i­cal assem­bly you can’t use this debug­ger visu­al­izer to see its IL.
  5. Write and run tests.
  6. If every­thing works, go back to step one, add another part of code and repeat until you have all you wanted.

Here’s an exam­ple of this approach. It’s an actual code I wrote while work­ing on Dynam­icProxy fea­ture. The thing that is dif­fer­ent here, is that Cas­tle has an addi­tional layer of abstrac­tion on top of Reflection.Emit so I was not work­ing directly with IL. This makes things a lit­tle bit eas­ier, because you’re oper­at­ing on a higher level of abstrac­tion. On the other hand how­ever, you don’t get that tight con­trol over what gets gen­er­ated, and you have a new API to learn.

Any­way, I actu­ally already had a pretty good idea of what I wanted to do (I only needed to change the way things worked, by call­ing other con­struc­tor in my dynamic method, pass­ing addi­tional para­me­ters). I wrote some tests to ver­ify that my code works the way I wanted it to, and I imple­mented it. Unfor­tu­nately one test didn’t pass with the fol­low­ing error.

reflectionemiterror1 

One para­me­ter I wanted to pass was an array, passed by ref­er­ence, and it seemed that there was some­thing wrong with it.

I opened Reflec­tor and peeked into the gen­er­ated method. Every­thing looked just fine when I switched to C# view.

 reflectionemitReflector

To inves­ti­gate things fur­ther I saved IL of gen­er­ated method to a file, and I did the same with IL of C# method I wrote as an exam­ple of what I wanted to accom­plish. I then opened them both up in a diff tool to see where the dif­fer­ence was.

reflectionemitdiff

As it turns out, the code below (generated.txt) passes the loads the field value (ldfld) while it should load its address (ldflda). Know­ing this it was triv­ial to fix my code.

On a side note, there’s also a Reflection.Emit Lan­guage plug-in for Reflec­tor that may be use­ful to you if you’re work­ing directly with Reflection.Emit classes. It shows you for any method you select the C# code that you’d write to gen­er­ate that method with Reflection.Emit.

Tech­no­rati Tags: , ,

Google Chrome: developer humor

Thursday, December 18th, 2008

I wanted to unin­stall Google Chrome today, and here’s the win­dow that prompts me if I’m sure I want to unin­stall it:

google_chrome

It says the usual “Are you sure you want to unin­stall Google Chrome” fol­lowed by “(We were behav­ing good, weren’t we?)”

I find that hilarious.

Tech­no­rati Tags: ,

Multilingual .NET applications. Enter .NET localization

Wednesday, December 10th, 2008

Cre­at­ing mul­ti­lin­gual appli­ca­tions is a huge topic. There are whole books devoted to it, and if you’re seri­ous about it, you should def­i­nitely read those, because what you see on sur­face, is only the tip of an iceberg.

If you only want to play with local­iza­tion or need a quick ref­er­ence, hope­fully this post will help.

Fist thing is, .NET is really well thought of if it comes to local­iza­tion, so if you know what you’re doing, it’s pretty pain­less to cre­ate appli­ca­tion that will be easy to trans­late to other lan­guages (local­iza­tion is a LOT big­ger topic than show­ing labels in dif­fer­ent lan­guages, but I’ll leave this topic out.)

Sec­ond thing is, local­iza­tion mech­a­nism in .NET is greatly based on con­ven­tions, and it’s what we’ll focus here.

First obvi­ous rule is, that each string, pic­ture, video… gen­er­ally speak­ing local­iz­able resource must not be hardcoded.

If you don’t hard­code resources where do you keep them? In (sur­prise) Resources file. Gen­er­ally you can use .resx files, or plain .txt, though the lat­ter are use­ful only if you only keep strings.

resourceFile

Visual Stu­dio has pretty good sup­port for edit­ing resources in .resx files, and later I’ll show you another tool that can do it as well.

To access the resources pro­gram­mat­i­cally you need Resource­M­an­ager class. To instan­ti­ate it you need to give it the part to resources within an assem­bly, and the assem­bly itself. If it’s a lit­tle bit unclear, here’s the example:

resourcePath

If the Visual Stu­dio project is named Local­iz­ableApp, and the .resx file we want to use is in folder Prop­er­ties, and the file itself is named Resources.resx, the whole base name for the resources is “LocalizableApp.Properties.Resources”.

That’s where the com­piled .resx file (.resources) will be located within the assem­bly. You can see it, if you open the com­piled assem­bly with Reflector.

resourceLocation

So to instan­ti­ate the Resource­M­an­ager you’d write code sim­i­lar to the following:

var manager = new ResourceManager("LocalizableApp.Properties.Resources", typeof(Program).Assembly);

Each resource is iden­ti­fied by it’s unique name string. For exam­ple in the pic­ture below, we have two resources with names, “greet­ing” and “howAreYou”

resourceEditor

You use these names to get the val­ues of the resources. The resource man­ager does its magic, to pro­vide you with resources best match­ing the Cul­ture­Info you pro­vided. If you don’t pro­vide any Cul­ture, cur­rent thread’s Cur­ren­tU­I­Cul­ture is used. So if you write:

Console.WriteLine("{0} {1}", manager.GetString("greeting"), manager.GetString("howAreYou"));

The Cul­ture­Info object held in Cur­ren­tU­I­Cul­ture prop­erty of cur­rently exe­cut­ing thread will be used. The default value for this prop­erty is the same as lan­guage ver­sion of Win­dows OS the pro­gram is exe­cut­ing on, which is rea­son­able. If your user uses Pol­ish Win­dows she will prob­a­bly want to inter­act with Pol­ish ver­sion of your app as well.

You may not rely on this default though, and either over­ride the Thread’s prop­erty, or spec­ify the cul­ture explic­itly when call­ing meth­ods on Resource­M­an­ager, like so:

culture = CultureInfo.GetCultureInfo("pl-PL");
Console.WriteLine("{0} {1}", manager.GetString("greeting", culture), 
    manager.GetString("howAreYou", culture));

Of course you wouldn’t hard­code the cul­ture the way I did in the exam­ple, because it would defeat the pur­pose of using cul­ture in the first place.

OK, so how to add another language?

You have the .resx file with the default, fall­back resources, right? So now all you need is either send the file to a local­iza­tion com­pany, sit back and enjoy life, wait­ing for them to do the hard job, or do it your­self. To go with the lat­ter option, you may want to use a tool to edit resource files, called Resourcer, by Lutz Roeder (Reflec­tor, people!).

resourceResourcer

You can eas­ily edit any kind of resources in it (not only strings). When you’re done trans­lat­ing your resources, save the file as .resources file, using fol­low­ing pat­tern: {baseResourceName}.{culture}.resources. For exam­ple if you were to trans­late our exam­ple app, to Ger­man lan­guage as spo­ken in Ger­many, you’d save your edited file with the fol­low­ing name: LocalizableApp.Properties.Resources.de-de.resources

It is impor­tant to obey this pat­tern, as by con­ven­tion, this is what Resource­M­an­ager expects. If you fail to obey it, Resource­M­an­ager will not be able to pick your trans­lated resources and will fall back to the default.

Hav­ing trans­lated and prop­erly named .resource file we need to make a satel­lite assem­bly out of it. To do it, you need Assem­bly Linker (al.exe) tool that is part of .NET SDK.

al

There are mul­ti­ple prop­er­ties you can set with al, the min­i­mal ver­sion to get valid satel­lite assem­bly is shown on above screen­shot. One thing that’s impor­tant to note, is the name of result­ing satel­lite assem­bly. Again, by con­ven­tion it has to be {NameOfBaseAssemblyWithoutExtension}.resources.dll, so if our appli­ca­tion assem­bly was named LocalizableApp.exe, satel­lite assem­bly must be called LocalizableApp.resources.dll

Notice that the name of the assem­bly is the same for every cul­ture. So how do we deal with that. Obvi­ously we can’t have two files with the same name in one folder. The way it is han­dled, is through sub­fold­ers. Each satel­lite assem­bly is held in a folder which is named after the cul­ture of the satel­lite assembly.

resourceFolders

For exam­ple if our LocalizableApp.exe is held in a folder, let’s say Debug like on the above screen­shot, the de-de satel­lite assem­bly would be Debug\de-de\LocalizableApp.resources.dll and for instance pl assem­bly would be in Debug\pl\LocalizableApp.resources.dll.

I hope this is all clear by now. The great­est thing is, to add new lan­guage you don’t even need the actual base assem­bly. All you need is its resources and their loca­tion within the assembly.

Tech­no­rati Tags: , ,

Unity framework and the Principle of the Least Surprise

Wednesday, December 3rd, 2008

I don’t like the Unity Inver­sion of Con­trol frame­work. I find it too ver­bose, requir­ing user to be too explicit (except for cases where it doesn’t while it should), not intu­itive and I gen­er­ally don’t like its design. Unfor­tu­nately, it’s the only IoC frame­work I’m allowed to used at work, so I’m stuck with it, good or bad. There are times how­ever that I’m just aston­ished by how it works, and mostly, in a neg­a­tive sense. There’s an impor­tant prin­ci­ple in com­puter sci­ence, called Prin­ci­ple of the Least Sur­prise, that says, that frame­work (in par­tic­u­lar) should have its API designed in such a way that it works like the user (pro­gram­mer in this case) would expect it to.

Let’s take… well, I don’t know… Unity for example.

Take a look at the fol­low­ing piece of code:

unity_method_signature

Every­thing seems pretty obvi­ous here, to any­one who has ever used an IoC con­tainer. Using generic para­me­ter I reg­is­ter a type (Ser­vice­Host) ser­vice, with spe­cific key (mySer­vice), then I explic­itly (I could write a whole post about how not good idea it is, but it’s leave it out for now) spec­ify con­struc­tor I want used and it’s para­me­ters using Injec­tion­Con­struc­tor, next I spec­ify method injec­tion with Injec­tion­Method class. Pretty sim­ple, huh?

Now, let’s take a closer look at Injec­tion­Method con­struc­tor. It takes a string, denot­ing method’s name, and next it takes the list of objects (array of System.Object to be pre­cise) that should be used as method’s para­me­ters, right? the tooltip leaves no doubt about it. It says:

method­Pa­ra­me­ters: Para­me­ter val­ues for the method.

Well, if you think it’s obvi­ous imag­ine my sur­prise when I saw this, after run­ning this code:

unity_exception

Turns out it’s not so obvi­ous to every­body. To make the long story short, pulling Unity’s source code showed, that there’s a fine print to that method (well, actu­ally there’s none, it just works in unex­pected ways, maybe that behav­ior is men­tioned some­where in the docs, but I’m paid for writ­ing work­ing code, not for read­ing docs). It does use the para­me­ters you pro­vide lit­er­ally, most of the time. How­ever if you pass an argu­ment of type System.Type, like I did, Unity implic­itly tries to know bet­ter, what you want to do, than your­self. It assumes that since you passed a System.Type, as System.Object para­me­ter, for sure what you meant was not to use it lit­er­ally, but instead to use instance of ser­vice of that type reg­is­tered with the con­tainer, and that’s what it tries to do. It then fails to bind those para­me­ters to the method, which results in afore­men­tioned excep­tion. To make it work you have to be yet smarter and know another implicit rule of Unity, that if you pass as para­me­ters val­ues of types derived from Injec­tion­Pa­ra­me­ter­Value it will han­dle them cor­rectly. So chang­ing the above code to this, yields the expected results:

unity_fixed

Tech­no­rati Tags: ,

Castle DynamicProxy IInterceptorSelector implementation

Sunday, November 30th, 2008

I just got this test pass:

[Test]
public void BasicCase()
{
    ProxyGenerationOptions options = new ProxyGenerationOptions();
    options.Selector = new AllInterceptorSelector();
    var target = this.generator.CreateInterfaceProxyWithTarget(
        typeof(ISimpleInterface), 
        new SimpleClass(),
        options,
        new NoopInterceptor() ) as ISimpleInterface;
    Assert.IsNotNull( target );
    target.Do();            
}

And here’s how Do proxy method looks like in Reflector:

interceptorSelectorMethodInReflector 

Skip generated types when performing analysis in NDepend

Tuesday, October 14th, 2008

Code cre­ated in more recent ver­sions of C# has a lot of gen­er­ated types, even if you don’t use code gen­er­a­tion explic­itly. Inter­a­tors (the yield key­word), and anony­mous del­e­gates both use gen­er­ated types under­neath. Also those neat anony­mous types intro­duced in C# 3.0 are noth­ing more than a com­piler magic.

All this may clut­ter your NDe­pend win­dow of choice, when look­ing at your projects. You can how­ever get rid of gen­er­ated stuff, pretty eas­ily, with this sim­ple CQL query:

// <Name>Types not generated by the compiler</Name>
SELECT TYPES FROM ASSEMBLIES "YourAssembly" 
WHERE !(HasAttribute "System.Runtime.CompilerServices.CompilerGeneratedAttribute")

Sim­ple, but useful.

If you want to get rid of just some types of gen­er­ated classes, for exam­ple you want to get rid of iter­a­tors, but want to leave anony­mous del­e­gate classes, you may use reg­u­lar expres­sions for that. This is my clumsy attempt to that:

// <Name>Types not generated by the compiler</Name>
SELECT TYPES FROM ASSEMBLIES "Castle.Facilities.WcfIntegration" WHERE 
!NameLike ".+<>c__.+" /* Anonymous delegates, like private sealed class <>c__DisplayClass1
*/ AND 
!NameLike ".+\+<.*>d__.+" /* Iterators, like private sealed class <FindDependencies>d__0<T> :
IEnumerable<T>, IEnumerable, IEnumerator<T>, IEnumerator, IDisposable */

Tech­no­rati Tags: , ,

Remove assemblies from Dependency Graph in NDepend

Monday, October 13th, 2008

Last minor ver­sion of NDe­pend intro­duced cool, inter­ac­tive Depen­dency Graph, that was really a huge step for­ward as com­pared to sta­tic .png we got ear­lier. You can now load set of assem­blies, and imme­di­ately see depen­den­cies between them, with­out run­ning your_picture_viewer_here. You also can drill down the depen­dency tree  and see depen­den­cies between name­spaces within an assem­bly, classes within name­space, meth­ods within class…

One thing (ok, there are more, but we’ll get to that in a minute), that I missed, was the abil­ity to remove an ele­ment from the graph. You could do this using CQL, but this just was too com­pli­cated solu­tion. This is now pos­si­ble with new and fresh 2.10.3 build.

Remove element from NDepend' Dependency Graph

So, back to my wish­list. You can inter­act with only one ele­ment of the graph at any given moment. That means, although you can select few assem­bles with ctrl+LMB if you click Remove, only one will get removed. Same with drilling down. You can’t select few assem­bles and go “View inter­nal depen­dency cycles on graph” to see cycles between classes in all of those assem­blies. (well, you can as a mat­ter of fact do this with CQL, but again, this may require a lot of typ­ing and GUI just feels like the right place to do it.)

Sec­ond thing I wish it had, is a scroll­bar for zoom­ing instead of + / – but­tons. Can we get this Partick?

Tech­no­rati Tags: ,