Stories about Software


Productivity Add-Ins: Bruce Lee vs Batman

In the last few months, I’ve seen a number of tweets and posts decrying or at least cautioning against the use of productivity tools (e.g. CodeRush, ReSharper, and JustCode). The reasoning behind this is is generally some variant of the notion that such tools are more akin to addictive drugs than to sustainable life improvements. Sure, the productivity tool is initially a big help, but soon you’re useless without it. If, on the other hand, you had just stuck to the simple, honest, clean living of regular development, you might not have reached the dizzying highs of the drug, but neither would you have experienced crippling dependency and eventual rock bottom. The response from those who disagree is also common: insistence that use doesn’t equal dependence and the extolling of the virtues of such tools. Predictably, this back and forth usually degenerates into Apple v. Android or Coke v. Pepsi.

Before this degeneration, though, the debate has some fascinating overtones. I’d like to explore those overtones a bit to see if there’s some kind of grudging consensus to be reached on the subject (though I recognize that this is probably futile, given the intense cognitive bias of endowment effect on display when it comes to add-ins and enhancements that developers use). At the end of the day, I think both outlooks are born out of legitimate experience and motivation and offer lessons that can at least lead to deciding how much to automate your process with eyes wide open.

Also, in the interests of full disclosure, I am an enthusiastic CodeRush fan, so my own personal preference falls heavily on the side of productivity tools. And I have in the past plugged for it too, though mainly for the issue static analysis purpose rather than any code generation. That being said, I don’t actually care whether people use these tools or not, nor do I take any personal affront to someone reading that linked post, deciding that I’m full of crap, and continuing to develop sans add-ins.

The Case Against the Tools

There’s an interesting phenomenon that I’ve encountered a number of times in a variety of incarnations. In shops where there is development of one core product for protracted periods of time, you meet workaday devs who have not actually clicked “File->New” (or whatever) and created a new project in months or years. Every morning they come in at 9, every evening they punch out at 5, and they know how to write code, compile it, and run the application, all with plenty of support from a heavyweight IDE like Eclipse or Visual Studio. The phenomenon that I’ve encountered in such situations is that occasionally something breaks or doesn’t work properly, and I’ve said, “oh, well, just compile it manually from the command line,” or, “just kick off the build outside of the IDE.” This elicits a blank stare that communicates quite effectively, “dude, wat–that’s not how it works.”

When I’ve encountered this, I find that I have to then have an awkward conversation with a non-entry-level developer where I explain the OS command line and basic program execution; the fact that the IDE and the compiler are not, in fact, the same thing; and other things that I would have thought were pretty fundamental. So what has gone wrong here? I’d say that the underlying problem is a classic one in this line of work–automation prior to understanding.

AngryArchLet’s say that I work in a truly waterfall shop, and I get tired of having to manually destroy all code when any requirement changes so that I can start over. Watching for Word document revisions to change and then manually deleting the project is a hassle that I’ve lived with for one day too long, so I fire up the plugin project template for my IDE and write something that runs every time I start. This plugin simply checks the requirements document to see if it has been changed and, if so, it deletes the project I’m working on from source control and automatically creates a new, blank one.

Let’s then say this plugin is so successful that I slap it into everyone’s IDE, including new hires. And, as time goes by, some of those new hires drift to other departments and groups, not all of which are quite as pure as we are in their waterfall approach. It isn’t long before some angry architect somewhere storms over, demanding to know why the new guy took it upon himself to delete the entire source control structure and is flabbergasted to hear, “oh, that wasn’t me–that’s just how the IDE works.”

Another very real issue that something like a productivity tool, used unwisely, can create is to facilitate greatly enhanced efficiency at generating terrible code (see “Romance Author“). A common development anti-pattern (in my opinion) that makes me wince is when I see someone say, “I’m sure generating a lot of repetitive code–I should write some code that generates this code en masse.” (This may be reasonable to do in some cases, but often it’s better to revisit the design.) Productivity tools make this much easier and thus more tempting to do.

The lesson here is that automation can lead to lack of understanding and to real problems when the person benefiting doesn’t understand how the automation works or if and why it’s better. This lack of understanding leads to a narrower view of possible approaches. I think a point of agreement between proponents and opponents of tools might be that it’s better to have felt a pain point before adopting the cure for it rather than just gulping down pain medication ‘preventatively’ and lending credence to those saying the add-ins are negatively habit-forming. You shouldn’t download and use some productivity add-in because all of the cool kids are doing it and you don’t want to be left out of the conversations with hashtag #coderush

The Case for the Tools

