Archive for the ‘How-To's’ Category

ReSharper 5.0 Preview: Call Tracking

Wednesday, March 17th, 2010

There’s a cool new feature in ReSharper 5.0 called Call Tracking (or, alternatively, Call Hierarchy). Basically, it’s a convenient way to perform an all-out Find Usages or Go To Declaration. You can access it by choosing ReSharper | Inspect | Outgoing Calls or ReSharper | Inspect | Incoming Calls.

There’s also Inspect This, a new shortcut to Call Tracking, Value Tracking, and Type Hierarchy features: Ctrl+Shift+Alt+A.

At first we thought of comparing our Call Tracking to Call Hierarchy in Visual Studio 2010. However, it turned out that the VS 2010 version is just not up to par: it doesn’t support events, interfaces, closures and a few other things. It offers no help at all with the use cases we present here. So we’re only going to talk about Call Tracking in ReSharper 5.0.

Events

Let’s search for an outgoing call from Foo (ReSharper | Inspect | Outgoing Calls):


   using System;
   public class C2
   {
     public event EventHandler E = (sender, args) => Subscription_In_Initializer();

     static void Subscription_In_Initializer()
     {
     }

     void Foo()
     {
       E(this, EventArgs.Empty);
     }
   }

   class C3
   {
     void Bar()
     {
       new C2().E += Subscription_In_Method;
     }

     void Subscription_In_Method(object sender, EventArgs e)
     {
     }
   }

Outgoing Call From Foo

Pretty self-explanatory. ReSharper easily finds all subscriptions to E and displays them as possible calls. Nothing too special, but handy for sure.

Generics

Consider this code sample:


   public abstract class Base<T>
   {
     public void Do(T value)
     {
       DoImplementation(value);
     }

     protected abstract void DoImplementation(T value);
   }

   public class Concrete1 : Base<int>
   {
     protected override void DoImplementation(int value)
     {
     }
   }

   public class Concrete2 : Base<string>
   {
     protected override void DoImplementation(string value)
     {
     }
   }

Now let’s look at outgoing calls from Base.Foo:

Outgoing Calls From Do

Speaks for itself.

Now, let’s add a Main class and try searching for outgoing calls from Foo:


   class Main
   {
     void Foo()
     {
       Concrete2 c = null; // null so that we don't clutter the call tree
       c.Do("string");
     }
   }

Outgoing Calls From Foo

Concrete1.DoImplementation doesn’t show up anymore! That’s because ReSharper looked at the type parameters and realized that Base.Do will be called with T->string (see the second line of results: Base<string>.Dostring means we’re calling a method that substitutes a specific type). Accordingly, ReSharper filtered out Concrete1 because it uses inheritance with the substitution T->int.

Now let’s look at a slightly more complex, yet very vital example using the Visitor pattern. Let’s search for incoming calls from ConcreteVisitor1.VisitNode1 (ReSharper | Inspect | Incoming Calls). Note how we’re going the other way here, in the direction opposite of method calls:


   public interface IVisitor<T>
   {
     void VisitNode1(T data);
   }

   class Node1
   {
     public void Accept<T>(IVisitor<T> v, T data)
     {
       v.VisitNode1(data);
     }
   }

   public class ConcreteVisitor1 : IVisitor<int>
   {
     public void VisitNode1(int data)
     {
     }
   }

   public class ConcreteVisitor2 : IVisitor<string>
   {
     public void VisitNode1(string data)
     {
     }
   }

   public class C1
   {
     void Foo()
     {
       var v = new ConcreteVisitor1();
       new Node1().Accept(v, 1);
     }

     void Foo2()
     {
       var v = new ConcreteVisitor2();
       new Node1().Accept(v, "string");
     }
   }

The result:

Incoming Calls to VisitNode

While traversing the generic Visitor, ReSharper did not lose any details about the substituted type parameters and successfully filtered out the irrelevant call from Foo2. When you have a highly-branched hierarchy and a large number of generic types, this kind of logic helps to really narrow down your search.

