22 May 2007

Coding Session with ReSharper

ReSharper team is approaching Feature Freeze milestone for version 3.0, so I didn't have time to write thoughtful posts. However, I needed to write primitive utility for doing some batch operations on the file system structure recursively, and I decided to record a small screen cast for part of the real coding session. It is about 8 minutes long and shows many things I use daily during development. I hope you will enjoy the movie :)

Download "Jedi Coding" from ReSharper Demo page.

Quality is not very good to keep size small. Music in background is "Voodoo People" by Prodigy from "Music For The Jilted Generation" album, I only repeated ending so it fit movie time.

Note: Some or all of the features seen in this movie may be available only in latest EAP versions of ReSharper.

08 May 2007

Code Completion with ReSharper

Completion with ReSharper is very different from what you have in Visual Studio. Some people refer to it as "broken". Indeed, when you start using ReSharper's intellisense, you may feel that something is "wrong". But it's just a little different and much better. I will describe completion features in ReSharper and you'll see how superior they are to what Visual Studio offers.

Look
Visually, completion list is not that different with default ReSharper settings. Here is original Visual Studio completion for type System.String, without any prefix:



Here is what ReSharper displays:



First evident difference is usage of bold font face. It emphasizes immediate members of type, those declared exactly in type for which completion was called. Note how GetType() is not bold, because it was inherited from System.Object. In large hierarchies, like windows controls, it is huge timesaver to be able to spot members specific to current type.

Another obvious difference is ability to show all overloads for a member in a signature popup, not just some random one with cryptic message (+2 overload(s)). You can instantly see that you can test end of line against string in a case-insensitive way and that it would be second boolean parameter.

You can also see, that ReSharper can suggest indexer (and correctly remove dot when inserting brackets). We also have some custom icons for parameters and local variables to distinguish them from fields.

If you wish, you can set completion font to match font in Editor and thus align completion items with what you type. You can tweak it on ReSharper/Options/IntelliSense/Code Completion page.

Narrow Down
More differences become visible when you start typing while completion list is open.



As you can see, list has become smaller and contains only items with the specified prefix, which is highlighted. For a large completion list, such as when you have windows control, it helps you quickly find what you need. It is even more important for type completion, but later about it.

Replace and Insert
The most confusing part and most difficult thing to adopt in ReSharper completion behavior is choosing between replacing and inserting. When you write new code, it doesn't matter, but if you are using completion inside existing expression it makes big difference. Consider the following example: we have method that replaces all spaces with underscores. Imagine that you need to modify the body to remove leading and trailing spaces before doing replacement.

        public string QuoteSpaces(string text)
        {
            return text.Replace(' ', '_');
        }


You position caret right after "text." and hit Ctrl-Space, then type few letters to locate Trim method.



Now, if you hit "Tab" key to complete the identifier it will remove "Replace" and insert "Trim", then put caret into parenthesis. Very useful when you need to change existing identifier to another one. Note the light red highlighting which denotes text to be removed, if you hit Tab. If you hit "Enter" key, it will just insert "Trim()" and let you specify parameters, if needed.

Name Suggestion
One more thing that ReSharper does for you is suggesting variable names when typing declaration.



It works for fields, parameters, variables, members and alike. Saves a lot of typing, I have to say. Name suggestion completion takes naming conventions into account, so be sure to set them in ReSharper/Options/Code Style/ C# or Visual Basic / Naming Convention.

Type Completion
Whenever you need a type at the caret position and you only have basic completion at hands, you have to type full type name and then import type via some sort of fix, e.g. Visual Studio smart-tag action. You also have to match case, and can you remember which one is right - DESCryptoServiceProvider or DesCryptoServiceProvider?

ReSharper comes to rescue with Type Completion, which shows all types matching prefix regardless of (un-)imported namespaces and inserts required using directives when you select a type.



Default shortcut is Ctrl-Alt-Space. Start using it now!

Smart Completion
ReSharper has deep knowledge about your code. Really! When you see variable declaration in gray, it is ReSharper who analysed execution flow and figured out that particular variable is not used. Some of this knowledge is available to you in completion. When it is known what type is expected at specific point, you may get filtered list of available symbols by invoking Smart Complete (default shortcut Ctrl-Shift-Space):



You can see that ReSharper suggested some static members of System.String and parameter "text". Well, you were going to return something of string type, so here you are!

Smart Completion is also smart enough to suggest anonymous and regular method creation:



Or even local variable creation in place of out parameter:



Conclusion
When you type code, completion is your best friend. Master all three completion kinds, practice for second-nature and you can achieve marvellous code generation speed.

Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

30 April 2007

Format Strings -- Episode Two

Last time I wrote about using string.Format as you type. What if you already have some code and want to transform it to string.Format?

    public override string ToString()
    {
      return "Folder: '" + myPath + "'";
    }

When you position caret inside such string expression, ReSharper displays light bulb and suggests few context actions (caret was on myPath in this case):



It is not surprizing that the first item in menu does what we want:

    public override string ToString()
    {
      return string.Format("Folder: '{0}'", myPath);
    }

If there is known method overload that fits format style, it will be used instead of creating extra string.Format call:

    public void Write(StreamWriter writer)
    {
      writer.Write("Folder: '" + myPath + "'");
    }

ReSharper converts it to:

    public void Write(StreamWriter writer)
    {
      writer.Write("Folder: '{0}'", myPath);
    }


Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

27 April 2007

Transforming Conditionals

Testing conditions is at least 50% of code in a typical program. When developer writes code, he not always knows in advance how method will look like at the end. Let's look at some typical cases.

This one is pretty simple method, which takes care of null object:

    public string ConvertToString(object obj)
    {
      if (obj != null)
        return obj.ToString();
 
      return null;
    }

Then I decided to add special handling for IConvertible:

    public string ConvertToString(object obj)
    {
      if (obj != null)
      {
        IConvertible convertible = obj as IConvertible;
        if (convertible != null)
          return Convert.ToString(convertible);
 
        return obj.ToString();
      }
      return null;
    }

Now it seems that it would have been better idea to check and return null immediately instead of placing all the code in the block. How can we fix this? I put caret on an "if" keyword and hit Alt-Enter.



After context action is executed I get what I need:

    public string ConvertToString(object obj)
    {
      if (obj == null)
        return null;
      IConvertible convertible = obj as IConvertible;
      if (convertible != null)
        return Convert.ToString(convertible);
 
      return obj.ToString();
    }

If you like shorter methods, you can further transform the code:



Accepting convertion to conditional makes it even smaller:

    public string ConvertToString(object obj)
    {
      if (obj == null)
        return null;
      IConvertible convertible = obj as IConvertible;
      return convertible != null ? Convert.ToString(convertible) : obj.ToString();
    }



Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

Highlight Usages Of What?

Many people know about Find Usages (default shortcut Alt-F7), which find usages of element under caret. Some people known about Highlight Usages (default shortcut Ctrl-Shift-F7), which places highlighting markers in current file on element usages. However, ReSharper can highlight usages of different things as well.

Usages of Namespaces
Position caret on "using" directive (Imports in Visual Basic) and invoke Highlight Usages command. ReSharper will highlight all symbols which depend on namespace in question.

Usages of Expressions
Select expression in code and invoke Highlight Usages command. ReSharper will highlight same expressions in other places in code.

Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

24 April 2007

Jedi Way -- Implementing Members

Object-oriented program is easy to read, if written properly. At every point you deal with appropriate level of abstractness and you don't have to deal with implementation specific details most of the time. However, when you have large type hierarchies and you are going to modify some aspect of a top level interface -- you may be in trouble. You have to thoroughly investigate all implementing types and provide method body for each one. ReSharper can help, of course.

Jedi Trick Level 1
Invoke Type Hierarchy and select Derived Types in the toolbar. You will see hierarchy of types derived from the interface. Use "Go To Next/Previous Occurence" command (Ctrl-Alt-Down/Up) to navigate between types. As soon as you have type which requires implementation in the code editor, Code Analysis will show red squiggly. Invoke Quick Fix to implement member and type in method body.

Jedi Trick Level 2
Use Context Action's power to implement members. Position caret on the newely created member, IsAvailable in this case. You will see the light saber bulb which is activated with Alt-Enter. Select "Implement member" and you will be prompted with the list of types. You can select "All above types" and get method body throwing NotImplementedException for every type.

Jedi Trick Level 3
Use Quick Fix power to implement members. Type in method body right in the interface, as if it were implementation. Code Analysis will show red squiggly, because interface member cannot have body. But you will also get two Quick Fixes via red light bulb - remove method body or use body for implementations. As soon as you select second one, body will be copied to appropriate implementations and removed from interface.

Jedi Trick Level 4
Available to Yoda only.

Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

Format Strings -- Episode One

Are you going to override ToString? You do this from time to time, definitely.



You begin typing format string and immediately see ReSharper coming to rescue in an absolutely non-invasive way. First the light bulb will appear.