The argument from the last section takes at face value the genuine concerns of those making it and lends them benefit of the doubt that their issue with productivity tools is truly concern for bad or voodoo automation. And I think that requires a genuine leap of faith. When it comes to add-ins, I’ve noticed a common thread between opponents of that and opponents of unit tests/TDD–often the most vocal and angry opponents are ones that have never tried it. This being the case, the waters become a little bit muddied since we don’t know from case to case if the opponent has consistently eschewed them because he really believes his arguments against them or if he argues against them to justify retroactively not having learned to use them.

And that’s really not a trivial quibble. I can count plenty of detractors that have never used the tools, but what I can’t recall is a single instance of someone saying, “man, I used CodeRush for years and it really made me worse at my job before I kicked the habit.” I can recall (because I’ve said) that it makes it annoying for me to use less sophisticated environments and tooling, but I’d rather the tide rise and lift all of the boats than advocate that everybody use notepad or VI so that we don’t experience feature envy if we switch to something else.

NorthPolePigeonThe attitude that results from “my avoidance of these tools makes me stronger” is the main thing I was referring to earlier in the post when I mentioned “fascinating overtones.” It sets the stage for tools opponents to project a mix of rugged survivalist and Protestant Work Ethic. Metaphorically speaking, the VI users of the world sleep on a bed of brambles because things like beds and not being stabbed while you sleep are for weaklings. Pain is gain. You get the sense that these guys refuse to eat anything that they didn’t either grow themselves or shoot using a homemade bow and arrow fashioned out of something that they grew themselves.

But when it comes to programming (and, more broadly, life, but I’ll leave that for a post in a philosophy blog that I will never start) this affect is prone to reductio ad absurdum. If you win by leaving productivity tools out of your Visual Studio, doesn’t the guy who uses Notepad++ over Visual Studio trump you since he doesn’t use Intellisense? And doesn’t the person who uses plain old Notepad trump him, since he doesn’t come to rely on such decadent conveniences as syntax highlighting and auto-indentation? And isn’t that guy a noob next to the guy who codes without a monitor the way that really, really smart people in movies play chess without looking at the board? And don’t they all pale in comparison to someone who lives in a hut at the North Pole and sends his hand-written assembly code via carrier pigeon to someone who types it into a computer and executes it (he’s so hardcore that he clearly doesn’t need the feedback of running his code)? I mean, isn’t that necessary if you really want to be a minimalist, 10th degree black-belt, Zen Master programmer–to be so productive that you fold reality back on itself and actually produce nothing?

The lesson here is that pain may be gain when it comes to self-growth and status, but it really isn’t when the pain makes you slower and people are paying for your time. Avoiding shortcuts and efficiency so that you can confidently talk about your self reliance not only fails as a value-add, but it’s inherently doomed to failure since there’s always going to be some guy that can come along and trump you in that “disarms race.” Doing without has no intrinsic value unless you can demonstrate that you’re actively being hampered by a tool.

So What’s the Verdict?

I don’t know that I’ve covered any ground-breaking territory except to point out that both sides of this argument have solutions to real but different problems. The minimalists are solving the problem of specious application of rote procedures and lack of self-reliance while the add-in people are solving the problem of automating tedious or repetitive processes. Ironically, both groups have solutions for problems that are fundamental to the programmer condition (avoiding doing things without knowing why and avoiding doing things that could be done better by machines, respectively). It’s just a question of which problem is being solved when and why it’s being solved, and that’s going to be a matter of discretion.

Add-in people, be careful that you don’t become extremely proficient at coding up anti-patterns and doing things that you don’t understand. Minimalist people, recognize that tools that others use and you don’t aren’t necessarily crutches for them. And, above all, have enough respect for one another to realize that what works for some may not work for others. If someone isn’t interested in productivity tools or add-ins and feels more comfortable with a minimalist setup, who are any of us to judge? I’ve been using CodeRush for years, and I would request the same consideration–please don’t assume that I use it as a template for 5,000 line singletons and other means of mindlessly generating crap.

At the end of the day, whether you choose to fight bad guys using only your fists, your feet, and a pair of cut-off sweat shorts or whether you have some crazy suit with all manner of gizmos and gadgets, the only important consideration when all is said and done is the results. You can certainly leave an unconscious and dazed pile of ne’er-do-wells in your wake either way. Metaphorically speaking, that is–it’s probably actually soda cans and pretzel crumbs.


You Need CodeRush


The other day, I was chatting with some developers and one of them pulled me over to show me the following code:

private void SetLayout(Page page)
    if (null == page)

I did a double take and then smirked a bit, pointing out that this was probably dead code. I asked the person who was showing me this to do a “find all references” and there actually was one:

private void mainFrameNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    Page page = e.Content as Page;
    if (page != null)