Constructors

Let’s also look at an artificial example using constructors and field initializers. Let’s search for outgoing calls from the Derived class constructor:


   class Base
   {
     public Base()
     {
       Base_Bar();
     }

     void Base_Bar()
     {
     }
   }

   class Derived : Base
   {
     int _i = Foo();

     public Derived()
     {
       Bar();
     }

     void Bar()
     {
     }

     static int Foo()
     {
       return 0;
     }
   }

Outgoing Calls From Derived

Again, nothing out of the ordinary. ReSharper simply displays calls in their the natural order, mindfully listing the implicit call of the base constructor. For a less-experienced developer, this saves a lot of time spent understanding code, and is a nice crutch to lean on for an expert.

Value Tracking

And here’s the final tidbit. If you open the ReSharper | Inspect menu, you’ll see two very interesting items: Value Origin and Value Destination. These functions implement value tracking: they let you track where a particular variable value or parameter value came from, or where it is headed. Naturally, it works with collections and delegates (it determines that an item was taken from a collection and then searches for usages of that particular collection) and is indispensable for identifying the causes of NullReferenceExceptions.

Illustrating this will take a whole batch of screenshots and examples, so please stay tuned for our next post.

Author: Alexander Zverev, senior ReSharper developer. Translated from original article (in Russian)

ReSharper 5.0 Preview: Solution-Wide Warnings and Suggestions

Wednesday, January 27th, 2010

Over the years, ReSharper has gradually advanced from plainly highlighting errors and problems in individual code files to somehow summing up errors and problems in a larger scope, up to the entire solution.

Back in 2007, ReSharper 3.1 was the first product version to introduce Solution-Wide Error Analysis to gather data on all errors in the solution using a single tool window. ReSharper 4.5 split many code inspections to execute in private and public scope, with the latter only available when you turned on Solution-Wide Error Analysis.

Taking another huge step towards instantly seeing every problem anywhere in your solution, ReSharper 5 introduces a new code analysis feature called Solution-Wide Warnings and Suggestions. As you’ve probably guessed, it lists all warnings and suggestions that ReSharper displays in the scope of your whole solution or in a narrower scope, depending on how you call it. In other words, any code smells or other problems that you may have in your solution can now be summarized in a single tool window, making tool-based code review much easier.

When you switch on Solution-Wide Errors Analysis, Solution-Wide Warnings and Suggestions starts showing errors as well, plus warnings and suggestions that work in non-private scope.

That doesn’t mean Errors in Solution tool window becomes obsolete with R# 5: when your goal is as simple as to make your code compile, Errors in Solution quickly indicates that something in the solution went awfully wrong and you should fix things up before you can compile.

However, as soon as you’re ambitious enough to make your code green - that is, eliminate compiler warnings, implement best practices, or upgrade your code to leverage the latest language opportunities - Solution-Wide Warnings and Suggestions is exactly what you need to get the job done quickly.

The feature includes two items:

  • Inspect Code - a new command that is available by right-clicking any node in Solution Explorer, from a single file to the whole solution:
  • Inspection Results - a tool window that actually shows problems found in a certain scope, broken up into several categories:

The Inspection Results tool window is pretty much similar to other ReSharper tool windows like Type Hierarchy or Find Results: it provides common navigation, grouping and export options. It also has a code preview pane where you can instantly see the context of a problem without opening the corresponding file in the text editor:

The tool window is not updated automatically, so as soon as you’ve made substantial changes, make sure to click the Refresh button to see up-to-date inspection results:

In many scenarios, chances are you don’t want to review all code problems you may have in a scope - you’d rather focus on a particular subset. Inspection Results lets you do this by clicking the glaring Filter button:

This displays the Filter Issues dialog box where you can select or unselect individual inspections or even entire inspection groups. For example, here’s how you can discover code that can be transformed to leverage C# 3.0 and C# 4.0 language features:

When you double-click an item in Inspection Results, the corresponding file opens in the text editor in the right position for you to actually take measures: apply a quick-fix, refactor or clean up code, or whatever:

However, instead of double-clicking through all inspections, in many cases you can apply fixes right from Inspection Results: say, you’re inspecting a single file that has three inspection items:

Of the three inspection items, two can be safely fixed using Code Cleanup, which can both delete a redundant “using” directive and make an explicitly typed variable implicitly typed. Then, you press Ctrl+Alt+F right on one of these two inspection items, and the Code Cleanup dialog box displays:

You launch Code Cleanup with Full Cleanup profile, and ReSharper applies fixes for both inspections straight away! Upon refreshing Inspection Results, you only have one inspection left:

In addition to cleaning up code, you can also apply refactorings and navigation actions right from Inspection Results. I hope to cover scenarios involving this approach in subsequent posts about ReSharper 5.

To try out Solution-Wide Warnings and Inspections in its latest incarnation, make sure to download a fresh ReSharper 5 nightly build!

ReSharper 5.0 Preview: Loops 2 LINQ

Friday, December 11th, 2009

On the eve of ReSharper 5.0 going beta, we thought it’s just about time to start elaborating on new R# features. We’re hoping for a series of posts on improved code analysis, navigation to and within external sources, structural search & replace, ASP.NET support, and other stunning capabilities that ReSharper 5.0 provides. Today, we’ll talk about R# going crazy over LINQ.

Among many new code inspections introduced in ReSharper 5.0, two are specifically aimed at converting for and foreach loops into LINQ statements and/or combinations of extension methods and lambda expressions. Here they are:

  • Loop can be converted into LINQ-expression
  • Part of loop’s body can be converted into LINQ-expression

If you are wondering why you would ever transform traditional cozy loops to LINQ, Jimmy Bogard, Matthew Podwysocki, and Justin Etheredge have done a great job of explaining why.

Back to ReSharper work, let’s see how it converts loops to LINQ method or query syntax for you in common scenarios.

First, there’s the aggregation scenario where we loop through a collection in order to get the number of this collection’s items for which a certain condition holds true:

ReSharper highlights the foreach keyword with a green curly underline. You press Alt+Enter for available actions, and ReSharper suggests that you convert the loop to a LINQ expression:

You apply the conversion, and here we go: no more temporary counter variable. Instead, we’ve got Count extension method with a lambda-styled condition:

Next, we’re taking on the transformation scenario where we’re looping though a collection to populate another collection:

Again, ReSharper is smart enough to see that the code fragment can be converted to LINQ method syntax:

On the output side, we’ve got one line of code instead of three, thanks to the ToDictionary extension method:

For the next scenario, let’s take a collection and filter it out, so to speak, like this:

ReSharper encounters three foreach loops and readily suggests that we convert each of them. Because conversion only occurs within a selected loop and its nested loops, let’s press Alt+Enter at the top-level loop:

What we’ve got here is a pretty return statement that leverages LINQ query syntax:

All three examples above show how ReSharper converts entire loops to LINQ. In many cases, specifically with write usages inside loops, that can’t be done. For such occasions, ReSharper provides its second LINQ-related inspection: Part of loop’s body can be converted into LINQ-expression. Unlike the previous action, it’s displayed as a hint and highlighted with a straight green underline.

Let’s take another foreach loop with a complex condition and a write usage inside:

Pressing Alt+Enter at the foreach keyword highlighted as a hint lets you convert a part of the loop to LINQ syntax:

ReSharper integrates the condition with iteration variable definition, resulting in a LINQ query that makes the previously bloated write usage clear:

If, for any reason, you want to keep your loops for future generations and you don’t need LINQ-related code inspections, or, say, you want them to display as warnings or even errors, you can always configure them by choosing ReSharper | Options | Code Inspection | Severity.

The two loop 2 LINQ inspections and many more exciting features are available right now: we keep publishing fresh ReSharper 5 nightly builds that you can download and evaluate.

