dotnet, ndepend comments edit

I recently updated to NDepend 4. I got an early preview of the sweetness that is CQLinq (code query using LINQ syntax) so I couldn’t wait to dive into the full deal.

For new users of NDepend, the “getting started” part of things isn’t too different from NDepend 3 - same download/unzip/run xcopy-style installer, same UI, same super-robust reporting. I wrote a good entry on getting started with NDepend 3 and most of that still applies here so I won’t rehash it.

NDepend home

For existing users of NDepend, CQLinq is really the big deal in this latest release. That alone is really worth the price of admission. But there are also some other cool things in there. Let’s take a look.

First, CQLinq. If you’ve written code queries in the old SQL style of syntax, you’ll love the new LINQ style.

Let’s say you want to find all the methods that start with “To” in your project (like “ToString()” or “ToDecimal()”). The old SQL style query looks like this:


The new CQLinq looks like this:

from m in Methods where m.NameLike("^To.*") select m

Or you can use the extension method style of LINQ syntax if you like that better (which I do):

Methods.Where(m => m.NameLike("^To.*"))

In this simple example it may not be too clear what the power is. But if you look at the result set, you see both your methods and methods from the framework assemblies you referenced. Let’s work in another of the features of NDepend - analyzing “JustMyCode”:

JustMyCode.Methods.Where(m => m.NameLike("^To.*"))

Now the result set is just the methods from your code. Oh, but that includes some crazy ToString methods that the compiler generated. Let’s remove those, too, and maybe even order the result set for easier reading.

JustMyCode.Methods.Where(m => m.NameLike("^To.*") && !m.IsGeneratedByCompiler).OrderBy(m => m.Name).Select(m => m)

The results of the query look like this:

Demo query results in

Now, that’s pretty sweet.

All of the base queries have been rewritten in CQLinq so you can really see some great uses. Here’s the built-in query that checks to see if your constructor is calling any virtual methods:

warnif count > 0
from t in Application.Types where
   t.IsClass &&
  !t.IsGeneratedByCompiler &&