So, we then backed it up a step and discovered that this was an event handler for an event declared in XAML (this whole thing was in a code-behind file). So, every time some event occurred (some sort of navigation thing), the code would cast the sender as a page, call a method with that page, and then return if the page was null, and also return if the page wasn’t null.

How Did It Come To This?

Looking at the SetLayout method, I quickly developed a hypothesis as to how the code wound up this way. The “SetLayout” method probably checked the page for null as a precondition prior to performing some sort of action on Page. At some point, that action became undesirable and was removed from the code, but whoever removed it didn’t realize that the precondition check was now meaningless, as was the whole chain of code above it for the event handler. This was confirmed correct by a quick glance through source control.

Here’s what this looks like in my IDE:

Do you see the dashes on the right, next to the scroll bar? Those are the issues in the CodeRush “issues list”. Do you see the squiggly underline of “SetLayout” (hard to see at this resolution, but you can zoom in or open the image in a new tab if you want)? That means there’s an issue here. In the interests of full disclosure, this is actually to tell me that the method could be static (it operates on no instance member of the class) rather than to tell me that the method has no effect on anything, but the important thing is that it’s underlined. It draws my attention to the method instead of encouraging me to skip over it while looking for something else here. And, as soon as this method catches anyone’s attention, it will obviously be deleted.

The Value of Productivity Tools

In general, the Code Rush issues list is a great companion. It alerts me to dead code, undisposed disposables, redundant statements, and plenty of other things. If you pause any time it tells you about an issue, you will become better at programming and you will start to recognize more problems. It isn’t necessarily superior to using, say, Style Cop or any other particular tool, but it is very convenient in that it paints the problems right inline with the IDE. They’re quite noticeable.

Code Rush’s competitor, Resharper does this as well. I plug for Code Rush because I use it and I love it, but if you get Resharper, that’s fine — just get something. These productivity tools are game changers. When looking at this code in someone else’s IDE, there was no squiggly and no immediately obvious problem if you’re casually scrolling through the class. But in my IDE, my eyes are drawn right to it, allowing and in fact demanding that I fix it. This sort of boy-scouting makes you better at writing your own code and better at fixing other people’s.

I forget what the license costs, but your employer can afford it. Heck, if they’re too cheap, you can afford it. Because what you can’t afford is to have code checked in under your name that looks like the code in this post. That’s no good, and it’s avoidable.


TDD and CodeRush

TDD as a Practice

The essence of Test Driven Development (TDD) can be summarized most succinctly as “red, green, refactor”. Following this practice will tend to make your code more reliable, cleaner, and better designed. It is no magic bullet, but you doing TDD is better at programming than you not doing it. However, a significant barrier to adoption of the practice is the (justifiable) perception that you will go slower when you start doing it. This is true in the same way that sloppy musicians get relatively proficient being sloppy, but if they really want to excel, they have to slow down, perfect their technique, and gradually speed things back up.

My point here is not to proselytize for TDD. I’m going to make the a priori assumption that testing is better than not testing and TDD is better than not TDD and leave it at that. My point here is that making TDD faster and easier would grease the skids for its broader adoption and continue practice.

My Process with MS Test

I’ve been unit testing for a long time, testing with TDD for a while, and also using CodeRush for a while. CodeRush automates all sorts of refactorings and generally makes development in Visual Studio quicker and more keyboard driven. As much as I love it and stump for it, though, I had never gotten around to using its test runner until recently.

I saw the little test tube icons next to my tests and figured, “why bother with that when I can just hit Ctrl-R, T to execute my MS Test tests in scope?” But a couple of weeks ago, I tried it on a lark, and I decided to give it a fair shake. I’m very glad that I did. The differences are subtle, but powerful, and I find myself a more efficient TDD practitioner for it.

Here is a screenshot of what I would do with the Visual Studio test runner:

I would write a unit test, and hit Ctrl-R, T, and the Visual Studio test results window would pop up at the bottom of my screen (I auto-hide almost everything because I like a lot of real estate for looking at code). For the first run, the screenshot there would be replaced with a single failing test. Then, I would note the failure, open the class and make changes, switch back to the unit test file, and run all of the tests in the class, producing the screenshot above. When I saw that this had worked, I would go back to the class and look either to refactor or for another failing test to add for fleshing out my class further.

So, to recap, write a test, Ctrl-R, T, pop-up window, dismiss window, switch to another file, make changes, switch back, Ctrl-R, T, pop-up window, dismiss pop-up window. I’m very good at this in a way that one tends to be good at things through large amounts of practice, so it didn’t seem inefficient.

If you look at the test results window too, it’s often awkward to find your tests if you run more than just a few. They appear in no particular order, so seeing particular ones involves sorting by one of the columns in the class. There tends to be a lot of noise this way.