ReSharper in Detail: Navigate from Here

Tuesday, November 11th, 2008

A subset of ReSharper’s navigation features is designed to help you promptly navigate from one symbol to another. These features are:
 

  • Go to Declaration
  • Go to Type Declaration
  • Go to Base
  • Go to Inheritor
  • Go to Usage

 
Two common ways to call them are to choose corresponding menu items or hit keyboard shortcuts, but there’s a third, by far the most convenient way, which is to invoke the Navigate from Here drop-down list upon the current symbol in the text editor (or upon a selected entry in File Structure or another ReSharper tool window) by pressing Ctrl+Shift+G:
 

 
Not only does this drop-down list provide a handy multiple-choice navigation technique, but it also extends a developer’s toolset with a bunch of “secret” navigation features that are not available from the ReSharper menu.

Control Flow Target

(Works in text editor only)
Function: navigates to next control flow recipient.
Available for: foreach, yield, jump statements (break, continue, goto, return), throw statement.
For example, in the following code fragment, selecting Control Flow Target upon the continue statement brings the caret to the next iteration of the enclosing iteration statement, i.e. –i:
 

Function Exit(s)

(Works in text editor only)
Function: navigates to member exit point or highlights alternative exit points.
Available for: getters and setters in properties, constructor names, return statement (alternative exit points are highlighted, if any), throw statement.
For example, invoking Go to Function Exit(s) upon the name of the following constructor highlights throw statements in if clauses, as well as the closing constructor body delimiter:
 

Implementing Members

Function: highlights interface members implemented in the current class.
Available for: base interface entries in implementing class declaration:
 

Overriding Members

Function: highlights abstract class members overridden in the current class.
Available for: base class entries in inheriting class declaration.
Works similar to Implementing Members

Conflicting Declaration(s)

Function: navigates to a member with identical signature in the current scope.
Available for: any of conflicting member declarations:
 

Member Overloads

Function: navigates to an overloading member or (if there are two or more of them) highlights such members in the text editor.
Available: anywhere within overloadable members:
 

To-do Explorer

Function: navigates from a to-do item in the text editor to its corresponding entry in the To-Do Explorer.
Available for: to-do items:
 

Test Explorer

Function: navigates from a unit test or test class in the text editor to its corresponding node in the Unit Test Explorer.
Available anywhere within test classes, unit tests:
 

 
As a finishing note, remember that whenever you execute a “Navigate from Here” action that highlights a set of symbols that are not entirely visible on the current screen, you can navigate to the highlights using ReSharper Marker Bar (take a note of blue markers in the example for Member Overloads). When you’ve finished examining the highlights, press Esc to remove them.
 

Generating object initializers with ReSharper

Friday, April 11th, 2008

ReSharper provides both a quick-fix and a context action to transform assignment statements into C# object initializers, and both are called “Use object initializer”.
 
So what’s the difference between them?
 
Suppose that you create an object with three assignment statements:
 

 
Putting the caret over the “new” keyword lets you apply a quick-fix that will put all assigned fields into an object initializer:
 

 
Putting the caret over the object variable or a field name in any of the tree assignment statements lets you apply a context action that will put only this assignment in the object initializer:
 

 
That is, using the context action, you can selectively put field assignments into the object initializer, leaving some of them to be declared explicitly.

Technorati tags: , , , ,

Create an overloaded delegate quickly

Sunday, March 23rd, 2008

Sometimes it is necessary to create method overloads that just pass default values to other overloads. ReSharper allows you to do this quickly and easily.

Take this simple method for example:

screenshot_01.jpg

We need to take the CreateUser method and add a new parameter to it. However, we also need to keep the old CreateUser method signature around for other code that still uses that version of the method signature. Using ReSharper’s Change Signiture (Control-F6) feature will allow us to create an overloaded method to solve our problem.

screenshot_02.jpg

When the Change Signature dialog opens for this method, we will go ahead and add our new email parameter to this method.

screenshot_03.jpg

