Archive for the ‘How-To's’ Category

ReSharper 6.1 Settings: DropBox and Company-wide

Tuesday, December 6th, 2011

This post is about ReSharper 6.1. For other features in ReSharper 6 (both 6.0 and 6.1), please see previous posts introducing ReSharper 6:

EAP Warning: This post is based on ReSharper 6.1 Early Access Program and some things such as screenshots and minor details might vary from the time this has been written to the time of release.

In a previous post on ReSharper 6.1 Settings, we introduced the concept of layers and covered a few scenarios when it comes to sharing of settings across solutions. In this post we’re going to cover a few more, namely: syncing settings over DropBox and providing a global setting for all projects across a company.

Syncing with DropBox

As developers we often end up working on multiple machines, whether it is that we own a desktop and laptop, or two desktops, one at work and one at home, or any other combination of scenarios, we have the need to alternate between machines. With the new layers settings in ReSharper 6.1, sharing the same settings in these cases has now become quite easy.

The idea is simple: add a new Global Layer and host the file in a DropBox folder (I’m using DropBox, but obviously you can use any other mechanism that syncs files remotely). In order to do this, we first need to export the current settings to that new file and then mount it.

1. Click ReSharper | Manage Options…

image

2. Select the Global Settings and click on Export to File. It will prompt for a filename. The idea is to place this file in a Dropbox folder. Select everything from the following screen except Housekeeping

image

It is important to note that only items that currently have non-default values will be displayed in this window. For instance, under PattersnAndTemplates, we’d see an entry of StructuredSearch if we were to have some custom patterns in the current context, as shown below

image

3. Select Add Layer | Existing File and select the file created in the previous step.

image

[Note: This screen will most likely be updated in a future release to combine the “ReSharper Global Settings” under the group header as this is a default layer that cannot be removed and therefore cannot intervene in normal operation such as priority]

We now have to repeat step 3 for each of our machines. Once we do that, the settings will automatically be loaded every time DropBox syncs.

Providing Company-Wide Settings

It should be pretty apparent that providing company-wide settings across all projects is pretty much the same as sharing via DropBox. We just need to provide a file. If we want to provide solution company-wide settings, we’d add the layer to the solution group. This would allow an alternative way of sharing settings which wouldn’t require the file to be checked in to source control.

Other operations to perform with Settings

Settings can be imported, exported, activated and deactivated (marking the checkbox or unchecking) at any point. We can also Copy To button to copy settings from one layer to another layer, making it also easy for sharing. In essence you can do pretty much anything you like now.

Why so many layers?

You might be thinking, if I could setup my settings to read from a specific file, why would I want more layers or the ability to order them in priority?. The idea with layers is that each one can add one or more configuration settings. This means that for instance a company could have a layer where only code formatting settings are defined, another layer where templates are defined and so on and so forth. When we export settings to a file as shown in two, we define which settings we want exported. We do not have to select them all like we did previously. We could for instance only choose to export Templates, and mount a layer where only these are defined. ReSharper can understand that there are different options in different layers and provides us access to them all. We don’t have to worry about this. The only thing we might need to take into account is if one layer overrides another one’s settings. That’s where the Move Up / Move Down comes in, allowing us to specify the priority.

Summary

The layers provide a lot of flexibility when it comes to sharing settings, either between two machines, a team or company-wide. Use them, abuse them. Give us your feedback.

ReSharper Tips and Tricks Video from NDC

Wednesday, June 22nd, 2011

We at JetBrains have recently visited the awesome NDC conference. In addition to booth activities and regular sessions (which you can download from the official NDC web site), Hadi Hariri has presented a semi-impromptu session called ReSharper Tips and Tricks that we know that some of you wanted to attend (and hopefully attended.) The session was recorded and kindly provided to us by the organizers, and is now available on JetBrains TV.

Since the complete session is worth an hour of video, and we only expect selected geeks to handle it in its entirety, we decided to also make several parts of it available as standalone videos, and we have five of them, namely:

Please watch and learn things about ReSharper that you probably haven’t known before!

Simulating Performance Improvements with dotTrace

Thursday, March 10th, 2011

Let’s say you’re trying to improve performance of some application that is doing poorly. You manage to find what could potentially be a bottleneck and decide that it needs fixing. Of course, Murphy’s Law dictates that the potential issue you’ve found is probably one of the harder problems to solve as it might involve improving a calculation algorithm or changing some third party framework.

This could turn into quite an expensive operation. It would be a shame to spend time and resources on it to not have a the desired impact on the overall system. In other words, it’s best to know you’re barking up the right tree.

What if…

That’s where dotTrace Adjust Time feature comes in very handy. By allowing us to adjust the amount of time spent in a particular spot of an application, we can simulate the overall impact it would if we were to perform optimizations in that area, without having to actually do them first.

Let’s take a look at the following call tree of a performance trace for a sample application

Looking at the call trace, we can see that the majority of the time spent is dedicated to IntersectRay. This method in turn calls Sphere.Intersect and Plane.Intersect. Out of the two, the first is the more time-consuming

What would happen if we were to now try and optimize the performance of Sphere.Intersect? What overall impact would it have if the time it takes to complete the call were reduced by 30%.

Now, instead of spending time on re-designing the method, we will use the simulation functionality in dotTrace to verify whether it’s worth a potential effort.

To simulate the improvement, we right-click on the Intersect line and select Adjust Time

We are then prompted by a dialog box that allows us to adjust the time by a factor of 0 to 100.