Speeding It Up With CodeRush

Now, I have a new process, made possible by the way CodeRush shows test pass/fail:

Notice the little green checks on the left. In my new process, I write a test, hit Ctrl-T, R, and note the failure. I then switch to the other class and make it pass, at which time, I hit Ctrl-T, L (which I have bound to “repeat last test run”) before going back to the test class. As that runs, I switch to the test class and see that my test now passed (I can also easily run all tests in the file if I choose). Now, it’s time to write my next test.

So, to recap here, it’s write a test, Ctrl-T, R, switch to another file, make changes, Ctrl-T, L, switch back. I’ve completely eliminated dealing with a pop-up window and created a situation where my tests are running as I’m switching between windows (multi-tasking at its finest).

In terms of observing results, this has a distinct advantage as well. Instead of the results viewer, I can see green next to the actual code. That’s pretty powerful because it says “this code is good” rather than “this entry is good, and if you double click it, you can see which code is good”. And, if you want to see a broader view than the tests, you can see green next to the class and the namespace. Or, you can launch the CodeRush test runner and see a hierarchical view that you can drill into, rather than a list that you can awkwardly sort or filter.

Does This Really Matter?

Is shaving off a this small an amount of time worth it? I think so. I run tests dozens, if not hundreds of times per day. And, as any good programmer knows, shaving time off of your most commonly executed tasks is at the heart of optimizing a process. And, if we can shave time off of a process that people, for some reason, view as a luxury rather than a mandate, perhaps we can remove a barrier to adopting what should be considered a best practice — heck, a prerequisite for being considered a professional, as Uncle Bob would tell you.


DXCore Plugin Part 3

In a previous post, I mentioned my ongoing progress with a DX Core plugin. I’d been using it successfully for some time now but had to dust it off again last week. Another convention that I’m required to abide for consistency sake but don’t much care for is explicit typing of my variables.

That is, I prefer declarations like:

var myTypeWithLongName = new TypeWithALongName();

rather than:

TypeWithALongName myTypeWithLongName = new TypeWithALongName();

I personally find the second to be needlessly syntactically noisy, and I don’t really see any benefit since the implicit (var) typing preserves strong typing and even causes the resulting type to show up in Intellisense. But, when in Rome…

Compared to my previous setup, this was relatively straightforward. Initially, I thought it would be even simpler than it turned out to be, since Code Rush itself supports the explicit/implicit conversion as an individual refactoring. I figured I’d just have to iterate through the file and call something like “Some.CodeRush.Namespace.MakeExplicit(myVariable)”.

Well, it didn’t turn out to be that easy (at least not that I found), but it did turn out to be relatively simple. Eliding the part about actually finding the variables, I was able to accomplish what I wanted with this method:

/// <summary>Convert the local variable declaration to FSG's standard of explicit typing</summary>
/// <param name="variable">Variable object to convert</param>
/// <returns>A string with the new type declaration</returns>
public string ConvertDeclaration(Variable variable)
    var myImplicit = variable as ImplicitVariable;
    string myString = variable.MemberType;
    if (myImplicit != null)
        var myObjectCreation = myImplicit.Expression as ObjectCreationExpression;
        if (myObjectCreation != null && myObjectCreation.ObjectType != null)
            myString = myObjectCreation.ObjectType.ToString();

        var myArrayCreate = myImplicit.Expression as ArrayCreateExpression;
        if (myArrayCreate != null)
            myString = myArrayCreate.BaseType.ToString();
    return myString;

This isn’t actully my finished ‘production’ code, but it’s easier to display in this format. I didn’t like the size of that method, so I created an abstract ExplicitExpressionConverter and gave it inheritors ObjectCreationExpressionConverter and ArrayCreateExpressionConverter, using a factory method creation pattern to figure out which to create, based on the variable. But while that abstraction makes the code cleaner, it makes the logic harder to document in a blog post.

So, anyway, the idea here is that you need to convert the variable you find into the appropriate type of expression. An object creation expression is standard allocation, and the array create expression is a special case. There are other special cases as well, such as null coalescing (var myFoo = someClass.GetAFoo() ?? new Foo()) and method call expression (var myFoo = someClass.GetAFoo()), but I have not yet figured out how to obtain the return type from those expressions. I’ll probably add a part 4 if/when I do.


DXCore Plugin Part 2

In the previous post on this subject, I created a basic DXCore plugin that, admittedly, had some warts. I started using it and discovered that there were subtle issues. If you’ll recall, the purpose of this was to create a plugin that would convert some simple stylistic elements between my preferences and those of a group that I work with. I noticed two things that caused me to revisit and correct my implementation: (1) if I did more than one operation in succession, things seemed to get confused and garbled in terms of variable naming; and (2) I was not getting renames in all scopes.