In the above screenshot, notice the option “Delegate via overloading method” circled in red. Clicking this box is what will take the signature changes and turn them into a new overloaded method.

When the changes are ready, clicking Next in the Change Signature dialog will now produce the following code.

screenshot_04.jpg

Notice that in the SaveNewUser method, the original method signature remains intact, but it is now delegated through an overloaded method. The CreateUser method now has two overloaded variations, the delegating method and the main method, where we can now add code to handle the new email parameter.

Jeff Pennal
JetBrains .NET Evangelist

Custom Templates

Saturday, March 15th, 2008

ReSharper templates enable you to quickly generate predefined code constructs. Many templates are provided ready to use; you can create new templates, edit existing ones and easily manage them.

Creating and using your own templates is a quick and easy way to help eliminate repetitive code or to automate common tasks. To demonstrate this functionality, I am going to show how to use custom templates to add log entries using the Apache log4net library.
(more…)

ReSharper in Detail: Quick-Fixes vs Context Actions

Tuesday, March 4th, 2008

Of all ReSharper’s features, two are most noticeable: context actions and quick fixes. Along with marker bar, these are exactly what a user sees every time he works with a real-world solution.
 
It’s pretty obvious what these features do - both offer drop-down lists filled with various available actions for modifying your code. However, specific differences between context actions and quick-fixes are not readily evident. Bearing that in mind, we will compare the two features below.
 
Availability of quick-fixes and context actions for a code position is designated by two differently colored bulb icons to the left of current line:

  • red for quick-fixes, and
  • yellow for context actions.

Whenever both quick-fixes and context actions are available at a specific caret position, a red bulb is displayed.
 
When any of two bulbs is displayed, pressing Alt+Enter launches a drop-down list with all available quick-fixes and/or context actions. If only quick-fixes are available, the list looks like this:


 
If only context actions are provided:


 
If both quick-fixes and context actions are available:


 
Quick-fixes are specifically designed to fix any code with highlighed errors, warnings, suggestions, or unused elements. In other words, wherever you see a code item marked with a red, green or blue curly underline, or a symbol highlighted in grey, you can bet there’s a quick-fix provided. Applying a quick-fix at a specific line can cause code modification in any other corner of your solution. For example, the “Create Method” quick-fix applied upon a call to a nonexistent method causes ReSharper to create the corresponding method after the current method ends or in another class:
 
Before applying:

 
After applying:

 
Another example would be triggering a quick-fix over a method call to modify the type of an argument in the corresponding method declaration, which can possibly reside in another file:
 
Before applying:
(Method call)

(Method declaration)

 
After applying:
(Method call)

(Method declaration)

 
On the contrary, context actions serve to provide ways to change your code instantly. They’re not associated with any discovered errors but displayed merely because they might be useful to you. After all, if you’re looking to surround a string with a string.Format() call or merge two nested if statements, it’s much easier to do with context actions than by hand.
 
Since quick-fixes are tied to the results of code analysis, they’re only applied to C# code. As for context actions, three separate sets of them are available for C#, VB.NET and XML.
 
For both C# and VB.NET, you can explicitly choose which context actions to enable. That can be done using language-specific Context Actions tabs in ReSharper Options. No comprehensive list of quick-fixes is available to a user and you can’t disable quick-fixes associated with compilation errors one by one - however, you can abandon code analysis altogether (to do that, clear Enable code analysis in ReSharper | Options | Code Inspection | Settings). You can also fine-tune the list of displayed warnings and suggestions that have quick-fixes associated with them (ReSharper | Options | Code Inspection | Inspection Severity).
 
For examples of using context actions and quick-fixes in practice, see the following links:

Technorati tags: , , , , , , , ,

ReSharper in Detail: Reformatting Code

Sunday, February 10th, 2008