Apart from adjusting the time, we can indicate whether we want the adjustment to be only on the specified call stack that we are currently on (Selected Call Stack), applied it to all call stacks (All call stacks) of this method or call stacks with the calling method as the parent function (this last option is available in dotTrace 4.5 EAP only).

We can also specify whether we want the adjustment to effect the overall time of the function (the function itself and all functions it calls), only the function’s own time or all functions of the the specified class.

It is important when applying adjustments to take these options into account because selecting different values can have an impact not only on the current call stack we are trying to optimize but also on the entire application.

In our case, we are going to apply adjustments to all call stacks and to the function’s total time. We will apply a 30% reduction, which means we will enter 70 as the Factor value. This now produces the following result

First thing to notice is that the line where we’ve adjusted the time is crossed out. Next to each time, we now see a new amount in the color green and the original time in blue in brackets. Focusing on the IntersectRay method, a 30% improvement of Sphere.Intersect would lead to approximately 19% improvement on the call and an overall increase of 15% in terms of performance. Is that worth it?

Let’s dig deeper. Opening up Sphere.Intersect we see that 24% of the time is dedicated to the Vector.op_Multiply. What would happen if we were to focus our improvement exclusively on this method call? Applying the same 30% increase in performance, we’d end up with an overall increase of 14%

Despite representing only 1/3 of the total time of Sphere.Intersect, an improvement on that call alone will provide us with the same overall performance increase as concentrating on the complete method. In fact, it makes more sense to optimize the op_Multiply method since it’s used extensively throughout the application. That’s where we should focus our efforts!

Optimization Shortcuts in 4.5

dotTrace 4.5, which at the time of publishing this post is in EAP, introduces some shortcuts for time adjustment. When right-clicking on Adjust Time context menu, a submenu displays two additional options:

which allow us to quickly optimize the current (or all) instances of a specific method. Optimizing means setting the total time to 0.

Experimenting before committing

The reason for the Adjust Time feature in dotTrace is for experimenting with different calls before actually having to commit to changes. Often a 10% increase in one function can lead to a 20% overall improvement. Other times, it can lead to a 2% improvement. Knowing this before hand is very valuable since it provides us with something to balance against to see not only whether we’re barking up the wrong tree, but also if it’s worth barking at all.

ReSharper 6 Bundles Decompiler, Free Standalone Tool to Follow

Thursday, February 17th, 2011

Previous posts introducing ReSharper 6:

What’s going on here?

We’ve recently hinted on a new kind of functionality that’s being developed within ReSharper 6 EAP. Those of you who saw that post got the message right: ReSharper 6 will feature a decompiler. More than that, it is already available in ReSharper 6 EAP builds that you can download and try.

As if it isn’t enough, we have more great news: make sure to read on to the end of this post.


How do I invoke the decompiler in ReSharper?