The main problem that I was having was the result of calling LanguageElement.Document.SetText(). Now, I don’t really understand the pertinent details of this because the API is a black box to me, but I believe the gist of it, based on experience and poking around blog posts, is that calling this explicitly causes the document to get out of sync if you chain renames together.

For instance, take the code:

void Foo()
    string myString = "asdf";
    int myInt = myString.Length();

The way that DXCore’s Document API appears to process this is with a concept called “NameRange.” That is, there are various ways you can use LanguageElements and other things in that inheritance tree to get a particular token in the source file: the string type, the Foo method signature, the “myString” variable, etc. When you actually want to change something name-wise, you need to find all references to your token and do an operation that essentially takes the parameters (SourceRange currentRange, string new text). In this fashion, you might call YourClass.Document.SetText(myStringDeclaration.NameRange, “newMyString”);

Assuming that you’ve rounded up the proper LanguageElement that corresponds to the declaration of the variable “myString”, this tells DXCore that you want to change the text from “myString” to “myNewString”. Conceptually, what you’re changing is represented by some int parameters that I believe correspond to row and column in the file, ala a 2D array. So, if you make a series of sequential changes to “myString” (first lengthen it, then shorten it, then lengthen it again) strange stuff starts to happen. I think this is the result of the actual allocated space for this token getting out of whack with what you’re setting it to. It sometimes starts to gobble up characters after the declaration like Windows when you hit the “insert” key without realizing it. I was winding up with stuff like “string myStringingingingd”;”

So, what I found as a workable fix to this problem was to use a FileChangeCollection object to aggregate the changes I wanted to make as I went, rather than making them all at once. FileChangeCollection takes a series of FileChange objects which want to know the path of the class, the range of the proposed change target, and the new value. I aggregated all of my changes in this collection and then flushed them at the end with CodeRush.File.ChangeFile(_targetClass.GetSourceFile(), _collection); After doing that, I cleared the collection so that my class can reuse it.

This cleared up the issue of inconsistent weirdness in naming. Now I can convert back and forth as many times as I please or run the same conversion over and over again and then run the other one, and atomicity of the standards application is perceived. If I run “convert to theirs, convert to theirs, convert to theirs, convert to mine,” the code ends up retaining my standards perfectly, regardless of whose it started with. This is due both to me getting DXCore right (at least as far as my testing so far proves) and also to my implementation being consistent and unit-tested. However, confidence that I have the DXCore implementation right now allows me in the future to know that, if things are wacky, it’s because I’m not implementing string manipulation and business rules correctly.

The second issue was that some variables weren’t getting renamed properly, depending on the scope. Things that were in methods were fine, but anything in nested Linq queries or loops or what-have-you were failing. I had previously made a change that I thought took care of this, but it turns out that I just pushed the problem down a level or two.

This I ultimately solved with some recursion. My conversion functions take an (element, targetScope) tuple, and they add FileChanges for all elements in the target scope. They then call the same function for all scoped children of targetScope with (element, targetScopeChild). If you think of the source as a tree with the root being your scope, intermediate nodes being scopes with children, and leaves being things containing no nested scoping language elements, this walks your source code as if it were a tree, finding and renaming everything.

Here is an example of my recursive function for adding changes to a class field “_collection”, which corresponds to a FileChangeCollection (no worries, I’m renaming that field to something more descriptive right after I finish this post :D )

/// Abstraction for converting all elements in a target scope
/// Element whose name we want to convert
/// Target scope in which to do the conversion
private void RecursiveAggregateLocalChanges(LanguageElement local, LanguageElement target)

    foreach (IElement myElement in local.FindAllReferences(target))
        var myFieldInstance = CodeRush.Source.GetLanguageElement(myElement);
        if (myFieldInstance != null)
            myFieldInstance.NameRange, _converter.ConvertLocal(local.Name));

    foreach (LanguageElement myElement in target.Nodes)
        RecursiveAggregateLocalChanges(local, myElement);

You want to preserve “local” as a recursion invariant, since this method is called by the method that handles cycling through all local variables in the file and invoking the recursion to change their names. That is, the root of the recursion is given a single local variable to change as well as the target scope of the method it resides in. From here, you change the local everywhere it appears within the method, then you get all of the methods child scopes and do the same on those. You keep recursing until you run out of nested scopes, falling out of the recursion at this point having done your adds.

It does not matter whether you recurse first or last because CodeRush keeps track of the original element regardless and even if it didn’t, you’re only aggregating eventual changes here – not making them as you go – so you don’t wind up losing the root.