ReSharper can reformat an arbitrarily selected block of C# or VB.NET code, all code in the current file, all files in a directory, the current project, or even the current solution, according to options configurable in:
 

  • ReSharper | Options | Languages | C# | Formatting Style for C# code, or
  • ReSharper | Options | Languages | Visual Basic .NET | Formatting Style for VB.NET code.

 
Once the formatting settings are configured, you can share them with your fellow team members to ensure uniform code appearance.
 
Whenever you have a file opened in the editor, select a fragment that you want to reformat, or, alternatively, don’t select anything, in which case reformatting will apply to the entire file. Then launch Reformat Code in one of three ways:
 

  • Choose ReSharper | Code | Reformat Code on the main menu.
  • Press Ctrl + Alt + F (no default shortcut in VS scheme).
  • Choose Reformat Code in the context menu.

 

 
The Reformat Code dialog box (shown above) contains several formatting options:
 

  • Optimize ‘using’ directives removes redundant namespace import directives from the source code. Note that this option is disabled when you have a selection – even if it includes the imports section of your file.
  • Shorten references replaces fully qualified names with short names where possible by importing namespaces.
  • Remove redundant ‘this.’ qualifier deletes unnecessary this keywords (note that it doesn’t do the same for VB.NET keyword Me).
  • Reorder type members (for C# code only) reorders type members according to patterns specified in ReSharper Options | Languages | C# | Type Members Layout.

 
After you have reformatted your code, ReSharper saves the state of check-boxes for future use. Subsequently, you can even launch Reformat Code silently, without opening the dialog box, by pressing Ctrl + Shift + Alt + F (or Ctrl+E, F in the Visual Studio keyboard layout).
 
An additional advantage is that you can execute reformatting via Solution Explorer. For example, you can reformat a specific C# code file, or all such files in a project or entire solution. Just right-click the required node and choose Reformat Code….
 
Additional links:
 
Kyle Baley explains how to remove regions with the Reformat Code feature (C# only)
An example of how you can customize a type member layout pattern
Tips for using Reformat Code with aspx pages
Joe White’s detailed review of ReSharper’s reformatting tools

Technorati tags: , , , , ,

ReSharper in Detail: CamelHumps

Friday, February 1st, 2008

CamelHumps is a feature that identifies parts of compound names composed according to CamelCase, where each part starts with a capital letter (“hump”).
 
By default, it works in four navigation commands, namely Go To Type, Go To File, Go To File Member, and Go To Symbol, like this:

 
However, you should take an additional step to activate CamelHumps for the Extend/Shrink Selection (Ctrl + (Shift) + W, or Ctrl + Alt + Right/Left in the Visual Studio keyboard layout) and Next/Previous Word (Ctrl + Left/Right) navigation actions. To do that, choose ReSharper | Options | Environment | Editor and select Use CamelHumps.
 
From now on, CamelHumps is switched on, and jumping to next/previous word works in a slightly different manner. Specifically, when you press Ctrl + Left/Right, the caret moves to the next/previous uppercase character in the current word, and only after that, it moves on to the next/previous word.
 
Extend/Shrink Selection commands are also affected by CamelHumps. Suppose that the caret is in the middle of a compound word with several parts that begin with uppercase letters:

If CamelHumps is switched on, pressing Ctrl + W for the first time selects the current part of the word:

It’s only after pressing this keystroke for the second time that you can select the whole word:

All subsequent keystokes are processed as usual.
 
In addition, ReSharper provides four actions for using CamelHumps locally when the global option (Use CamelHumps) is switched off:
 

  • ReSharper_HumpNext - move caret to next hump/word
  • ReSharper_HumpPrev - move caret to previous hump/word
  • ReSharper_HumpNextExtend - expand selection to next hump
  • ReSharper_HumpPrevExtend - expand selection to previous hump

 
Of course, you can assign individual shortcuts to these actions in the Visual Studio Options dialog box (Tools | Options | Environment | Keyboard).
 
Note that both HumpNextExtend and HumpPrevExtend only work in a linear fashion, without additional functionality of Extend/Shrink Selection.

Technorati tags: , , , , , ,