Second, you hit Alt-Enter to see the list of available context actions. Only one is available here, but it is exactly the one we need.



Accept it with Enter and you can start typing arguments.



Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

Customizing ReSharper Colors

Sometimes people complain that they don't like ReSharper's colors, or default colors do not math their personal scheme, or identifier highlighting gets too much in the way. Luckily, you can configure colors.
Color configuration for ReSharper items can be changed in the Visual Studio Options (Tools Options menu), in the Fonts and Colors section. Select "Text Editor" in the settings combobox and scroll down to "Resharper" items. You will see color and font settings for identifiers of different kinds, error and warning highlighting, navigation targets, read/write usages and much more.

20 April 2007

The Horizon Comes Closer

It's been a while since I last wrote about ReSharper future. That's because we are actively working on ReSharper 3.0, the upcoming new version of our intelligent Visual Studio add-in. Besides numerous bug fixes, improvements and greater performance, we are adding more functionality to our product. In the upcoming posts I'm going to reveal what is going to be included in ReSharper 3.0 in more detail. Now I'll just list the most important things we are planning for this release:

Visual Basic .NET
C# developers already know how fast one can work with source code when ReSharper is installed. Now we bring the same pleasure to VB.NET developers. Editor improvements, such as expand/collapse selection, navigate next/prev member, duplicate line, comment/uncomment block/line and other small features, make code editing more enjoyable. Completion brings Smart Completion and Type Completion flavors to VB.NET along with automatic Imports inserting and all other bells and whistles. Code generation with Alt-Ins provides a quick means for generating properties, constructors, overriding and implementing members and works with the same level of cleverness as it does in C#. Live Templates now understand VB.NET and have smart iteration and cast templates, such as For Each or TryCast. Of course, we have Refactoring support for VB.NET in this version, which includes the most important refactorings like Rename, Move and Copy Type, Change Signature, Introduct and Inline Variable, and many others.

If you are a VB.NET developer and if you've ever seen how fast ReSharper-powered C# developers work, you owe yourself to try our EAP versions of ReSharper 3.0.

XML support
We are adding a number of useful editor improvements to Visual Studio XML support. They include expand selection, navigate to next/previous tag, replace tags, and some others. Live Templates are now supported in XML files and have some useful macros. Type completion works in XML, so that you can write configuration files easier. You can also navigate to type from XML.

XAML support
Being a language for user interface definition, it is still a compilation unit and it defines types and fields which are visible from other code. ReSharper is now capable of parsing XAML files, navigating, searching, and otherwise providing data for code exploration tools. We also plan to support smart completion and type completion in specific places, like event handlers, namespace aliases and tags/attributes where a control type is expected. Refactoring support in XAML will be limited in this version, but will allow renaming and moving types between namespaces without breaking code.

Tools
Besides all the languages support listed above, we are adding a number of useful tools and upgrading some existing tools. We've included To-do Explorer, which hunts for comments according to specified patterns and displays them in a dedicated tool window for quick access. We've improved Type Hierarchy to show members of selected type, either all or just polymorphic, and added some new hierarchy browsing capabilities. Unit Testing system is undergoing a major update to support multiple sessions, better support for various testing frameworks like mbUnit, VSTS and NSpecify, improved debugging usability and allow browsing solution for tests in dedicated Unit Test Explorer tool window. The "Go to by name" family of features, which already includes Go To Type, File or File member, is supplemented with Go To Symbol - your best friend when you remember a method's name, but not that util class it was seen in.

Improvements and bug fixes
I'm not going to give you a list of hundreds of bugs and exceptions fixed since previous release. I can't even remember all those small improvements here and there, which makes development with ReSharper even smoother and helps support development flow. Numerous context actions help craft code faster in many new use cases. New code analysis helps keep code clean and spot various problems as soon as you create them (accidentaly, of course). New quick fixes provide yet more automatic code corrections.

What next?
I'm going to blog in details about some of the new features in ReSharper 3.0 and show you some screen casts. I will probably break announced rules of this blog and start publishing tips and tricks, combos and advanced techniques in code generation, analysis and refactoring.

Stay tuned!

11 December 2006

ReSharper 2.5 Released

We are proud to announce ReSharper 2.5 release! You can read about what's new in this version in my recent post Near Future, and on official New Features page.

Current users of ReSharper 2.0 can use new version for free - just download and install it. If you didn't yet try ReSharper - you owe yourself to download a 30-day evaluation of ReSharper, obtain a free evaluation license and increase you productivity with C# and VB.NET projects.

Develop with pleasure!