Hopefully this continues to be somewhat helpful. I know the DXCore API documentation is in the works, so this is truly the diary of someone who is just tinkering and reverse engineering (with a bit of help from piecing together things on other blogs) to get something done. I’m hardly an expert, but I’m more of one than I was when I started this project, and I find that the most helpful documentation is often that made by someone undertaking a process for the first time because, unlike an expert, all the weird little caveats and gotchas are on display since they don’t know the work-arounds by heart.

I will also update the source code here in a moment, so it’ll be fresh with my latest changes.


Creating a DxCore plugin

Coding standards are one of those things that generally involve some degree of compromise, as there is often a goal during collaboration to give the code a uniform look and feel. I don’t necessarily agree with this goal in all cases, but I do understand it. Having code formatted in wildly different styles in the same solution or assembly steepens the learning curve for newcomers to the project and will have some negative effects on maintenance activities.

So, what to do when the group’s agreed-upon coding standards don’t match your own preferences? Most would simply adapt. I’m not really like most, though. I’m an inveterate tinkerer and heavy customizer. In all of my IDEs, I use a black background and arrange the colors just so. This mentality extends to everything from my windows folder views to my coding idioms. Everything that I do, I make a point to do because of conscious deliberation and not simply because I’m used to doing it. There is a method to my madness. So my solution to being asked to adopt a common set of standards was to write an IDE plugin that would convert my idioms to the group’s and vice-versa.

Because I’ve really been enjoying the DxCore set of tools lately, I decided to go this route. Here are the steps that I’ve taken in order to get a plugin up and running. At the time of writing, this plugin is fairly simple. I like to use camel casing in my code, and I distinguish between class fields, method parameters, and local variables by using the following idioms, respectively: _classField, methodParameter, myLocalVariable (properties and methods are ClassProperty and ClassMethod()). My rationale is that this allows me at a glance to tell what each thing is that I’m referring to. The standard of one of the groups in which I’m developing is _ClassField and localVariable (sans my). I don’t prefer this because I can’t distinguish between method parameters and my local variables at a glance, meaning I don’t know whether I own the reference or my caller does. So, the plugin converts all class variables and method variables back and forth between these idioms, and that’s it.

For usability purposes, I created a CodeRush action to which I could bind a shortcut key sequence, and I adorned it with some niceties such as putting it in a menu and showing a BIGHINT when the actions are executed. Since the documentation for the DxCore API is somewhat scattered and not always complete, a fair bit of reverse engineering went into this, so I make no claims that what I’m doing is the preferred way to do things. But it does work. I may refine this and revisit this as I get more familiar with it, but here is what I’ve done so far (using CodeRush/DXCore 10.2.5 and Visual Studio 2010):

Getting started

Getting started with a new DXCore plugin is pretty straightforward. Open a new Visual Studio project, go to the DevExpress menu, and select “New Plugin.”

Create a new DXCore plugin

From there, give your plugin a descriptive name that suits your purposes and take care of all of the particulars of naming the classes the way you want. Then you’re ready to go. This link describes some steps in detail, including selecting manual rather than automatic loading of the plugin that you’re creating (you probably don’t want Visual Studio scooping this up until it’s tested and stable): Create a plugin. This blog was actually what I referred to for the how-to of creating this.

Lights, Camera, Action

This will create an empty plugin project ready to use. In order to have it do anything useful, you must open the Toolbox from the designer and drag and drop an Action (from the DXCore portion) onto your designer.

Create a new action

Once the action is on your designer page, double click on it.  You will be booted into the code behind, ala classic Visual Studio development. Here, an event handler will be created for the action’s execution. This is going to be the plugin’s entry point. We’ll bind the action to a shortcut key sequence in the IDE, and this is the method to which you’ll add code to manipulate the IDE.

Newly created event handler

For now, if you want to verify that something is happening, I would suggest dropping a “Big Hint” onto your designer, naming it something (I got creative and left it as “bigFeedback1″), and adding the following to your execute event handler:

bigFeedback1.Text = "Hello World!"

Now that you have an actual action and something that it does, you’re ready to try it out. Follow the instructions on Dror Helper’s blog for running the plugin. Basically, you’re going to do a normal run which will, in turn, launch a new instance of Visual Studio. Assuming that you’ve bound a shortcut sequence to your new action, once you load your plugin and execute that sequence, you will see that big CodeRush feedback:

Big Hint

(Clearly, my code does not say “Hello World” at the time of running, but you get the idea.)

One thing to look out for is an exception message when you run. I don’t know if it’s something about my setup specifically, but I see the following:

Loader Lock message

