Mark Miller
  • CodeRush 13.1 - Enhancements to the Visual Studio Debugging Experience

    With the release of CodeRush 13.1, we have made several significant enhancements to improve the Visual Studio debugging experience, shedding more light on some of the more challenging-to-discern aspects of debugging.

    XAML Bindings in Silverlight 5

    Now when stepping through Silverlight 5 XAML binding code you’ll see previews of the binding properties. Gone is the need to bring up the Locals window, open the BindingState object, and then find and open the FinalSource property. Now the information you need is right where you’re looking – in the code.

    DV in SL5 
    Instantly see binding properties without looking away from the code, reaching for the mouse, or pressing excessive keystrokes.

    Improved Support for Exceptions and the Call Stack

    To make finding bugs even easier we’ve added the Call Stack and Exceptions (CS&E) tool window. While at first it may appear to be simply an easier way to read call stacks, like CodeRush itself, it’s more than a pretty face. It is especially handy when debugging asynchronous code.

    To show how useful it is, first let’s look at the typical Visual Studio asynchronous code debugging experience. We’ll measure the impact on usability along the way – if this gets too crazy for you, you can jump ahead to the “Now let’s try it with CodeRush…” section below.

    Async Debugging Experience in Visual Studio (without CodeRush)

    First the exception is thrown. Visual Studio stops execution here:


    VS Usability Impact so far: 1 target area visually scanned, 3 seconds invested

    Hmm. That’s not very helpful. Of course, Visual Studio also presents this dialog:


    Where’s the useful information? We have no indication of what code caused the problem.

    VS Usability Impact so far: 2 target areas visually scanned, 7 seconds invested

    Next you look at the call stack. It looks like this:


    Also, not useful.

    VS Usability Impact so far: 3 target areas visually scanned, 11 seconds invested. We’re going nowhere fast.

    OK, let’s go back to that exception helper window. Let’s click the “View Detail…” link.


    VS Usability Impact so far: 1 click, 3 target areas visually scanned, 12 seconds invested

    Here comes the View Detail dialog. It looks like this:


    No useful information yet. Good thing our hand is on the mouse. Move it up to the triangle and click it.

    VS Usability Impact so far: 2 clicks, 4 target areas visually scanned, 14 seconds invested

    Now we see this:


    Scanning this data, your eyes may have noticed the InnerException. What’s that all about? Let’s open it up. Click the triangle to the left of the InnerException node.

    VS Usability Impact so far: 3 clicks, 5 target areas visually scanned, 17 seconds invested

    You probably have to resize and scroll to see this data.

    VS Usability Impact so far: 4 clicks, 1 scroll, 5 target areas visually scanned, 20 seconds invested

    The contents of that InnerException node look like this:


    OK, so it feels like we’re getting closer. After visually scanning the InnerException child nodes, we can see three important pieces of information:


    The InnerException of this InnerException is null (which means we’re near the root of the problem). The Message tells us a parameter called “address” is null, and we have a stack trace that may finally be useful.

    VS Usability Impact so far: 4 clicks, 1 scroll, 6 target areas visually scanned, 26 seconds invested, and it seems we’re almost there.

    Let’s open up that stack trace.  First, click anywhere on that StackTrace line in the dialog. Then click on the drop down button to the right. If your Visual Studio is like mine, you’ll see something like this:


    Lovely. As an exercise in futility, try to read that wrapped call stack to figure out where your problem is. There is actually more to the call stack than you see in this drop down, unfortunately there’s no scroll bar to tip you off to that fact.

    After more clicking, scrolling, and reading (both above and below the visible parts of the call stack above), we might infer that our problem is at the topmost position of the call stack that references our application code:

    WindowsFormsApplication1.MailSenderAsync.<SendEmail> in MailSenderAsync.cs (line 27)

    VS Usability Impact so far: 7 clicks, 2 scrolls, 9 target areas visually scanned, 33 seconds invested, and it seems we’re farther away than we thought.

    So now we look at the code. Since there's no navigation support built in, we need to close this stack of windows.

    VS Usability Impact so far: 10 clicks, 2 scrolls, 9 target areas visually scanned, 36 seconds invested.

    Next we need to get to line 27 of MailSenderAsync.cs and take a look:

    VS Usability Impact so far: 11 clicks, 2 scrolls, 5 keystrokes, 9 target areas visually scanned, 41 seconds invested.


    Let’s press Ctrl+Shift+Space to see the parameter tool tip for the MailAddress constructor.


    Excellent! We’ve found the parameter named “address”. Getting closer.

    VS Usability Impact so far: 12 clicks, 2 scrolls, 8 keystrokes, 9 target areas visually scanned, 44 seconds invested.

    OK, so the “sender” parameter must be null. But how did we get here? How do we fix this? Unfortunately, after almost a full minute of clicking, scanning, and reading, we’ve only scratched the surface of understanding the problem. Typically the next step is to set a conditional breakpoint to stop when sender is null so we can investigate the call stack in more detail.

    From the Usability Count we’ve been maintaining it seems we’re investing a lot of development time going nowhere. We might need to set a breakpoint and try this again, or scan the call stack from the inner exception again to find out how we got here and find out how sender is getting a null value. Even a guru developer may be several seconds, if not minutes away from discovering the answer.

    Let’s compare this experience with Visual Studio on some serious family-friendly steroids, err CodeRush, plus our new CS&E window.



    Now let’s try it with CodeRush…


    By the way, if you already have the latest version of CodeRush installed, we recommend starting a new debug session (create new project and run it) right now and then open and dock the CS&E window at your favorite place in the editor while VS is in debug mode. This one-time step will get Visual Studio to remember this position and make sure the CS&E window is there for you in future debug sessions.

    I’ll wait while you do that.

    DevExpress | (CodeRush) | Tool Windows | Call Stacks and Exceptions. Smile

    OK, ready? Here’s how easy it is to find the bug with CodeRush:

    Starting with the same code and the same place as the previous example, click this link:


    CR Usability Impact so far: 1 click, 1.5 seconds invested.

    The CS&E window immediately looks like this:


    We’re debugging Async, so we know this outer call stack isn’t interesting. Instead we click the “Show inner exception” link above the stack.

    CR Usability Impact so far: 2 clicks, 3 seconds invested.

    Now we see this:


    Do you see that? The CS&E window is ACTUALLY HIGHLIGHTING the line of code contributing to our “sender equals null” problem. No need to visually scan the call stack. Just click the “MailSenderAsync.cs line 21” link, and we’re immediately inside this code:


    Are you kidding me? The Sender field variable, the parameter to the SendMail overload is ACTUALLY SELECTED. It’s actually selected, kids, drawing your eyes right onto the source of the problem, explaining how the sender parameter became null – the Sender field variable, passed into the method from line 21, was null. Now we’re much closer to understanding the problem. Nice.

    CR Usability Impact so far: 3 clicks, 5 seconds invested.

    When you’re debugging asynchronous code, the difference is huge. Here are the usability totals for this example:

      Visual Studio (alone) VS + CodeRush
    Clicks 12+ 3
    Scrolls 2+ 0
    Keystrokes 8+ 0
    Areas Visually Scanned 9+ 0
    Time invested 44+ seconds 5 seconds

    This is good stuff. CodeRush helps you stay focused on the code instead of wasting time struggling with suboptimal UI.

    Important notes about the CS&E window:

    • Make sure you have the “Automatically paste exception or call stack from clipboard” button in the down state to get this seamless ease of use.
    • You can copy call stacks and exception data from any location (including Visual Studio’s Call Stack window).

    This last point means you can send a call stack to a team member and they can copy it to the clipboard and see it inside the CS&E window, and they can use it to explore the same version of the code, EVEN IF THEY ARE NOT DEBUGGING. Impressive.

    Dead Path De-emphasis

    CodeRush de-emphasizes code on dead paths (e.g., outside the current execution path). Conditional blocks that won’t be executed on the current pass are grayed out, so as you’re stepping through code it’s even easier to focus on the code that will be executed.

    Code along the dead path (e.g., inside the conditional block) is grayed-out. We won’t be stepping into that block in this pass.

    Recursive Method Depth Counter

    CodeRush now displays a counter indicating the depth of recursive method calls. The counter appears when a method is called from itself at least one time.

    The Recursive Method Depth counter shows how deep you are into that method’s recursive call stack.

    The recursive call indicator reveals how many times the method appears on the call stack, so “2” is shown on the first recursive call.

    New Actions, New Options, and Other Debug Visualizer Improvements

    The following actions and default shortcuts are now available:

    • Toggle Expression Values - Ctrl+Shift+Alt+F10
    • Focus Next Expression - Tab
    • Focus Previous Expression - Shift+Tab
    • ToggleDebugVisualizer - Ctrl+Alt+D

    We have added a “Show historical values” option to the “Editor | Debug | Visualizer” options page. It specifies whether to show values only for the current code line or for all code lines within the current method. I prefer seeing a full history, however you may prefer a more compact display as you work.

    In Visual Basic, CodeRush now shows icons indicating whether the current Boolean expression is true or false for “case” statements.

    The Debug Visualizer is smarter and able to automatically preview more expression types than before.

    CodeRush smoothly adjusts line height when showing or hiding debug visualizer visual elements (expression values or Expression Explorer). This results in a smoother debugging experience and keeps your eyes on the important data.

  • New XAML features in CodeRush 13.1 for Visual Studio

    CodeRush 13.1 includes a number of new features to make working with XAML easier.

    Navigation Support

    The Declaration navigation provider is available in XAML code now. You can use it to navigate to:

    1. Control declarations
    2. Types
    3. Properties
    4. Resource keys
    5. Named controls
    6. xmlns aliases


    Code Completion

    With CodeRush 13.1 installed, Visual Studio’s XAML Intellisense is smarter and more capable. CodeRush suggestions are integrated with the Intellisense window, and include:

    • Available continuations for Binding path expressions and TemplateBinding arguments
    • Binding.ElementName, Setter.TargetName, and Trigger.SourceName values
    • Resource key completions for StaticResource and DynamicResource markup extensions.


    New Code Cleanup Rules for XAML

    The following XAML specific code cleanup rules are new for 13.1:
    Remove All Comments – removes all XAML comments.
    Remove Default Values – removes control attributes initialized to default values.

    Code Providers

    Declare XAML Namespace Reference

    This CodeProvider declares a new XAML namespace reference for the active qualifier.


    If the type resolves to multiple locations, a submenu will appear allowing you to select the namespace to declare.


    Declare All XAML Namespace References

    This CodeProvider declares multiple namespace references for every qualified control that can resolve to a single declaration. This refactoring can be useful after pasting XAML fragments from another source.


    Seven New Grid CodeProviders

    CodeRush 13.1 includes seven new Grid CodeProviders, which makes it much easier to work with controls inside XAML Grids.

    Insert Columns/Rows

    These CodeProviders insert the specified number of columns or rows at the specified location, shifting control position as needed. This CodeProvider can save a huge amount of time if you need to add a column or row to an existing grid. In the example below, we effortlessly add two rows to an already complex grid, shifting 50 control positions down automatically.


    Position Control

    This provider allows you to visually position a control inside the parent grid without reaching for the mouse or risking unintended changes (such as span and margins being set by the Visual Studio designer due to less-than-precise mouse operations).


    Delete Columns/Rows

    These CodeProviders remove the specified number of columns or rows at the specified location, shifting control position and span as needed. Controls contained entirely inside the deleted range will be removed unless the “(keep controls)” variation of this provider is applied.


    All grid manipulation operations are intelligently performed so undo is simple:


    Note: the first 13.1 release omitted the delete column/row providers. The subsequent minor update (and daily builds) include this feature.

    New Templates

    Setting Numeric Properties

    Now setting common numeric properties is fast and easy. Here are your shortcuts:











    Just follow these with a number (1-4 digits) and press the template expansion key. For example, the h149 template, when expanded inside a control’s tag, produces the following:


    Creating Controls

    CodeRush 13.1 includes a new set of dynamic code templates for creating common XAML layouts. New shortcuts for common controls:





























    The shortcuts above work anywhere a control is valid inside XAML. These templates will expand with a unique name. For example, pressing “b” followed by the Space or Tab key will produce the following:


    I should emphasize the name is unique, which is useful when you’re quickly prototyping or presenting to other developers.

    If you want to omit the name from the expansion, just follow the template with a comma (the comma is used throughout the CodeRush template library to produce shorter versions of many templates). So if you want a nameless border, just expand the “bd,” template.


    If you’re expanding one of these controls inside a grid, you can optionally specify the location using one of these modifiers:





    So to place a TextBlock inside row 1, column 2 of the parent grid, you can expand this template:


    This template will do the same thing:


    To omit the name, just follow the template with the comma.

    Modifying templates with grid position like we’ve seen above is optional. And as you might expect, with CodeRush, there is more than one way to get the job done…

    Positioning Controls inside a Grid

    The row and column modifiers seen above also work as stand-alone templates inside the main/start tag of a control. That means you can use any of these templates to set a control’s position within a grid:





    Also, don’t forget the Grid | Position Control provider shown above if you prefer a more visual approach.

    Creating Grids

    Need a grid that’s 3x3? Use the g3x3 template.

    Need a grid that’s 2x5? You guessed it – use the g2x5 template. Creating grids is easy. Just use this format:


    This animation shows how quickly you can set up a grid with the templates:



    Note: the initial 13.1 release of this template limits row and column counts to 9x9. Subsequent releases will increase this to 20x20.

    What’s that you say? You’re more of a visual person? Typing g2x5 is too much work for you? It gets easier. Here’s your new template:


    That’s right kids. You need a Grid of any size? Just hit the letter g followed by the template expansion key (typically Space or Tab, depending on your settings). Here’s what you’ll get:


    Exciting, isn’t it? On Monday I’ll show the cool new features we’ve added to the Debug Visualizer.

  • Here’s Your Game Changer: Debug Visualizer in CodeRush for Visual Studio

    One of the goals of team CodeRush is to release something revolutionary, something with the power to change the way developers work, at least once a year. CodeRush 11.2 was the first tool on any platform to offer duplicate code consolidation. This year CodeRush 12.2 comes out of the gate with another powerful game changer: the Debug Visualizer.

    The Debug Visualizer attempts to eliminate a number of productivity barriers inherent with today’s debugging experience. You may have noticed:

    1. The debugging experience can be slow
    2. Your hands reaching for the mouse to add a watch or inspect a value
    3. Your eyes moving back and forth between code and watched values

    Sometimes when stepping through code you encounter unexpected results. Unexpected results are frequently interesting because they can reveal details about the code that were previously unknown, and they are a smell indicating a logic error or bad data. Unfortunately the time from the moment you see the unexpected result to the moment you understand why is frequently measured in minutes, not seconds. Drilling down into a complex expression or reviewing historical data leading to a potential issue involves way too many mouse clicks and keyboard shortcuts, and may even require a restart in an attempt to catch the problem where it happens. Unraveling complexity is often tedious and may require intense focus.

    The Debug Visualizer is here to dramatically reduce the time between unexpected data and complete understanding.

    Here’s how it works.

    Historic Visual Record

    As you step into a method the Debug Visualizer immediately gets to work, revealing values for any arguments passed into the method.

    Figure 1: The Debug Visualizer acting like a Locals window, but without the messy window.

    Those local values you see just below the arguments persist as you step through this method, serving as a sort of historical document on the original values on entry or assignment, which may be useful if those later change inside the method.

    See Changes Right Where They Occur

    When values change as you step through the code, you’ll see those changes immediately. For example, in the screenshot below we can see the value of surfaceAreaOfCylinder is 0.0.

    Figure 2. An assignment statement before execution.

    Stepping over this line of code updates the local variable’s value, shown in red on the left:

    Figure 3. Now we can easily see which line of code changed a variable.

    Showing Function Results

    One debugging task that takes far too many steps and too much time is determining the value of a function that returns a calculation. There seems to be no easy way to get to this important information quickly.

    Fortunately the Debug Visualizer makes this pain a thing of the past. Now when you step up to a return statement, you can see the value returned before you leave the function:

    Figure 4: Easily see calculated values that functions return.


    Revealing the Future

    In addition to documenting the past, the Debug Visualizer can also reveal the future. Step through the code and you’ll see the values for expressions on the active line before they are executed. For example, in the code below, the Math.Sqrt() call has not been executed yet, however the future result, 42.0, can be seen right below the expression:

    Figure 5:  The future revealed, and the answer is… 42?

    If there is an unexpected value on the current line, many times it’s useful to know this before the line executes. It’s much easier to step into a method call or property getter before the line executes than after:

    Stepping into a Method Call or Property Getter:

    Before the Line Executes After the Line Executes
    OrangeDot Press F11 or Ctrl+Shift+F11

    OrangeDot Move the caret back to the problem line which might be far away if an exception occurred

      OrangeDot Press Ctrl+Shift+F10 to set the active line
      OrangeDot Wait for the line to become active
      OrangeDot Press F11 or Ctrl+Shift+F11

    The future previews are here to save all those extra steps and waiting.

    Values of expressions involving potential side-effects that may impact program behavior are not predicted; you’ll see a Refresh button instead. Click the button or press Ctrl+R to see the values.

    Expression Explorer

    So, what happens when you encounter an unexpected value while debugging? For this section, we’ll use a simple code example, however you might want to imagine this working on an expression with greater complexity.

    Figure 6: An unexpected value.

    With the caret anywhere on the active statement, press Alt+Down to bring up the Expression Explorer.

    Figure 7: Drilling into the expression.

    The Expression Explorer lets you drill into individual expression parts and see their corresponding values. In the screenshot above we can see the result of the call to Math.Sqrt() is 4.58 (we were expecting 5), and that the value of the expression passed into the Sqrt call is 21.0 (expecting 25).

    Once the Expression Explorer is up, you can move around and drill into expression parts with the arrow keys. For example, pressing the Down arrow (using the example code above) reveals the children of the active expression:

    Figure 8. Drilling further...  aSide * aSide == 9.0

    The Node Map to the right shows a hierarchical representation of the expression.  You can click and drag this window to reposition it if necessary.

    Figure 9. The Node Map reveals the active node (emphasized with high-contrast), parent nodes in purple, other nodes in blue, and hidden child nodes in gray.

    Notice the high-contrast active node on the left contains two hidden children (in gray). Sometimes you just want to take a peek at the child node values without actually changing the active expression. We can toggle child expression visibility by pressing the spacebar. Doing so in our example code produces the following:

    Figure 10. Spacebar toggles child expression visibility.

    In the screenshot above, we can see the 9.0 comes from 3.0 * 3.0.

    We can collapse all child expressions with the spacebar as well. Pressing spacebar again produces this:

    Figure 11. Collapsing the child expressions with the spacebar.

    The “9.0” value shown above for the “aSide * aSide” expression is expected, and the child expression values look good. Our problem must be elsewhere. Let’s move right.

    Figure 12. Continuing to explore…

    Expressions and their corresponding values are always left-aligned.

    Figure 13. Values are displayed below a horizontal line that matches the length of the corresponding expression.

    Let’s move down into the child expressions with the Down arrow.

    And to the right with the Right arrow:


    And now we can see our problem. This reference to “aSide” should have been a reference to “bSide”. Now we just need to fix the code. You can close the Expression Explorer by pressing Escape, or by clicking anywhere else in the editor. When the Expression Explorer closes, the code looks like this:

    Figure 16. The Expression Explorer has closed, and we can still see the last values explored.

    With Edit and Continue enabled we can fix the code. As soon as we make any change to the code the Debug Visualizer clears the historical data in the method we’re modifying.

    Figure 17. After editing.

    Of course, after editing, you can show the Expression Explorer again by pressing Alt+Down.

    Figure 18. Results are now as expected.

    Here’s the Expression Explorer in action:


    And here’s the Expression Explorer scaling up to a more complex expression:

    Figure 19. The Expression Explorer scales to handle complex code.

    Why is this Expression False (or True)?

    Sometimes when stepping through code with Boolean expressions an unexpected result appears. For example, you expected the expression to be true, but it is false. Or maybe you expected it to be false, but it is true. When this happens, the Expression Explorer can help you quickly understand why. For example, in this method we want to rent/hire a car. However the Debug Visualizer tells us this won’t happen:

    Figure 20. The Debug Visualizer optionally adorns Boolean expressions with “DebuggerVisualizerTrue” (true) or “DebuggerVisualizerFalse” (false) icons.

    So the question is “why is this expression false?” To find out, press Alt+Down to bring up the Expression Explorer:

    Figure 21. Conclusive Boolean expressions are highlighted (in green) in the code and the Node Map (as squares)

    Now we can immediately see the problem. It’s here, highlighted in green:

    Figure 22. Conclusive Boolean expressions determine the value of their parent expressions

    A parent Boolean expression might contain one or more conclusive Boolean child expressions. In this example there is only one. Let’s navigate into it to get more detail. Press the Right arrow to move right and select the conclusive Boolean expression:

    Figure 23. The conclusive Boolean expression, shown as a square in the Node Map, is selected.

    And now press the Down arrow (or spacebar) to see the children of this expression:

    Figure 24. And now we see why we can’t rent/hire the car.

    Highlighting conclusive expressions is useful for understanding why Boolean expressions are true or false.

    Evaluating Expressions with Side Effects

    Sometimes an expression might contain a method call or property getter access with potential side-effects. If CodeRush is unable to verify that the call is free of side-effects, the Debug Visualizer will display a Refresh button. As long as the line of code is active you can click this button (or Press Ctrl+R) to call into the method and get the result.

    Figure 25. Calls with potential side-effects (e.g., the call to “Exists()”) are highlighted.

    Note that even though an expression preview may be marked with a Refresh button, it may still be possible to drill down into its children to see their values without refreshing. For example, in the screenshot above, the Exists call prevents evaluation of the parent expression, however you can still see an evaluation of the “drive + path” expression.

    The Debug Visualizer is Here Now

    So there’s your game-changer for 2012, kids. Faster expression evaluation, historical record of changes, future reveal, function return preview, expression drill down, conclusive Boolean highlighting and important data always right where you need it – right in the source code. It works in C# and Visual Basic and is available right now in CodeRush 12.2 for Visual Studio. JavaScript support is expected in the next minor update. Give it a try and let us know what you think.



    A file lock issue experienced by some developers has been fixed since the 12.2 release. You can get the update here.

  • Consolidating Duplicate Code in Visual Studio – Easy with CodeRush

    On Twitter last week a developer mentioned a competing developer tool, inferring its clone detection and consolidation abilities were similar to what we were already shipping with CodeRush. Skeptical (I had looked into this tool once before months ago), I decided to dig deeper and found a video showing how to consolidate code with the tool. I watched a developer show step-by-step how to manually consolidate duplicate code found by the tool. Steps included determining the differences between the blocks of code and then manually removing them in each of the duplicated methods, then extracting one of the methods, then copying a method call and pasting it over each of the other duplicate methods. The entire process took nine minutes and 43 seconds. Wow.

    In the video the developer only worked with two duplicates, and those duplicates were both located in the same class; you could see the proposed solution would become incredibly difficult and error-prone to perform manually for duplicates in larger numbers or spread across classes.

    I consider the video a demonstration of how our ancestors used to consolidate code, back in the old days when dinosaurs roamed the earth.

    Here’s how you do it today with CodeRush:

    1. Open the project inside Visual Studio. The screenshots in this post are using the same source code sample I saw in the demo.
    2. CodeRush lists duplicates on the Duplicate Code tool window. Here are the duplicates CodeRush has found (on an extremely granular setting – you can adjust settings in Options):

      In the screenshot above I’ve circled the important differences.
    3. Double-click one of the duplicates. This takes you to the code and brings up the Consolidate Duplicate Code UI.

      The preview hint shows you the duplication will be turned into a single method inside the class UINameHelper.

    4. Select “to the current class”. The Target Picker (with a handy preview) lets you decide where to insert the new method:

    5. The Up/Down arrows change the target location.  I press Enter to accept the position and generate the consolidated method. Here it is:

    6. Let’s rename it to “BuildUINameFrom”. CodeRush updates the calling methods automatically:

    7. Then I rename the parameters in the consolidated method:


    And I’m done.

    Elapsed time: About two minutes (which includes two full runs of all the test cases). Kids, let me tell you why it’s important to work in the future rather than the past: Because spending ten minutes making high-risk manual changes is senseless when you can do it safely in seconds with CodeRush.

    Here’s the video showing how fast it is:

    Note we start the video from an empty Visual Studio (no solution loaded). As we load the solution watch how quickly the Duplicate Code window fills up. You can also see the Test Runner collect unit tests and populate itself in seconds as well. Nothing is faster than CodeRush.

    CodeRush is still the only tool that can consolidate your duplicate code automatically across classes and projects. For more information on CodeRush, click here.

  • Duplicate Detection and Consolidation in CodeRush for Visual Studio

    CodeRush 11.2 introduces a new feature we’re very excited about. It’s called Duplicate Detection and Consolidation (DDC) and it’s revolutionary.


    Duplicate code, sometimes referred to as clones, is a cluster of code blocks that are functionally equivalent (or nearly equivalent) spanning across two or more locations within a solution. Duplicate code is expensive to maintain because:

    1. Multiplied bugs. A bug in one clone means there’s a bug in all the copies. This can lead to a continued, repeated release of previously-fixed bugs as each copy of the bug is individually discovered by a customer and then fixed by the team.
    2. Flexibility barriers. If the copied code needs to be more flexible, changes need to be made across all the copies or ideally, the copies need to be consolidated first. Unfortunately consolidation is a high-risk, error-prone, time-consuming activity.
    3. Increased ramp-up time. Copy the code and new developers trying to get up to speed will have twice as much code to read and understand. If discovered, duplicated code tends to be harder to understand than normal code because the reader must not only understand functionality, but also understand the reason behind the duplication.

    Reaching into the Future

    Because duplicate code is such an expensive problem, for years tools have been developed to detect duplicate code, each achieving various degrees of success. So you might wonder, after so many years of development, what makes CodeRush’s DDC so revolutionary?

    1. Speed. CodeRush has the fastest duplicate code detection available for .NET. It’s 17 times faster than the duplicate code detection currently available in the Visual Studio 11 preview.
    2. Integration. DD runs in a background thread while you work in Visual Studio. Duplicate code is highlighted on screen so you know exactly what you’re working with before you change the code.
    3. Functional Equivalence. The CodeRush duplication detection engine is built to understand functionally equivalent code. In 11.2, we take baby steps in this direction. However, by 12.1 we expect to really be blowing minds in this area, matching structurally distinct yet functionally equivalent blocks of code.
    4. Consolidation. CodeRush is the first and only tool on this planet to offer the ability to immediately consolidate duplication into a single block of code, directly from the IDE. Not only is CodeRush first, but Team CodeRush has delivered an impressive solution.

    The Complexity of Consolidation

    To give you an idea of just how impressive duplicate consolidation is, let’s take a look at what needs to happen to consolidate:

    1. You need to understand not only the similarities, but also the differences among the code blocks. Differences can be parameterized.
    2. If the duplicate blocks of code are functionally equivalent but structurally distinct, then a decision needs to be made - upon which of the duplicate blocks should we base the consolidation?
    3. You need to offer a variety of consolidation solutions so the developer can pick the one that fits best. For example, you could consolidate to a new method in a class, create a new ancestor class, or create a new helper class.
    4. You need to understand and respect project boundaries. In many cases duplication between projects survives beyond initial discovery because consolidating is time consuming and may require the creation of a new project.  If a new project is created, the appropriate references need to be added. Regardless of whether we’re creating a new project or moving code from one existing project to another, we need to verify that we can do this without creating any circular references.
    5. Types need to be correctly resolved. You might have two classes with the same name declared in different namespaces in your solution. The consolidated code must have the correct namespace imports to ensure that all the types are correctly resolved.

    As a result, the steps to consolidate by hand are many, complex, error-prone, and high-risk. Only the best developers are brave enough to venture forth in this domain, and if they do, they are best advised to bring a paired programmer along for the ride.

    Enter CodeRush 11.2

    This changes everything. From this day forward, the quality of code is going up. Let’s take a simple example. I have a class named Mortal, which looks like this:

    public class Mortal
      protected List<Mortal> friends = new List<Mortal>();
    public string Name { get; set; }

    And a descendant named Human, which has a FindHuman method:

    public class Human : Mortal
    public Mortal FindHuman(string name)
    Mortal mortal = null;
        foreach (Mortal friend in friends)
    if (String.Compare(friend.Name, name, false) == 0)
    Console.WriteLine("Found a Human: " + friend.Name);
            mortal = friend;
    return mortal;

    So far so good. But now, let’s do something incredibly dangerous. We’re going to make a copy of this Human class and perform a search and replace, “Human” for “Martian”…

    public class Martian : Mortal
      public Mortal FindMartian(string name)
        Mortal mortal = null;
        foreach (Mortal friend in friends)
          if (String.Compare(friend.Name, name, false) == 0)
            Console.WriteLine("Found a Martian: " + friend.Name);
            mortal = friend;
        return mortal;

    But let’s continue to change the code. Let’s introduce a few local variables, rename “mortal” to “myFavoriteMartian”, remove the unnecessary curly braces around the if-block, and change case-sensitivity of the String.Compare call so it ignores case (as one might expect with Martian names)…

    public class Martian : Mortal
      public Mortal FindMartian(string name)
        Mortal myFavoriteMartian = null;
        bool ignoreCase = true;
    string msg = "Found a Martian: ";
    foreach (Mortal friend in friends)
          if (String.Compare(friend.Name, name, ignoreCase) == 0)
            Console.WriteLine(msg + friend.Name);
            myFavoriteMartian = friend;
        return myFavoriteMartian;

    And now we have some code that is functionally equivalent, but structurally distinct. Can CodeRush find this? It can, providing we drop the Analysis Level down to 2, so the detection engine can see this smaller code block (the default level is set to 3, which is a slightly larger block):


    Here’s what the code looks like inside Visual Studio:


    On the left of the gutter in each view, you see a thin purple vertical bar. This means duplicate code exists elsewhere. Also, in the bottom right, the “!!” icon signals CodeRush has detected duplicates inside the solution. If you hover over the icon in the bottom right, a hint appears to explain the status.


    You can click the icon to see a summary of all duplicate clusters found inside the new Duplicate Code tool window. In this case, our simple example, only one cluster is found:


    On the left is a list of all clusters found, sorted by redundancy (the total amount of redundant code that could be removed if consolidated). Note that because we are sorting by redundancy, it’s possible for a very small block of code (duplicated many times) to appear above a very large duplicate block of code (that only appears twice).

    On the right is a preview of the duplicate code. You can double-click any duplicate code preview to be taken directly to that location. When you do this, CodeRush immediately presents the consolidation hint, which looks like this:


    Notice the mouse is positioned right over the “Next duplicate block” button, in case you want to navigate and compare the blocks. This might be useful when it’s time to consolidate. The block you consolidate from determines the structure of the consolidated block. So let’s consolidate from the FindMartian method. Click the “Next duplicate block” button, then move the mouse over the “to the base class” consolidation option. You’ll see a preview hint that looks like this:


    Notice the parameters to FindMartianExtracted – CodeRush takes the code that differs between the blocks and turns them into parameters. Press Enter to apply the consolidation. The target picker will appear letting you select the location of the consolidated method.


    The target picker shows the block of code that will be inserted. It’s based upon the structure of the method where we initiated the consolidation (FindMartian). Let’s press Escape to cancel and back out of this, and then see what happens when we initiate consolidation from the other duplicate…


    Now consolidate to the base class Mortal. We’ll see the target picker. Notice how the FindHumanExtracted consolidated code in the preview below differs from the FindMartianExtracted consolidated code in the preview shown two screen shots above.


     Just use the up/down arrow buttons to select a location and press Enter to accept it. Now we’re left with a small task of coming up with good names for the consolidated method and its parameters.


    And the calling code is simplified:


    And that’s it (for a simple consolidation example)!

    An Even Bigger Example

    But what happens when the project is much bigger? The good news is, that the detection scales well for large solutions, taking only seconds (at most a few minutes) to scan thousands of files for duplicates at the default settings (Analysis Level set to 3). Let’s take a look at DDC with the source to Umbraco.

    Here’s cluster #4 selected. The Lowest and Highest methods inside the ExsltMath class:


    Nearly identical blocks of code. However note the real difference is in the operator used to compare t against min (and max). On the left you have “t < min”, and on the right you have “t > max”. Can CodeRush consolidate this duplicate? It can. Here’s the preview hint:


    And after consolidation (and renaming the method, the “min” local, and the “func” parameter), I get this:


    And now the quality of the code is much higher than it was before.

    Remember, CodeRush has the fastest duplicate code detection available for .NET. It works in the background and shows when you’re working inside a method that is cloned. Consolidation is based on the structure of the method you start from. While CodeRush can consolidate many kinds of duplicate blocks, not all duplicate blocks can be consolidated automatically (trust me, this is an incredibly challenging problem to solve). But we’re working on making the consolidation engine even smarter and even more extensive as we approach the 12.1 release (and we expect to blow your mind again with that one).

    Do me a favor, kids: Tell every developer you know about CodeRush’s Duplicate Detection and Consolidation. DDC is truly revolutionary; help us spread the word.

  • Advanced CodeRush Plug-ins: Converting an Object Initializer into a Constructor

    Today Rory Becker and I presented an Advanced CodeRush Plug-ins session, showing how to create CodeProviders and RefactoringProviders. These providers show up on the CodeRush/Refactor menu, like this:


    The session included several moments where we tasted sweet success, and at least one tough coding segment where we were pushing through some challenging code.

    The new feature converts code like this:

      Box box = new Box() { Height = 33, Width = 44, Depth = 22 };

    into this:

      Box box = new Box(33, 44, 22);

    and creates a constructor if needed.

    At the end of the two-hour session, we were left with a refactoring that worked, but a CodeProvider that needed more effort. The CodeProvider was challenging because it needed to modify code in two places (it is adding a constructor and replacing the object initializer with a call to new constructor), potentially in two files.

    Here’s an overview of the points we learned in the session:

    1. The Expressions Lab can reveal many of the hidden details behind the source code you want to analyze or generate.

    2. The ObjectCreationExpression class represents a call to a constructor.

    3. ObjectCreationExpression elements have three interesting properties:

    • Arguments – the parameters to the constructor call, if any
    • ObjectType – a reference to the type being constructed
    • ObjectInitializer – an ObjectInitializerExpression (if the constructor call includes an initializer).
    4. ObjectInitializerExpression has one interesting property:
    • Initializers – a collection of MemberInitializerExpressions
    5. MemberInitializerExpression has two interesting properties:
    • Name – the property name being assigned.
    • Value – the value assigned to the property in the initializer expression.
    6. MemberInitializerExpression also has an interesting method, Resolve, which allows us to determine the type of the initializer argument.

    7. We can use the FileChange object to queue up changes to multiple files.

    At the end of the webinar, we encountered an issue where the CodeProvider wouldn’t generate any code. The problem was due to this line of code which set the source file Path property of a FileChange instance to the folder holding the text document (but not the actual file name):

      newConstructor.Path = CodeRush.Documents.ActiveTextDocument.Path;

    it should have been this:

      newConstructor.Path = CodeRush.Documents.ActiveTextDocument.FileNode.Name;

    Correcting the two places where we set FileChange’s Path property enabled the plug-in to generate code correctly. We’ll record a part 2 to this webinar where we’ll see this fix and wrap up all remaining issues:

    1. Fix the FileChange code generation.
    2. Add code that transfers parameters to the properties.
    3. Declare parameters in the developer’s preferred style.
    4. Test, and handle any new issues found.
  • New CodeRush Feature: Quick Pair (Parens, Brackets, Quotes, etc.) for Visual Studio

    Today was the first CodeRush Feature Wednesday webinar presented by Rory Becker and myself. And for our first feature we decided to implement something I wanted – a better way to enter paired delimiters in code. When entering paired delimiters, there seem to be a number of common scenarios:

    • Enter the pair and move on (for example, parens in a C# method call that takes no arguments)
    • Enter the pair and place the caret between the pair (but then you have the challenge of moving outside the pair)
    • Surround a selection with the pair

    To implement this feature, in the webinar we created a new Action called QuickPair which accepts leading and trailing delimiters, and an optional third parameter to determine whether the caret goes inside the delimiters or to the right outside the delimiters.

    You can download and install the feature here:

    This plug-in includes shortcut bindings based on the US keyboard. You may need to change these bindings to match your keyboard locale settings. For example, on a US keyboard, the parens are located above the 9 and 0 keys, respectively, like this:



    The curly braces are above the brackets:



    The angle brackets are above the comma and period keys:



    And the double-quote is above the apostrophe (and the key to the left is the semi-colon):



    With each of these key pairs, we’ve assigned two functionalities. The left key (e.g., Ctrl+[ ) places the caret between the two delimiters (adding a field, so you can just press Enter to get to the right of the delimiter pair), and the right key (e.g., Ctrl+] ) places the caret after the two delimiters (no fields needed). If there’s a selection, the left key will embed the selection within the delimiters (maintaining the original selection), and the right key will embed the selection within the delimiters, extending the selection to include the delimiters. Examples of all the bindings created in the webinar appear below.

    Given these key positions, the table below shows available functionality (the “|” character indicates the caret position and the blue background indicates the selection, after code is inserted):

    On a US Keyboard, press this: to get this:
    (no selection)
    or to modify a selection:
    Ctrl+(   (|)   (My Selection)
    Ctrl+)   ()|   (My Selection)
    Ctrl+[   [|]   [My Selection]
    Ctrl+]   []|   [My Selection]
    Ctrl+Shift+{   {|}   {My Selection}
    Ctrl+Shift+}   {}|   {My Selection}
    Ctrl+Shift+<   <|>   <My Selection>
    Ctrl+Shift+>   <>|   <My Selection>
    Ctrl+;   "|"   "My Selection"
    Ctrl+"   ""|   “My Selection”
    Ctrl+=   (|) =>   (My Selection) =>

    You may notice a lack of symmetry with the Ctrl+= binding (there is no corresponding binding to place the caret to the right of the lambda operator). I omitted this binding due to a lack of a suitable neighboring key to the equals sign. If you want to correct this asymmetry and add your own binding, feel free to. After installing this plug-in, you may view or change the shortcuts bindings in the IDE\Shortcuts options page. The QuickPair bindings are in the Code\QuickPair folder:


    Have a request for a new feature? Email and let us know what you’d like to see us build for you on CodeRush Feature Wednesdays.

  • Get Your CodeRush Training Here

    Here’s a summary of CodeRush training videos created so far, to help you find relevant training quickly:


    1.       Introduction to Features

    a.       Getting Started/Configuration

    2.       Navigation

    3.       Working with Selections and the Clipboard

    4.       Consume-first Declaration

    5.       Declaring and Refactoring:

    a.       Properties

    b.      Events

    6.       Refactoring in-depth:

    a.       Introduction

    b.      Changing Signatures

    c.       Conditionals

    d.      Declaration and Initialization

    e.      Dead Code

    f.        Expressions

    g.       Formatting and Structure

    h.      Lambda Expressions and Anonymous Methods

    i.         Loops & Blocks

    j.        Moving and Extracting Methods

    k.       Properties and Fields

    l.         Strings

    7.       Language/Framework follow-up:

    a.       ASP.NET

    b.      C++

    c.       MVC

    d.      Working with Color

    e.      WPF and Silverlight

    f.        XAF

    8.       Advanced Topics

    a.       CodeRush Template Deep Dive

    b.      TextCommands

    9.   Creating Plug-ins

    a.       Introduction – Actions and Tool Windows

    b.      Text Commands, StringProviders and ContextProviders

    c.       TextDocument and TextView


    Nearly every Tuesday at 12:00 noon Pacific time Rory Becker and I host a CodeRush training webinar, where we dive into a particular topic and answer questions from viewers. You can see a list of upcoming CodeRush webinars here.

  • Visual Studio Features Built Instantly for CodeRush Developers

    This week Rory and I continue our path-rip through the space time continuum by responding to customer requests yet again with mind-numbing development speed.

    Earlier today this question appeared on twitter:


    Joe needs to convert a method call with positional arguments (the old way of passing arguments), into a named argument call. For example, he wants to change something like this:

    RegisterDev("Mark", "Miller", 0);

     to this, in C#:

    RegisterDev(firstName: "Mark", lastName: "Miller", id: 0);

    Definitely a useful refactoring. Here’s how we built it:

    1. Create a new plug-in.
    2. Drop a RefactoringProvider on the design surface
    3. Fill out properties for the refactoring (Name, Description, AutoUndo)
    4. Handle three events (CheckAvailability, Apply, & PreparePreview)

    Within an hour the feature was implemented and published (working in C# and VB), ready for consumption by CodeRush devs, prompting this response from Joe:


    But this isn’t unique. Over the last two weeks we’ve released a number of new features, all built and delivered on the same day they were requested (most in under an hour from the original request)…




    Need a feature? Just let us know. CodeRush can do anything, and if the feature isn’t there, we can likely add it easily. Tell us on Twitter what you want CodeRush to do (include the word “CodeRush” in your tweet), and lets see if we can keep up the pace. Smile

  • Importing Namespace References for Extension Methods in CodeRush for Visual Studio

    From feature request to binary delivery in less than four hours. Here’s the timeline:

    At 10:06 this morning, Apeoholic tweets the following question:

    Is there a way to get #CodeRush to suggest namespace usages for extension methods?

    Which led to the following discussion with one of our CodeRush devs on IM:

    [10:08] Mark: Hey Alex, I have this question in a tweet -- "Is there a way to get #CodeRush to suggest namespace usages for extension methods?"
    [10:09] Alex: Hi Mark, I'm not sure what he means…
    [10:10] Mark: I think he's talking about adding namespace imports when an extension method is at the caret.
    [10:10] Mark: I'm wondering if VS fails to do this.
    [10:10] Alex: I suppose VS does it, doesn’t it?
    [10:10] Mark: Check it for me.
    [10:12] Alex: OK, VS fails to do this.
    [10:13] Alex: And we don't have such feature
    [10:13] Mark: Can we write this as a plug-in?
    [10:13] Alex: Of course, but this will take time.
    [10:14] Mark: What's the challenging part of this?
    [10:14] Alex: Find and resolve all the extension methods
    [10:15] Mark: Create a spike -- work on this for an hour and see what you get.
    [10:15] Mark: Then send me that source and I can finish it up
    [10:15] Alex: ok
    [10:15] Mark: Then I'll have Rory put it on the community site.
    [10:15] Alex: k

    Which led to the development of the feature, testing, a few changes, and then this IM with Rory Becker:

    [13:06] Mark: I had Alex create a plug-in spike for a feature request to add missing namespace references for extension methods (something VS does not do)
    [13:06] Rory: cool
    [13:06] Mark: I'm going to send this to you. Can you get this on the community plug-in site today?
    [13:06] Rory: yeah sure, no problem

    At 14:05, we published the feature on the community site.

    Here’s the feature in action:


    Here’s the link to the feature on the CodeRush community plug-ins site:

    We are likely to roll this functionality into a future version of CodeRush. If you have a CodeRush question or feature request, we want to hear from you. Post a comment below or include “#CodeRush” in your tweets and we’ll respond in a timely manner.

1 2 3 4 5
7 8 9 10

Chat is one of the many ways you can contact members of the DevExpress Team.
We are available Monday-Friday between 7:30am and 4:30pm Pacific Time.

If you need additional product information, write to us at or call us at +1 (818) 844-3383


DevExpress engineers feature-complete Presentation Controls, IDE Productivity Tools, Business Application Frameworks, and Reporting Systems for Visual Studio, Delphi, HTML5 or iOS & Android development. Whether using WPF, ASP.NET, WinForms, HTML5 or Windows 10, DevExpress tools help you build and deliver your best in the shortest time possible.

Copyright © 1998-2018 Developer Express Inc.
All trademarks or registered trademarks are property of their respective owners