There are several ways you can navigate to decompiled code in ReSharper:

  1. You can navigate to a decompiled library symbol right from its usage in the source code. This should be done via ReSharper’s Navigate To feature. To invoke Navigate To, press Alt+` and select Decompiled sources:
  2. You can jump to the declaration of a specific library type from anywhere within Visual Studio using ReSharper’s Go to Type menu (Ctrl+T in Visual Studio layout). You can even go further by jumping to a specific library method or property using Go to Symbol (Shift+Alt+T).
  3. If you prefer browsing library types using the Object Browser, you can invoke Navigate To Decompiled Sources right from there:

  4. Will common ReSharper features be available with decompiled code?

    Well naturally, you can’t refactor decompiled libraries, generate new code in them, or run code inspections (though it would be fun in some cases).

    However, most navigation features that ReSharper normally provides in source code are equally available in decompiled code. For example, you can:

    • Navigate to declarations and implementations:
    • Search for usages, inheritors, and base symbols:
    • Explore a decompiled type with File Structure:
    • View type hierarchy or even see incoming calls to library symbols from your source code:
    • Highlight usages of symbols:


    Where can I configure the behavior of ReSharper decompiler?

    Decompiler is configured in the same group as other features from the External Sources feature group, namely ReSharper | Options | Tools | External Sources | Decompiled Sources.

    If you’re trying to get ReSharper show decompiled code but it’s failing to do so, make sure that Decompiled sources is selected as an external sources data provider in ReSharper | Options | Tools | External Sources. By the way, if Decompiled sources is at the top of the list, you can navigate to decompiled code with Go to Declaration (F12 or Ctrl+click).


    How sophisticated is ReSharper decompiler?

    Let’s just say, ReSharper decompiler is sophisticated enough to correctly infer lambda expressions and yield returns. Some things are not yet supported, for instance auto-properties, but that’s only a question of time.


    Why has ReSharper moved in this direction?

    Source code management has been in focus of the developer community for ages. We have lots of source code storage systems with histories and branches, distributed and personal, tools ecosystem, and what not. However, many applications are quite large today, and handling them in source form tends to get more and more complicated. Setting up binary reusable libraries even inside a single business entity can be a very painful thing to perform.

    ReSharper started assisting developers with this in version 5, by introducing navigation to and within external sources. The External Sources feature brings code available through information in PDB (Program DataBase) files straight into Visual Studio editor. For example, when Microsoft releases another library in Reference Source form, they publish PDB files having links to their Source Servers. ReSharper can parse this information, download source files and display them for a developer to explore.

    That’s cool, but what about home-built libraries? What if your company doesn’t have Source Server infrastructure in place and doesn’t want to invest into getting one? How to get seamless integration with source code and binary libraries referenced in projects?

    That’s exactly the task that the decompiler in ReSharper 6 is going to solve. Adding to the Source Server support, the new ReSharper reconstructs source code from compiled assemblies and enables all code reading features in such files.

    Say, one department in your company builds a framework, and another department uses it to create an end-user application. You can reference assemblies for the framework and avoid bloating your workspace with files and projects that you don’t really need. However, when required, you can easily jump into decompiled sources and explore internals. Should you need further details — comments, real variable names, exact code — you can go and check out sources for that project, but in fact it is quite rarely needed.

    Another point is the emerging market of packaging solutions: NuGet and OpenWrap to name a few. Packages (or wraps) contain binaries and tools, but not source code. However, many of them are open source and it is perfectly legal to look for sources, even reconstructed. We would like to talk to providers of packaging solutions and ask them to include information about source code locations into package descriptors, so that everybody can get the exact source code for a specific version of binaries.



    Will the decompiler be only available as a part of ReSharper?

    At this point you are probably asking yourself “Well, but what about a standalone solution? I don’t need ReSharper!”.

    Bad news is you should only not need ReSharper if you’re not doing .NET development.

    Good news is that we’re preparing a standalone binary-as-a-source application, i.e. a decompiler + assembly browser to explore whatever .NET compiled code is legal to explore. We don’t have any specific date for release, but it’s going to be released this year, and it’s going to be free of charge. And by saying “free”, we actually mean “free”.

    UPDATE (May 12, 2011): Standalone decompiler called dotPeek is now available for download!


    If you’ve read it up to this point, you completely owe it to yourself to try ReSharper 6 EAP builds with decompilation engine right now!

    Let us know what you think about the quality of the decompiler and overall source-binary integration experience and how we can make it even better for you.

CSS Support in ReSharper 6

Tuesday, February 15th, 2011

ReSharper 6 EAP has been available for about 1.5 months, and it’s time to move on zooming into new features that this new version brings.

We’ve announced that supporting JavaScript and CSS is one of the most important directions in ReSharper 6, and following an earlier post about JavaScript support, let’s take a look at the second major functionality area for ReSharper 6: support for CSS. It is currently represented by the following features:

Syntax/Color Highlighting and Palette

ReSharper applies its own highlighting to CSS syntax including properties and functions:

Syntax highlighting in CSS files

Property values representing colors is another item that ReSharper highlights and provides additional assistance for. Every color value is underlined with a respective color, and there’s a quick-fix available to help change the color:

Color highlighting and access to the Select Color window in CSS

As soon as you select the quick-fix, ReSharper shows the Select Color window that contains controls to fine-tune the color based on any property:

Select Color window to select color in CSS

CSS Validation

Whenever ReSharper fails to validate a CSS symbol, it leaves a mark on the marker bar and, when you hover the mouse over the error, tells you what it expects to see:

CSS validation with custom error messages

File Structure and Go to File Member

File Structure and Go to File Member have both successfully arrived to CSS files:

File Structure in CSS files

These navigation features fully support lowerCamelCase search, enabling you to instantly land at selectors with tricky names, like this:

Go to File Member: find all selectors in file by name

The same technique can be applied to properties. -webkit-border-top-left-radius anyone?

Go to File Member: find all properties in file by name

Find Usages

You can easily find where a certain CSS property or selector is used both within the current file and in a larger scope. For example, when you have multiple CSS files in your solution, applying Find Usages over a selector in one of these files finds all occurrences of the selector in all remaining files:

ReSharper lets you find all usages of a selector in all CSS files

Code Completion

ReSharper provides its own IntelliSense in CSS files and in other file types where CSS can be used. It helps you complete HTML tag names, including those introduced with HTML 5:

ReSharper helps complete HTML tag names in CSS

It lists available HTML attributes in a similar way after the opening bracket:

ReSharper completes HTML attributes after the opening bracket in CSS

In fact, ReSharper code completion helps in multiple scenarios when you specify selectors. For example, it provides a list of available pseudo-classes after colon:

ReSharper helps complete all kinds of selectors including pseudo-classes

Sure enough, ReSharper code completion suggests available properties…

ReSharper suggests CSS properties matching a given lowerCamelCase-enabled string

…and property values:

ReSharper suggests CSS property values matching a given lowerCamelCase-enabled string

On top of that, ReSharper suggests available classes when you’re invoking code completion inside the value of the class attribute…

ReSharper code completion for CSS classes in markup files

…and available id’s within the id attribute in HTML or ASP.NET markup files:

ReSharper code completion for CSS id selectors in markup files

To sum up most significant benefits of ReSharper code completion in CSS over Visual Studio native IntelliSense:

  • ReSharper provides completion for all kinds of selectors, including elements, .classes, #id’s, [attribute]s, and :pseudo-elements in CSS files.
  • Both ReSharper and Visual Studio provide completion for properties and values in CSS files. However, ReSharper code completion supports lowercase CamelHumps, letting you complete background-color by only entering bc.
  • Both ReSharper and Visual Studio complete usages of CSS classes in markup files but ReSharper goes further by completing usages of id’s.

Rename Selectors

Naturally, the majority of ReSharper refactorings are not applicable in CSS, but some of them could work there just fine. The first refactoring to be provided in CSS is the Rename refactoring.

With ReSharper 6, you can rename a class selector — both from its declaration in a CSS file and from its usage in markup files.

ReSharper renames a class selector from its declaration

Of course, whichever way you choose, all usages of the class selector in markup and all CSS files are updated accordingly. In addition, as you would expect, ReSharper will let you rename any occurrences of the old selector name in comments:

ReSharper finds class selector name usages in comments

A couple more CSS-specific refactorings are in the works, as well as other nice CSS support features here and there.

Download ReSharper 6 EAP builds and explore the goodies!

Using a ToDo list more effectively

Tuesday, January 25th, 2011

Have you ever had the need to place a TODO in your code? I’m sure we’ve all done so, for some reason or another. Normally it’s just a temporary reminder that we’ll get back to after finishing off something else, in an attempt to avoid breaking the expensive flow we get our minds into when writing code.

Similar to comments however, TODO’s are only valuable if they have meaningful information, and much like comments, we developers, aren’t necessarily to attentive to such things. A TODO can be a bug, a code smell, an optimization or even a feature that would need to be logged. As such, it would be more valuable if things TODO’s were defined correctly, something that doesn’t often happen (specially when considering the whole flow thing…). That translates into expecting TODO’s inline with:

// TODO: this needs cleaning up

// FEATURE: Need to add support for XYZ

but in turn we get:

// this is some stinky piece of code

// ultimately we need to support feature XYZ

// this code smells worse than a dark alley next to a Club on a Sunday morning

The problem with this, apart from the inconsistency that can cause you sleepless nights, is that things can get lost. The TaskList feature in Visual Studio requires these kind of comments to follow a certain pattern, and even when that occurs, the way they are presented leaves a bit to be desired.

image

[Visual Studio Task List]

Enhancing ToDo’s

ReSharper ToDo management adds several benefits over Visual Studio’s built-in. But before we see these, let’s first examine how we can solve the previous problem. To recall, what we want to do is be able to support multiple formats when it comes to defining comments, so // TODO: fix this and // add this to the list of ToDo’s to fix both would appear under the list of ToDo’s.

Fortunately, the way ReSharper allows us to define ToDo items make this very simple. First, in order to access the definitions, we go to ReSharper| Options | ToDo Items

image

Selecting any of the items (for instance the first one) and double-clicking or clicking on Edit, we get the definition dialog box:

SNAGHTMLd8e0cd3

As opposed to the default Visual Studio, with ReSharper we use regular expression. This provides us with the flexibility required. The above example for instance is telling ReSharper to search for any pattern that contains the word TODO in it. By default, normally these patterns are searched for in comments, although we can optionally look in strings and identifiers too. We do not have to worry about defining case-sensitivity in the regular expression. Instead we can just mark the Case sensitive checkbox if we require it. Finally, we can define the color and icon we want displayed when viewing the list of items (which we’ll see later on).

Adding new Items

By default, out of the box, ReSharper comes with four items (Todo, Bug, Note and NotImplemented). We can easily extend this to offer support for other items such as identifying code smells, features, etc. Easiest way is to simply click on an existing item and Duplicate it:

SNAGHTMLdbf5c1b

Searching and Filtering Items

Having the items defined, we can now display a list of them by invoking the Todo Items Explorer from ReSharper | Tools | To-do Items, or pressing Ctrl+Alt+D (VS Scheme)

SNAGHTMLdc547b1

The advantage of course is that it is not required for items to begin with a certain word, as this can be in any position of the string. ReSharper also allows us to filter items so that we can focus on a specific type of task by using the Filter option:

image 

which can also be customized using under Tools | Options (accessible too from the To-do Explorer [icon to the left of Filter]). Last but not least, we can also group items by a variety of options, from namespaces to projects, to types, etc.

SNAGHTMLdc90bf9

Now that’s what I call a colorful, albeit long list of tasks!

In-depth look at Customizing Type Layout with ReSharper

Tuesday, January 4th, 2011

When we run Code Cleanup with ReSharper, one of the options it has is to re-order the member layout in classes. This means that some ugly layout like this

image

can be turned into this

image

(you need to have Reorder Type Members checked).

The advantage is that we don’t need to constantly worry about making sure properties and fields are declared in their correct position, wasting time manually re-arranging code.

What happens however when we don’t agree with ReSharper’s choice in layouts? Recently I came across this situation when I ran the clean-up (by mistake) on my Specifications project. I use MSpec and I like to keep certain things in certain places. In particular, with MSpec you make use of statics and I like to have them placed at the bottom of each class where I can ignore them.

image

Of course, when I ran ReSharper clean up, I ended up with

image

So what to do? Well, I am aware of the possibility of modifying how type members are ordered in ReSharper, the problem with it however is that it’s global, that is, you can’t change it per project. What hadn’t occurred to me (talk about not looking at the default pattern. Thanks Alex) was to bind the customization to MSpec’s Subject attribute that specifications have (albeit it is not required but nice practice).  Although much of the work is done, I thought it would be a good opportunity to delve a bit more into customizing layouts since it could probably benefit others. So here goes…

Customizing Type Layouts

Layout is defined in ReSharper using XML which is defined under ReSharper | Options | Languages | C# | Type Member Layout

SNAGHTML70374c6

To get access to the default pattern and customize it, we need to uncheck the Use Default Patterns checkbox, which then causes the editor to display the text. Don’t be scared!

image 

What we see is the XML file that defines the pattern layout. Most of the text is actually comments defining how things are layout. The actual patterns start lower down (although there’s no scrollbar, you can scroll). Here is the same contents in a nicely XML highlighted view

image

A Pattern (<Pattern></Pattern>) consists of multiple entries (<Entry></Entry>). Each entry in turn represents some type of member. The order of these entries define the order in which the code is laid out. Let’s take a look at an entry in more detail

image

Each entry consists of a <Match> element and optionally a <Sort> and <Group> element. <Match> in turn consist of one or more Operands combined using <And>/<Or> and negated with <Not>. An Operand can be:

Operand $val can be..
<Kind Is=”$val” [Order=”$val”]>

class, struct, interface, enum, delegate, type, constructor, destructor, property, indexer, method, operator, field, constant, event or member

<Name Is="$val” [IgnoreCase=”true/false”]> Regular expression. IgnoreCase indicates whether to ignore case
<HasAttribute CLRName=”$val” [Inherit=”true/false”]> Regular expression. Inherit indicates if it applies to inherited classes.
<Access Is=”$val”> public, protected, internal, protected internal, private
<Static/>
<Abstract/>
<Virtual/>
<Sealed/>
<Readonly/>
<ImplementsInterface CLRName=”$val” [Immediate=”true/false”]> Regular expression
<HandlesEvent/>  

Taking this into account, if we look at the previous pattern, we see that we are trying to match constructors, specifying (optional) that static constructors should be ordered first. Let’s take a look now at a more “complicated” pattern

image

This pattern is for matching instance fields that are not static. What we do is identify fields using the Kind Operand and passing field as the value for the Is attribute. Since we are interested in non static fields, we add a <Not> operator around a <Static/> operand. We need to wrap this in an <And> operator (using Polish notation). Finally, let’s look at static fields and constant

image

Here the pattern should match a constant or (<Kind Is=”constant”>) <And> a static field (<Kind Is=”field”>) which is <Not> static (<Static/>). Again, if we look at this using Polish (or prefix) notation, it is easy to understand.

Defining Multiple Patterns

Having understood the basics of how patterns are defined, we can now come back to solving our issue with MSpec. Our issue is where statics are located. One solution would be to move the static pattern to the lower part of the pattern. Problem of course is that this would effect all classes. We only want it to effect classes that are of MSpec, that is, have the Subject attribute.

The key in solving this problem is to define a different pattern for MSpec classes. In the Pattern definition file, we can have multiple patterns. What we can therefore do, is add a new pattern specific for our MSpec classes. How will ReSharper choose which pattern to use? That’s solved easily by defining a <Match> as the first element of each Pattern

image

We have defined a new pattern that has a <Match> element with an <HasAttribute> for the Subject attribute of MSpec. When we now run Code Cleanup, ReSharper will match the pattern with MSpec classes and apply the appropriate layout. In our case, the only thing we have defined is that static fields should be after all other entries (indicated by using the <Entry/> element). This means that we are leaving layout as is for everything else (in real-world scenarios, this might not be the case. The MSpec file defined by Alex in fact has a full nice layout for MSpec).

Giving Matches Weights

In the previous pattern definition, there would not be any conflicts between the default patter and that of MSpec because the <HasAttribute> element discriminates correctly only MSpec classes. What would happen however if two patterns would match? That is where the weight factor comes in. Each <Match> element can have a Weight attribute associated with it. In case of conflicts, the one with the highest weight wins.  

Sorting, Grouping and Regions

In addition to matching elements and defining their positions, we can also specify sorting and grouping options with patterns. By providing a <Sort> element

 image

and defining the Operand by which it is to be sorted, elements that match the pattern will follow the specified order. In a similar way, using the <Group> element, we can group similar constructs and optionally wrap them in regions. Many of these operands can take as attribute values the variable they represent. In the previous pattern, we are specifying as the region name the variable ${Name} which will be instantiated to the name of the type.

One final option is the possibility (which many of us are thankful for) of removing regions on cleanup. Each <Pattern> element has an attribute RemoveAllRegions which can be set to true or false. By setting it to the latter, regions will be removed on code cleanup.

As we can see, the possibilities of laying out type members when performing code cleanup are quite unlimited. The process is a little bit cumbersome, mostly due to the editor, although there are already planned improvements for ReSharper 6. Nonetheless, if you have any feedback, please send it now or log it in YouTrack.

[Download the XSD Schema here]

ReSharper NullReferenceException Analysis and Its Contracts

Wednesday, November 17th, 2010

If you use ReSharper, you are likely familiar with its Possible ‘NullReferenceException’ inspection. I want to talk about the analysis engine that displays this type of warnings and how you can, with just a bit of work, use it for best results.

Consider this sample code:

public string Bar(bool condition)
{
 string iAmNullSometimes = condition ? “Not null value” : null;
 return iAmNullSometimes.ToUpper();
}


ReSharper will reasonably highlight iAmNullSometimes in the second line of the method with the ‘NullReferenceException’ warning. Now let’s extract the method:

public string Bar(bool condition)
{
 string iAmNullSometimes = GetNullWhenFalse(condition);
 return iAmNullSometimes.ToUpper();
}

public string GetNullWhenFalse(bool condition)
{
 return condition ? “Not null value” : null;
}


The warning no longer pops up. Why?

The Analysis Engine

The analysis engine tries to determine what values variables could have. Let’s see what level of abstraction its knowledge of variable values is reduced to. From its point of view, a variable can be in one or more of the following states:

  • NULL, NOT_NULL — either null or non-null value.
  • TRUE, FALSE — the same for bool type.
  • UNKNOWN — this value is introduced for optimistic analysis, which is used to minimize the risk of incorrect analysis.

In the end, the analysis engine determines a set of possible states for a variable’s every use point.

In the first code sample above, after iAmNullSometimes is initialized it will have two possible states: NULL or NOT_NULL. Therefore, the Possible NullReferenceException highlighting tells us that there exists at least one execution path in which iAmNullSometimes will be null (in this case, when condition is FALSE).

The second code sample is more complex. The analysis engine doesn’t know what kind of values GetNullWhenFalse returns. Of course, we could analyze it and make sure it could also return a null. But this would increase the number of methods being analyzed (which also call something in their turn), and thus greatly increase analysis time. Unfortunately we cannot afford that kind of on-the-fly analysis on today’s PCs (to have ReSharper highlight all possible errors). Note also that the method being called could potentially belong to a library referenced in our project. It would be unwise to decompile and analyze that library on the fly too.

There is another possible option: to assume that the external methods, which we know nothing about, return either NULL or NOT_NULL. That’s how pessimistic analysis works.

By default, ReSharper uses optimistic analysis. In this kind of analysis, if we don’t know anything about a method, its return value will be in the special state called UNKNOWN. If a variable is in the UNKNOWN state at the time of use, it isn’t highlighted (unless of course there are other ways in which it can be assigned the null value, either explicitly or from a CanBeNull type of method). That’s what makes the analysis engine ‘let its guard down’ in the second code sample.

Whether we are doing optimistic or pessimistic analysis, we want to somehow find out what the method being called is capable of doing, so that ReSharper can find more potential errors. This is where contracts come in.

Contracts

ReSharper analysis engine can use additional knowledge of the called methods, which it obtains through contracts such as “method never returns null,” “method can return null” or “method doesn’t take null parameters.” In the basic case these contracts are defined through the attributes JetBrains.Annotations.CanBeNullAttribute and JetBrains.Annotations.NotNullAttribute. Applying one of these to a method specifies whether it can return a null. Applying one to a parameter specifies whether it can be null. You can also apply these attributes to properties and fields. They are defined in the library JetBrains.Annotations.dll which is located in <ReSharper install directory>\Bin.

Our second code sample above can be improved by marking GetNullWhenFalse with the CanBeNull attribute:

public string Bar(bool condition)
{
 string iAmNullSometimes = GetNullWhenFalse(condition);
 return iAmNullSometimes.ToUpper();
}

[CanBeNull]
public string GetNullWhenFalse(bool condition)
{
 return condition ? “Not null value” : null;
}


Now, when we use a method of iAmNullSometimes, the Possible ‘NullReferenceException’ highlighting appears.

Unless you want to maintain an extra assembly with your project, which doesn’t do much for your application’s functionality during runtime, you can declare these attributes right in your project. But basically, the analysis engine will make use of any attributes from any assemblies, as long as their names match those in JetBrains.Annotations.dll. The definitions of these attributes can be easily accessed via the Copy default implementation to clipboard button located on this ReSharper Options page:

External Annotations

If you’re using an external library (e.g. mscorlib.dll), it doesn’t seem feasible to specify contracts for its entities using attributes. Enter External Annotations. This ReSharper feature allows you to complement the already compiled entities with attributes used by ReSharper’s analysis engine. External Annotations let you ‘cheat’ the engine, by making it see the attributes (for methods, parameters and other declarations) which weren’t declared at the time the library was compiled. To do this, the attributes must be specified in an XML file located in <ReSharper install directory>\Bin\ExternalAnnotations.

Such is the definition of contracts for standard libraries stored in this folder when ReSharper is installed. These contracts are obtained based on source code analysis as well as Microsoft Contracts. The contracts obtained using the former technique are stored in files of the type *.Generated.xml, while those obtained using the latter technique are stored in files of the type *.Contracts.xml.

The files that describe additional attributes have a structure similar to XmlDoc. For example, for the method XmlReader.Create(Stream input) from the assembly System.Xml of .NET Framework 4.0, NotNull contracts are defined as follows:

<assembly name=”System.Xml, Version=4.0.0.0″> <!—The attribute name contains the assembly name. If you don’t specify the version, this file’s attributes will be applied to all versions of the assemblies of that name –>
<member name=”M:System.Xml.XmlReader.Create(System.IO.Stream)”> <!—This shows the name of the member whose attributes are complemented; the notation is the same as XmlDoc –>
 <attribute ctor=”M:JetBrains.Annotations.NotNullAttribute.#ctor” /> <!—attribute constructor names are also specified using XmlDoc notation –>
 <parameter name=”input”>
  <attribute ctor=”M:JetBrains.Annotations.NotNullAttribute.#ctor” />
 </parameter>
</member>
</assembly>


To make sure ReSharper recognizes the file, you should store it either as <ReSharper install directory>\Bin\ExternalAnnotations\<Assembly name>.xml OR as <ReSharper install directory>\Bin\ExternalAnnotations\<Assembly name>\<Any name>.xml, where <Assembly name> is the assembly name without the version. If you use the latter kind of location structure, you will be able to specify multiple sets of contracts for the same assembly. This may be useful if you need to use different contracts for different assembly versions.

Right now, editing these files isn’t as easy as we’d like — it involves a lot of manual work plus requires administrator-level privileges. But we’re planning to release a handy tool to simplify this pretty soon. Most likely it will come in the form of a ReSharper plug-in.

Use Cases

Here are some External Annotations use cases that will help you get more from ReSharper.

XmlDocument.SelectNodes(string xpath)

The CanBeNull annotation for this method gives rise to many bug reports. The thing is that SelectNodes is a method of XmlNode and can generally return a null (for example, for XmlDeclaration). But most of the time we use this method in such a way that it cannot return a null — from XmlDocument. One solution would be to delete this annotation from External Annotations or replace it with NotNull. But there is a better way: to write an extension method for XmlDocument:

public static class XmlUtil
{
 [NotNull]
 public static XmlNodeList SelectNodesEx([NotNull] this XmlDocument xmlDocument, [NotNull] string xpath)
 {
  // ReSharper disable AssignNullToNotNullAttribute
  return xmlDocument.SelectNodes(xpath);
  // ReSharper restore AssignNullToNotNullAttribute
 }
}


In this case it would also make sense to create additional methods such as SelectElements and SelectAttributes, to avoid typecasting every time, but that’s another story.

Assertion

If you use your own Assert methods or those from an external framework, they can be marked with the attributes AssertionMethodAttribute or AssertionConditionAttribute. Top of the list candidates for this would be Contracts.Assert methods, as long as you use Microsoft Contracts:

<assembly name=”Microsoft.Contracts”>
<member name=”M:System.Diagnostics.Contracts.Contract.Assert(System.Boolean)”>
 <attribute ctor=”M:JetBrains.Annotations.AssertionMethodAttribute.#ctor”/>
 <parameter name=”condition”>
  <attribute ctor=”M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)”>
  <argument>0</argument>
  </attribute>
 </parameter>
</member>
<member name=”M:System.Diagnostics.Contracts.Contract.Assert(System.Boolean,System.String)”>
 <attribute ctor=”M:JetBrains.Annotations.AssertionMethodAttribute.#ctor”/>
 <parameter name=”condition”>
  <attribute ctor=”M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)”>
  <argument>0</argument>
  </attribute>
 </parameter>
</member>
</assembly>



If you have methods that always throw exceptions, you can also consider TerminatesProgramAttribute.


Author: Alexey Kuptsov, ReSharper developer. Translated from original article (in Russian)

Source code in this post is highlighted with Source Code Highlighter.

ReSharper 5 Overview: Navigation to and Within External Sources

Monday, October 4th, 2010

While you’re waiting for the first public build of the recently announced ReSharper 6, here’s a follow-up on the “Introducing ReSharper 5″ blog post series that we did earlier this year. One feature that we have not highlighted before but that’s a major presence in ReSharper 5 is navigation to and within external sources.

When you want to know how a certain method is implemented, with ReSharper you expect to be able to quickly navigate to the declaration of an identifier. In most cases you can do this perfectly well. However, things get tricky in the following two scenarios:

  1. The method you’d like to zoom in on is part of the .NET Framework.
  2. Your really huge project is broken down into several subprojects. You’re working in one of them but the class or method that you want to navigate to is declared in another subproject.

ReSharper 5 covers both scenarios with a fresh feature called “External Sources”. External Sources makes all sources available to a developer even if they should be accessed remotely. This is the first step to eliminating differences between your local working copy and actual sources of all components involved in your project.

Let’s take a look at standard use cases when you need access to sources not included in the current project.

.NET Framework Sources

Microsoft provides free access (with certain licensing restrictions) to source code of the entire Microsoft .NET Framework. Within plain Visual Studio, you generally access it during debugging sessions. ReSharper complements this use case with the following extended functionality:

  1. Navigation to.NET Framework sources.
  2. Find Usages over all .NET Framework public symbols.

This enables you to easily and transparently access sources of complex .NET Framework classes such as DataGrid.

Your Company’s Library Sources

When working on a big project, a developer usually either doesn’t have the entire sources on their local machine, or they do have them but not in the current project.

In the latter case, if the sources are available but not included in the current project, ReSharper allows you to specify the path to these sources. So, when you try to navigate to an external symbol, ReSharper will search the local (or network) drive for the appropriate file and open it. The only requirement is having .pdb files available for external components.

In the former case, if the sources are way too numerous (or if it is simply impractical to store them all locally, i.e. if they are used infrequently or if there are just too many versions), you can use the Microsoft Source Server. There’s a good chance that it’s already installed in your place of work. ReSharper provides full support for the Microsoft Source Server and relies on it to implement navigation to the source of the .NET Framework. All you need to do is specify the path to the local server(s) in Visual Studio (Tools | Options | Debugging | Symbols).

Reflector Plugin

Now, what do you do if you don’t have .pdb’s, or even no sources at all? Or if you can’t set up Source Server?

For many developers the answer is Reflector. But as you probably know, it is rather cumbersome to use: first you find the right .dll, then you look inside it for the symbol you need. ReSharper PowerToys include a plugin that lets you to connect Reflector with Visual Studio. On the outside it will look like you’re navigating to the source, only Reflector will be used ‘behind the curtains’ to retrieve them.

You might ask, in what way is Reflector integration with Visual Studio inferior to that of ReSharper? We at ReSharper wanted to make the integration seamless, and that’s exactly what our plugin does. You no longer have to think about where a particular symbol is declared - ReSharper finds it for you, wherever it is. First it looks for it on your local drive, then it polls the Source Server, and if that fails, finally it decompiles the sources you need via Reflector.

About Options

If you open ReSharper Options and select External Sources, you will see a list of configured source providers. Use this dialog window to define the order in which these providers will be polled. For some providers you can define additional options, e.g. set C# or VB as the presentation language, show XML-doc or not, etc.

The first time you try to navigate to an external source, ReSharper will ask you which provider to use by default:

External Sources

If you’re not happy with the current provider or the default provider, you can always click on a symbol to bring up the Navigate To menu (ReSharper | Navigate | Navigate To…) and switch the view:

Navigate To

The Way Forward for External Sources

In Internal mode, you can already see the feature called “Find Usages In Compiled Code”. This works like Find Usages which lets you search for symbols used in builds already compiled. This tool is indispensable for situations such as when you’re developing a system core and you must know exactly where and how your public API methods are used.

Another area JetBrains will focus on in growing this functionality is integration with TeamCity — one of today’s most powerful Continious Integration products. Oftentimes, different development teams work on different parts of a system, and synchronizing all their source versions and compiled libraries becomes a real challenge. Enter TeamCity: it knows at all times which source version corresponds to each local library version. Why maintain a huge codebase locally, when you can rely on TeamCity to be your company’s internal Source Server — with no extra configuration required?

Author: Alexander Zverev, senior ReSharper developer

Templates Galore: File Templates

Tuesday, August 24th, 2010

Continuing with Templates, in this post we’re going to take a look at File Templates. Whereas Live Templates allow us to generate interactive code and insert this at the current cursor position, File Templates allow us to do the same but directing the output to a file. Additionally, as we’ll see, they are very useful for creating both standard and custom files efficiently.

If we open up the Templates Explorer via ReSharper | Live Templates, we can see three tabs: Live Templates, Surround Templates and File Templates.

SNAGHTML2cd01427

Similar to Live Templates, Files are organized into different categories, corresponding to the type and language of a project. By default the predefined ones include templates for Web Applications (ASP.NET) and generic applications (Console, WinForm, Libraries, etc.). There are also User defined ones as well as Shared Solution and Personal Solution, again similar to Live Templates.

On the right-hand column we have a repeated set of templates. What these allow us to do is customize the usage of templates. However, before seeing that and delving into creating new templates, let’s see how we can use the existing ones.

Using Templates in Web Applications

1. Create a new Web Application (can be MVC or WebForms) to work with.

2. There are multiple ways to create new file templates with ReSharper (right-click Solution Explorer |Add | New From Template or via the ReSharper | Edit | New From Template menu). However, by far one of the easiest and most efficient ways is what we introduced in ReSharper 5: Create New File. You can invoke this from anywhere, be it the Solution Explorer or from a file in the editor, by pressing Ctrl+Alt+Ins

image 
[Pressing Ctrl+Alt+Ins in ASPX editor]

 

image 
[Pressing Ctrl+Alt+Ins in Solution Explorer]

Since this is a Web Application, the list of Templates to choose from include all those that appeared under ASP.NET Projects in the Template Explorer. In addition, since creating a Class, Interface, Struct or Enum are still valid in the context, it will display those too.

3. Select a new file, for instance Web form with master page and provide it with a name and hit OK (Enter key)

SNAGHTML2cee1c61

4. Based on the type of file, and in particular the template it contains, we will be prompted for additional information. In this case since we requested a Web Form with a MasterPage, ReSharper prompts for the MasterPage file

image

5. Select the corresponding master page and hit Enter.

We’re done. With very little effort, we’ve created a new Web Page and referenced the Master Page. Comparing that to the default way of creating Web Forms (or in fact any other item) in Visual Studio, we can quickly see how much more efficient it can be. However, the true power of this lies in it’s customization, not only in the template but also in what templates we can choose from.

Customizing the Files we care about

When invoking the Create New File, the list that appears is customizable, both in regard to the contents as well as the ordering. Imagine for instance that we usually work with MVC applications and Spark View Engine and are not really interested in WebForms. Having things like Web Control or Web Form with master page pop-up only add noise to the options. Fortunately we can eliminate these easily:

1. Open up the Templates Explorer editor via ReSharper | Live Templates and select File Templates

2. Select the element we don’t want to appear when creating a new File Template. In this case we want to eliminate Web Controls and Web form xxxx

SNAGHTML2d038f50

3. Click on the red cross (X)

4. Close the Templates Explorer

5. Invoke the Create New File menu by pressing Ctrl+Alt+Ins. It should now only display the remaining entries.

image

Apart from eliminating entries, we can also change the sort order by dragging the entries in the Templates Explorer (right-hand column, same place we selected to delete in step 2) up and down.

Creating new File Templates

Being able to generate templates fast, customize them and edit them wouldn’t be sufficient if we couldn’t also create new ones. Fortunately, we can. Let’s see how we can easily create simple DTO objects that use for instance the DataContract and DataMember attributes.

1. Create a new project. Any type will do.

2. Open Templates Explorer via ReSharper | Live Templates and click on File Templates

3. Select the User Templates node and right-click to create New Template

image

3. In the Template Editor, type DTO for the Description and NewDTO.cs for the file name

4. Enter the following in the Editor

SNAGHTML2d410809

We now need to define some macros on the placeholders (variables $nameSpace$, $className$, etc.).

Note: The first [DataMember] property we’ve added is of course optional and more for demonstration purposes.

5. Select the nameSpace placeholder in the right-hand column and for the value choose “Default namespace for current file

6. Select the className placeholder in the right-hand column and for the value choose “Current file name without extension

7. Uncheck the Editable Occurrence on previous two entries. This prevents ReSharper prompting us for values

8. Save changes and close the editor

Using the new File Template

We saw that File Templates can be invoked using Ctrl+Alt+Ins (Create New File). However if we do this now, our template will not appear. That is because we need to tell ReSharper we want it on this quick list. We can do this in two ways:

Method 1: Invoke the template using an alternative option, for instance ReSharper | Edit | New From Template and selecting More..

image

This will bring up a dialog box with other templates:

SNAGHTML2d4b70d9

where we can select our Template. At this point we can tick the CheckBox “Add to quicklist”, selecting the Category from the Dropdown below it.

Method 2: Alternatively, we can drag and drop the template from the Template Explorer to the Category we are interested in (for instance C#)

SNAGHTML2d50a8da

Either way we choose, from this point on, our template will now be accessible via Ctrl+Alt+Ins:

image

Summary

With File Templates we can easily create files that are used frequently, such as DTO’s, Unit Tests, Controllers or other common classes we create. In addition to providing an efficient way to create these items, we can also interact with them, just like we do with Live Templates to adapt them to our needs on each creation.