For me, ignoring this and hitting continue makes everything go fine. YMMV.

The code to make it go

I wrote a good bit of code and some unit tests to make this work. The full, zipped solution (as of this writing) can be downloaded here for anyone interested. I certainly won’t go into everything, especially the logic of modifying the variable names. But I will go over a few concepts with which I struggled a bit and had to learn by trial and error.

The DXCore engine has a very deep inheritance hierarchy, and it’s important to find the right level of object in the hierarchy to get the operations that you want. This API is not yet thoroughly documented, so it can be a bit confusing. The first thing that you’re going to be interested in for my plugin is the ActiveClass. This corresponds to the class that’s currently active in the IDE. ActiveClass is obtained by querying static class CodeRush — specifically, CodeRush.Source.ActiveClass.

ActiveClass exposes IEnumerables of TypeDeclaration called “AllFields”, “AllMethods”, “AllProperties”, etc. that correspond to language elements of interest in the class. However, you don’t want TypeDeclarations — you want LanguageElements.  So you’ll want to cast these guys as LanguageElement. Doing so exposes a “NameRange” property, which is what you pass to ActiveClass.Document.SetText(namerange, newname) to change the name of the variable. You’re also going to be interested in LanguageElement’s “FindAllReferences()” method, which returns an IEnumerable of IElements.  You’ll need this in order to pass to CodeRush.Source.GetLanguageElement(IElement) so that additional LanguageElements correspond to additional instances of your element besides its declaration.

And, finally, if you want to check certain properties of a language element (is it private, protected, etc., what its parent element is, etc.), you will need to cast it to AccessSpecifiedElement.

This is not incredibly intuitive, so I’m hoping that this helps people — at least by pointing in the right direction of which types and classes to look at in the meta-data or to play with.

Adding your action to menus

This part is relatively straightforward once you know what to do, but it took me a while to figure that out. I was looking to create something like this where I could right-click inside the class and apply my conversions:

Context Menu

So, as it turns out, if you right-click on your action in the designer and display the properties, you can set this all through the properties. I’ve circled the ones that I needed to set in order to achieve the desired effect in the previous screenshot. If you want to create another layer of sub-menuing, I have no idea how this would be achieved. But, I don’t want to do that right now, so that’s that.

Adding to the context menu

If you want to add it to one of the existing menus in Visual Studio like the edit menu or the DevExpress menu, you can do that too.

Switching out of Development Mode

When you’re finished with developing and ready for your plugin to be loaded automatically when Visual Studio and DXCore startup, navigate to the project’s AssemblyInfo.cs and edit the properties of the assembly DXCoreAssembly. Change “PluginLoadType.Demand” to “PluginLoadType.Startup”, and now your plugin will be available for loading at startup. You will still need to configure it in the DevExpress plugin manager.

An interesting thing to note is that DXCore’s plugin creator automatically sets the build output to go in the DevExpress plugins directory (DevExpress\IDE Tools\Community\PlugIns). So if you want to redistribute this guy, you can just grab the DLL from there and email it to your friends, or whatever.

Follow Up

This is very much a work in progress, and I expect to polish this tool more as I use it. I may revisit this post and edit a bit if it needs it or create follow-up posts if there is interest. One thing that comes to mind off the top is that I plan to disable the conversions menu item if the user does not click inside a class. Other nice features might be to play with and set some default settings on the context picker for users to have some guidance when creating keyboard shortcuts.

If anyone has questions, comments, or suggestions for improvement, all are welcome.

Edit: I just now uploaded a slightly modified version of the plugin about a day after this post. I discovered that I local variables were not being modified properly in methods if they were nested in any kind of scoping delimiter, like an “if” statement or a try/catch block. The reason for this was that I was previously checking to see if the AccessSpecifiedElement had a parent of type Method, not realizing that these other scopers were considered logical parents. I modified that code to instead call GetMethod() and check to see if it was null. There’s doubtless some better heuristic for distinguishing locals, but this one seems to work.

Edit2: I have created a new post detailing additional progress on this matter.


Adding CodeRush Templates

Today I’m going to briefly describe one of the cool and slightly more advanced features of CodeRush in a little more detail. But first, a bit of background. One of the many things I found enjoyable about CodeRush is the templated shortcuts, ala VS code snippets but better. I found myself typing “tne-space” a lot for generating:

throw new Exception("");

with my caret placed in the quotes within the exception. However, I would dutifully go back and modify “Exception” so that I wasn’t throwing a generic exception and arousing the ire of best-practices-adherents everywhere. That rained on my parade a bit, as I found the time savings not to be optimized.