from ctor in t.Constructors
let virtualMethodsCalled = from mCalled in ctor.MethodsCalled
                           where mCalled.IsVirtual &&
                                (mCalled.ParentType == t ||
                           select mCalled
where virtualMethodsCalled.Count() > 0

select new { ctor ,
             t.DerivedTypes }

You can really dig into your code like this. I find this way easier to use than the previous SQL-style syntax.

Now here’s the bit that sort of blows me away:

You can use this API to write your own custom analysis tools.

This is also a new thing with the 4.0 version of NDepend. NDepend comes with a bunch of sample applications that show you how to use the NDepend API. There’s also plenty of online documentation. I will warn you, this isn’t for the faint of heart. If you’ve ever written a custom FxCop rule, it looks to be roughly that level of complexity. The trouble isn’t in running the CQLinq to get your analysis results - that’s the easy part. The complexity is in getting the analysis results in the first place. You’ll most likely want to make heavy use of the sample code and “borrow” from it when making your own tools.

Once you build the sample app, you get a console app with some old-school console menus that show you different options.

NDepend Power Tools

I thought I’d try the duplicate code detector. Here’s the output running it on one of my projects (I had to blur a few things out, but you get the idea):

NDepend duplicate code

Not pretty, but you can see the power there. You could do all sorts of things with that - Visual Studio add-ins, PowerShell scripts for analyzing across solutions… all sorts of ideas. (Keep in mind that with CQL and CQLinq you can basically replace FxCop rules with queries. Using the API is primarily for more in-depth analysis tools. My point in saying the relative difficulty is around the difficulty of writing for FxCop is that with FxCop there’s a lot of interesting custom stuff you have to learn to wire things up - the object hierarchy, the way you get analysis results, the way you insert yourself into the process, etc. It appears there is roughly that level of learning to be done to write a power tool using NDepend.API. That said, if you’re just interested in doing analysis and querying… you can just write CQLinq pretty easily inside NDepend and skip the API part.)

With the power of CQL and CQLinq comes a little bit of a learning curve in the form of some hard-to-diagnose gotchas when things aren’t finding what you expect. I found a couple while crafting the above example query:

  • You have to add a Select after an OrderBy or you get an error. Notice in that last example query I order the list of methods by name. In standard LINQ, you order it and you’re done. In CQLinq, you get an error telling you that you need a Select after that. So… add a Select and you get the ordered list as you expect.
  • IsGeneratedByCompiler doesn’t mean “has the CompilerGeneratedAttribute.” If your application has, say, some generated web proxy classes or some things that have the [CompilerGenerated] attribute on them, you won’t find them by using the IsGeneratedByCompiler predicate. IsGeneratedByCompiler only finds things that really were generated by the compiler
    • iterators, anonymous methods, that sort of thing.

Learning about NDepend takes effort. It’s not something you’ll just “figure out” without watching the videos or reading the docs. And there’s a lot of documentation. And a lot of videos. It’s thick, it’s technical, and it’s hard to get through. In some cases, the language/phrasing of the documentation belies that the author isn’t a native English speaker, which makes it sometimes a bit harder to parse for a native speaker like myself. Stick with it, though. It’s worth the effort, especially if you’re working on a larger enterprise project. Not only is it a great way to learn about NDepend, it also helps you learn about good code quality and metrics used to analyze code.

Speaking of doc, you can find it everywhere. Even in tooltips. Hover over a part of a CQLinq query and you get doc for that element:

NDepend support is really good. I think Patrick does it all by himself, so when you ask a question, you get an answer straight from the source. We worked through a recent weird issue and resolved it almost in real-time.

The UI continues to be a little confusing. Each version gets better, guiding you to steps like “what to do next,” and given the robustness and complexity of what NDepend is doing I don’t know how I’d do it better… but there are still little things that get me. For example, I updated the location of analysis report output and wanted to re-run the report, but couldn’t find the option to do that. It turns out the ability to re-run the analysis isn’t in the Analysis menu - it’s behind this little button in the bottom right corner of the window.

The button in the bottom right corner of the window is really

IntelliSense in the query window can sometimes be frustrating. Maybe I type too fast, but I find that sometimes it autocompletes when I didn’t want it to, or the cursor “jumps around” as I backspace. This isn’t new in 4.0 and I can’t consistently reproduce it.

The mouse scroll wheel doesn’t do what you think it does. Normally in a window with a scroll bar, scrolling the mouse wheel will scroll the window up and down. Zoom is usually done by holding Ctrl and scrolling. In the Dependency Matrix view the mouse wheel zooms without holding Ctrl (even though there’s a scroll bar and I generally want to scroll more than I want to zoom in that window). In other views, the mouse wheel does nothing - even if there is both zoom and scroll available. Definitely takes some getting used to.

My NUMBER ONE problem with NDepend, though, persists to this day: You STILL can’t use environment variables in framework folder paths. For example, I may have Windows installed on my C:\ drive but moved Program Files to D:\. If I set up an NDepend project on that machine, I won’t be able to use it as part of my build because the build server doesn’t have the same setup. I’ve reported this to NDepend support, so they’re aware, but it’s still never been fixed. It’s a small thing, but in an environment where you truly need NDepend - a large, enterprise shop with build server farms and lots of developers and architects - this is a huge oversight.

Despite all that,NDepend is a totally valuable tool. If you think your code is good now, run it through NDepend and dig in. You can make your good code great.

Full disclosure: I got a free personal license from Patrick at NDepend. However, we have also purchased several licenses at work and make use of it to great benefit.

UPDATE: After the initial posting of this article, I got some answers on how to do some of the things I was stuck on, so I added that info.

dotnet, vs comments edit

I write a lot of API documentation. I do it to help the people consuming my code… and to help me a year from now when I have to come back and can’t remember how the thing works. I have CR_Documentor out there to help you see what your docs will look like rendered, but sometimes you also need help getting the content right.

Your first stop should beGhostDoc to get some basic bits in place. GhostDoc doesn’t actually write good documentation, but it can help you get things started. After that, though, you may need some easy ways to get some of the fancier tags in there or a little bit of standard shorthand to get things in place. That’s where CodeRush templates come in.

CodeRush templates are like magic macro expansions. You type a little text and hit the expansion key (usually a space or tab, pending on what you have configured) and magic happens. I say magic because you can do a lot with templates beyond just expanding some text. You can add required namespace registrations to a file… you can do different things based on context (are you in the code editor or in the designer? HTML or XML?)… you can insert content from your clipboard… Lots of stuff.

You can set up some pretty nice templates for helping you write standardized documentation. Here’s how.

First, open up the CodeRush Options window (Ctrl+Shift+Alt+O or DevExpress -> Optionsfrom the Visual Studio menu). On the left side, in the tree view, expand the “Editor” node and select “Templates.”

At the bottom of the Options window, select the “*Neutral*” language. Do this so you can add the expansions to work for both VB.NET and C# and keep them together. Otherwise you have to switch back and forth between the two languages every time you want to modify or add a template.

At this point, stop for a second. I’m going to walk you through how to make your own templates, but at the end of the article I’m also going to let you download some I’ve already made to get you jumpstarted. If you download/import the ones I made, you don’t need to do this next step where you create the “XML Doc Comment” templates folder. Importing mine will create this for you.

Create a new folder to hold your XML Doc Comment templates [if you’re not downloading/importing mine first]. Right-click somewhere in the middle tree-view area, select “New Root Category…” and give it a good descriptive name like… “XML Doc Comments.”

You can make any other sort of hierarchy in there that you want. If you import my templates, you’ll see some folders for canned documentation blocks, some inline expansions, list templates, and some general standard block comment types.

Now I’ll walk you through creation of a simple template. One of the templates in my pack will expand the word null in an XML doc comment to <see langword="null" /> so you get the proper expansion/highlighting when it renders. I’ll show you how to create that and set the appropriate values so you don’t end up with XML doc comments in the middle of your code.

Select a folder for a new XML comment template and click the “New Template” button. Type the key combination you want to expand. In this case, put “null” in there.

Fill in the “comment” for the expansion and the actual text you want to see when it’s expanded. Also check the “case-sensitive” box because you don’t want “Null” or “NULL” expanding.

The last and most important thing is the context for the expansion. You want your template to only run when:

  • The active language is C# (you can set up a similar “Nothing” expansion for VB, which comes with my template set).
  • There is no selection in the editor.
  • You are typing code (not in the designer).
  • You are working in an XML doc comment (not in executable code).

To accomplish this, there are three boxes to check in the context tree view below your macro expansion:

  • Editor/Code/InXmlDocComment
  • Editor/Selection/No Selection
  • Language/C#

There is a very, very rich context selection mechanism in CodeRush, so I won’t show you the entire tree view with all of the boxes selected - I’ll just show you the C# box here, but you need to check all three boxes.

Click “OK” to save your template and close the Options window.

Now, in a C# code editor, start an XML doc comment like this:

/// <summary>
/// Template test for null
/// </summary>
public class TestClass

Press “space” after the keyword null in that XML doc comment. You should see it expand to:

/// <summary>
/// Template test for <see langword="null" />
/// </summary>
public class TestClass

Pretty simple, right? Now you can just type your doc comments and not have to think about expanding that markup.

Like I mentioned before, I’m going to let you download some templates I use.

First, download the zip of the templates. It has one XML file in it - the exported set of templates. Unzip that file somewhere you’ll remember. Now, in the Options window, after you select Editor/Templates and set the language to “*Neutral*” (as outlined in the steps above), right-click in the center tree view area and select “Import Templates…”

Select the XML file you downloaded and unzipped. (Don’t select the ZIP file, that won’t work. You need to unzip it first.) Once you’ve done that, you’ll see a bunch of templates available to you:

There is a lot here, so I recommend you explore and see what’s there, what’s useful, etc. Conventions I used in naming templates:

  • Documentation blocks/elements are generally prefixed with “d” (for “documentation”).
    • “ds” - document <summary> content.
    • “dx” - document <exception> content.
    • “dp” - document <param> content.
  • One-liner tags just start with “x” (for XML) because there’s no content.
  • Keywords that expand are the exact keyword (e.g., “null”) so you don’t have to think about it.
  • List template expansions start with “l”.

Some particular highlights I use almost daily:

  • dxargnull expands to standard <exception type="System.ArgumentNullException"> documentation for when a parameter is null including a placeholder for parameter reference info.
  • dxargempty expands to standard <exception type="System.ArgumentException"> documentation for when a parameter is empty including a placeholder for parameter reference info.
  • <see langword="..." /> expansions for all of the standard C# language words (null, abstract, true, false, sealed, static, virtual) and VB.NET language words (CanOverride, False, MustInherit, Nothing, NotInheritable, Shared, True).
  • xseealsome expands to a <seealso cref="..." /> link where the link destination is the current type you’re working on. xseeme does the same thing, but <see cref="..." />
  • lb starts you a bullet list with one item.
  • lt starts you a table with a header and one item.
  • li creates a new list item with both the <term> and <description> elements.

Again, you’ll only see these things expand in XML API doc comment context, so you shouldn’t worry about crazy things happening in your code - it’ll just help you write doc faster. And if I have templates you don’t like, you can always import what I’ve got and delete the stuff you don’t want. It should all import into the same folder, so it won’t “corrupt” your other settings.

Tips for writing your own doc comment templates:

  • Pick a consistent set of template naming schemes. I outlined mine, above, but if you don’t like that one, pick something different. It’s good if it’s consistent, though, because if you have a lot of templates that you don’t use daily, it can be easy to forget what you have. Consistency means you can possibly “guess” if you already have it and you may well be right.
  • Copy/paste contexts. Once you have a working template set up, you don’t need to always manually check all the boxes to set up the context. When you create a new template, right-click on an existing working template and select “Copy Context,” then right-click on your brand new template and select “Paste Context.” All the boxes will be checked for you.
  • Pay attention to the little “Command” dropdown beneath the “Expansion” box. It inserts things that can help you out in your template. For example, selecting “Caret” in there will place a special marker «Caret» into your template. After your template finishes expanding, this is where the cursor will end up and where you’ll start typing. The “Paste” command can insert data you have on the clipboard. Make use of things like this to make powerful templates. I use many of these in my templates.

Finally, if you’re looking for tips on writing good XML documentation, check out my previous article on the subject.

[Download my XML Doc Comment templates]

windows comments edit

I had a tiny breakdown yesterday where I finally got Windows 8 installed (on a Hyper-V VM) and hit a massive “someone moved my cheese” moment where I basically couldn’t figure out how to do anything. The Windows key wasn’t doing anything, I couldn’t figure out just the right spot to right-click… bad times. My Google-fu totally failed me, too.

This morning, with a fresh set of eyes, suddenly looking for the same search terms yielded two super-helpful articles. For those in the same [late] boat as me…

javascript, gists comments edit

I just spent like six hours trying to figure this out, so profit from my experience.

I have some custom code wiring up jQuery Validation in a form and for some reason, the jQuery “html” method was causing a “HIERARCHY_REQUEST_ERR: DOM Exception 3” whenever validation errors were being displayed. After banging my head against it for a while and getting some help from a co-worker, we found it came down to the $.each iterator.

I was compiling up a list of error messages and using the $.each to add them to settings for a jQuery validator. It looked something like this:

var parsed = {
  required: "A is required",
  notEqual: "A must not equal B"
$.each(parsed, function(rulename){
  options.messages[prefix + rulename] = this;

As you can see, I wasn’t doing a straight extension - I needed to add a prefix to the hash key, so I iterated through. The gotcha is that this in the iterator loop isn’t actually literally the same as the value of the item.

More explicitly:

var parsed = {
  required: "A is required",
  notEqual: "A must not equal B"
// typeof parsed.required === "string"

$.each(parsed, function(rulename){
  // typeof this === "object"
  options.messages[prefix + rulename] = this;

That type conversion was what was causing the problem. Way down the line, after wiring everything up to jQuery Validation, the validator would try to do something roughly like this:

$("<span />").html(message)

At the time of execution, message wasn’t a string, it was an object, so the DOM threw a tantrum and resulted in “HIERARCHY_REQUEST_ERR: DOM Exception 3”.

The answer is to not use this in the iterator. Instead, provide the second parameter to the iterator function that brings along with it the original item value:

var parsed = {
  required: "A is required",
  notEqual: "A must not equal B"
$.each(parsed, function(rulename, message){
  options.messages[prefix + rulename] = message;

That way the string value isn’t boxed into an object and you won’t lose the type information.

android comments edit

I recently upgraded my phone to a Samsung Galaxy SIII. So far, seriously, this thing is awesome. It’s fast, I love Android 4.0, the screen is super clear, the camera is nice… serious win over my older Droid X.

One of the things Samsung seems to be pushing is the NFC (near field communication) abilities of the phone. They have these little NFC tags you can buy called “TecTiles” that you can use to play with NFC. They have an Android app you can use to program the tags or use them to execute programs from tags read by your phone.

I figured I’d try out some of these TecTiles and see what it’s all about.

TecTiles are small, about an inch square, and are stickers. Here’s one still on the backing paper:

Samsung TecTile NFC

They run roughly $3 each - you get them in a pack of 5 for about $15, though sometimes you can find them a little cheaper.

To program them, you first open the TecTiles app.

Samsung TecTile app: Pick a TecTile

From there, you can pick what you want the TecTile to do. You can choose from “Settings & Apps” (have it change phone settings or launch an app); “Phone & Text” (have the phone make a call, send a text, or add a contact); “Location & Web” (do a Facebook or Foursquare check-in or visit a web site); or “Social” (update Twitter or Facebook status, connect on LinkedIn).

For this walkthrough, I’ll choose “Settings & Apps.” Once you do, you get asked what sort of tag you want to make.

Samsung TecTile app: TecTile

I chose “Change Phone Settings.” Then you get to choose which settings you want to change.

Samsung TecTile app: Change Phone

You can select more than one setting at a time, but for now I just chose to set my phone in Silent mode. The next screen gives you some options about what exactly you want it to do.

Samsung TecTile app: TecTile setting

In this case, I want the tag to set my phone into Silent mode. This is something I might put on my desk at work so when I get in I can scan the tile and have it in “work mode.” Once it’s all set, you’re ready to program the TecTile.

Samsung TecTile app: Write

You just hold the phone over the little TecTile sticker, magic happens, and it’s programmed. You’ll notice there are options to “lock” the TecTile so you can’t re-program it. If, for example, you put your business contact info on the TecTile and stuck that on the front register at your store, you’d lock the tile so no pranksters overwrite it. There’s also an “allow multiple writes” option to allow you to re-use the program across multiple TecTiles. (I was actually hoping this option would allow me to make more complex programs by writing multiple “tasks” to the same TecTile, but, alas, no.)

To use the TecTile, you just sit your phone next to it/on it. Depending on what the TecTile is programmed to do, sometimes it brings up some info directly, but generally it seems to do most actions through the browser. For example, when you update Twitter status, it does it through the browser inteface, not the Twitter app. Here’s the weird bit - in the case here, where I’m setting my phone to silent mode, you still get an alert that the browser is launching:

Scanned TecTile: launching the

But when I click “OK,” the browser doesn’t come up - instead the TecTile app takes over and notifies me my phone is going into Silent mode.

Samsung TecTile app: Reading

Then that screen disappears and I go on my merry way.

I liked that it was pretty simple to get working and seemed novel… but I have to admit I’m a little disappointed. The list of available actions right now is pretty small:

Settings & Apps

Change Phone Settings

  • Alarm Time
  • Alarm Switch
  • Car Mode
  • Night Mode
  • Bluetooth
  • WiFi
  • Silent
  • Ringer Volume
  • Music Volume
  • Automatic Brightness
  • Brightness

Launch an App

Join a WiFi Network

Show a Message

Phone & Text

  • Make a Call
  • Send a Text Message
  • Share a Contact
  • Start a Google Talk Conversation

Location & Web

  • Show an Address or Location
  • Foursquare Check In
  • Facebook Check In
  • Open a Web Page


  • Update Facebook Status
  • Facebook Like
  • Tweet a Status
  • Follow a Twitter User
  • Connect on LinkedIn

I mean, that doesn’t look small, but the first thing I wanted to do was set my phone in Vibrate mode since I use that at work, not Silent. But… no luck. Then I thought it would be neat to do a Latitude check-in since I use Latitude, not Facebook or Foursquare. Nope.

The “Send a Text Message” action doesn’t work right now, which is the first one I actually tried (after not finding Vibrate mode or Latitude check-in) but it seems they’re having problems with that. The most recent update says it fixed some problem with sending messages, but it doesn’t look fixed to me. (You scan the tile and then… back to the home screen. Nothing.)

Another thing: You can’t do any complex actions. For example, if you wanted a tile at work that turns your phone to Silent and then checks in… nope. That’s two tiles, not one.

In the end, I don’t really feel ripped off or anything. I’m having fun messing around with them, and I know I’m pretty early to the party on this, so I have faith they’ll beef up the offering as time goes on. However, from a practical standpoint, it doesn’t do all the stuff I’d like it to.

On a final note, for a more “real world” type of scenario, check out NameBump. These guys make NFC-enabled business cards. Hand your card to a potential client, and they can scan it with their phone to get your contact info in their phone instantly. That’s pretty slick and seems to me a great use of NFC. You could do something similar with TecTiles if you wanted - just program the TecTile and stick it to your card. Or, if you’re at a trade show, stick it to your vendor badge and hold it out for people to scan. I may have to do this for the next conference I go to. Rather than exchange cards, “Here

  • scan my badge.”