I decided that I’d create specific templates for the exceptions that I commonly used, and I am going to document that process here in case anyone may find it helpful. This is a very simple template addition and probably a good foray into creating your own CodeRush templates.

The first thing to do is fire up Visual Studio and launch the CodeRush options, which, in the spirit of CodeRush, can be short-cutted by using Ctrl-Alt-Shift-O. From here, you can select “Editor” from the main menu and then select “Templates.” This will bring up the templates sub-screen:
CodeRush templates

From here, you can either search for “tne” or navigate to “Program Blocks -> Flow -> tne”:

Create duplicate

Now, you will be prompted for a name. Call it “tnioe” for “throw new InvalidOperationException(“”);” (You can call it whatever you prefer to type in.) Next, in the “Expansion” frame, change “Exception” to “InvalidOperationException” and click “Apply.”

New Template

Now, when you exit the options window and type “tnioe-space” in the editor, you will see your new template.

As a bonus, I’m going to describe something that I encountered and was driving me nuts before I figured out how to fix it. CodeRush’s options screen remembers where you last were in its navigation tree for the next time you launch it. However, it is possible somehow to lose the actual view of the main tree and get stuck in whatever sub-options page you were in without being able to get back.

To fix this, go to DevExpress->about and click on the “Settings” button. This will open a folder on your drive containing settings XML files. Close the options window in Visual Studio and then open OptionsDialog.xml. Set the Option with name attribute “SplitOpen” to “True” and you’ll have your normal, sane options back.


The Pleasure of Using CodeRush

For some months now, I’ve been using CodeRush/DevExpress express (read: free) version, and I’ve just recently upgraded to the paid version. After playing with it for only a few short weeks, I’ve come to find it indispensable, so I thought I’d log a post highlighting some of my favorite features. These are relevant to C# 3.5 and up in Visual Studio 2010.

  • The “Issues List” is one of the first features that you might notice if you don’t turn it off because it puts various squigglies under things that it flags as issues. This includes dead code, overly-complicated methods, expressions that could be converted to lambdas, etc. This facet of the utility has immediate payoff in that it may make you aware of some coding practices that you hadn’t previously thought were issues. For example, I had squigglies every time I had something along the lines of:

    Foo myFoo = new Foo();
    CodeRush informed me that I could (should) use var instead of the declarative Foo. This took some getting used to for me, since the “var” looks suspiciously like weak typing and reminds me of Visual Basic 6.0 (which I do not count amount my favorite languages) and its “dim.” However, I see the logic in it. Declaring a Foo twice is needlessly verbose and redundant, so CodeRush has been helping me conform to what are, evidently, now best practices.

  • Ctrl-3 to encapsulate selected text in a region. This is simple but cool. I’ve got a bunch of functions or properties that I want to put into a region and I can just hit Ctrl-3, type the region name, and it’s done. (We can discuss the merits or lack thereof regarding regioning somewhere else, but for the time being I’ll simply state that it’s the convention in which I’m using CodeRush).
  • “mv”-space. This guy creates a new private void method and highlights the method name. So, you type mv-space, type the name of the method, hit enter, type your parameters, hit enter, and you’re off. Also, if you don’t like the method as private, you can hit alt-up/alt-down and cycle the visibility of the method.
  • “tne”-space. (In general, {expr}-space is the CodeRush paradigm for executing ‘templates,’ which are similar but more sophisticated than code snippets in Visual Studio.) This creates the code:

    throw new Exception("");
    and it places your cursor inside the quotes. I think that the default is to have it predicated by String.Format, but it’s seemed to learn that I’m more likely to throw exceptions with no variables than I am to include them in a formatted string.

  • NumberPad +/- highlights growing/shrinking amounts of text, respectively. So, if your mouse is on a string inside a method call that’s inside a method inside a region, continuously hitting + will highlight the string, then the method parameters, then the method call, then the whole method that you’re in, then the whole region, then the class. Minus will take you back down again. Very handy.
  • Tab to next reference. If you place the cursor over an identifier and start hitting tab, you can cycle through instances of the identifier in the code. Hitting escape will take you back to where you started. This is a huge improvement over Ctrl-K, R (find all references) in Visual Studio, which displays in a different window.
  • Smart Cut. One of the things I very much enjoy is being able to put my cursor at the beginning of a line, hit Ctrl-C, and then paste the line. There are a lot of other features of Smart Copy as well, but that one really sticks out for me as handy. Generally speaking, I try to avoid the mouse as much as possible, and this is a help.
  • Camel Case Navigation. Much like Ctrl-Arrow moves in chunks and Ctrl-Shift-Arrow highlights words in chunks, using the same while also holding down Alt navigates that way through CamelCaseWords.

Acknowledgements | Contact | About | Social Media