Posts Tagged ‘plugins’

Creating plugins for dotPeek

Wednesday, May 15th, 2013

In a previous post, we’ve seen that dotPeek supports creating and loading plugins. The NuGet plugin for dotPeek is a good example to demonstrate how to get started creating plugins for dotPeek. Sources for this plugin are available on GitHub. But let’s create a plugin of our own!

Before we start: dotPeek does not have a formal SDK yet. However it shares a lot of commonalities with ReSharper. In fact: dotPeek is built on the same platform as ReSharper reusing the project model, PSI, navigation and so on. Which is good news: we can use the ReSharper SDK (see the downloads page) to create plugins for dotPeek. Another option is to start from a class library project and work with a small NuGet package I’ve created to help you get started.

Creating a new plugin

To create a plugin for dotPeek, we can make use of the instructions provided with the ReSharper SDK. This involves a lot of project modifications so we’ll take the easy way out: we can create a dotPeek plugin by installing a NuGet package.

Install-Package JetBrains.DotPeek.PluginDevelopment

In Visual Studio, we can start out with a new Class Library project, making use of .NET 3.5 or up. Next, we can install the JetBrains.DotPeek.PluginDevelopment NuGet package into the project. This NuGet package will convert the class library we have into a dotPeek plugin by adding assembly references and several attributes. Note that the NuGet package will target the latest version of dotPeek that is installed on your system (which also means we have to have a copy of dotPeek installed).

That’s everything we have to do: by running our project, dotPeek will launch with our fresh plugin loaded:

New plugin for dotPeek

Now let’s see where those menu items are coming from…

Menus, toolbars and handlers

Menu items, like the About menu we saw when loading our plugin in dotPeek, are triggered using handlers. The AboutActionHandler.cs file in our project is a sample handler implementation.

About action handler

There are some things to note here:

  • The ActionHandler attribute denotes the fact that this class is a handler with a specific name, “MyFirstDotPeekPlugin.AboutAction” in this case.
  • Handlers are added to menus and toolbars in the Actions.xml file, referencing the action name. More information on actions.xml can be found in the ReSharper plugin documentation. To make working with Actions.xml easier, the NuGet package also added an Actions.xsd containing the full XML schema we can use.
  • Handlers implement two methods of the IActionHandler interface:

    • Update – specifying whether the action is enabled or disabled.
    • Execute – the code which is executed once an action is being invoked.

    The following handler will be always available and can open a new command dialog when invoked:

    Command line tool window in dotPeek

    We can add it to a menu or toolbar by updating the actions.xml file:

    Actions.xml for plugins

    Distributing a plugin

    There comes a time when we want to make our plugin available to the public. Distributing a plugin is a simple process:

    • Distribute the assembly compiled from your project
    • Users can copy this assembly into %LOCALAPPDATA%\JetBrains\dotPeek\v<your target dotPeek version>\plugins

    Another option is to generate a simple installation batch file, check my NuPeek plugin’s GitHub repository for more information.

    Further reading

    In this blog post, we’ve only scratched the top of the surface. With plugins, a lot of things are possible: we can add menu items, toolbar buttons, tool windows, options panes and so on. In fact, many of the features shipped with dotPeek are in fact built as plugins. It is advised to consult the ReSharper Plugin Development Guide for additional information on developing dotPeek plugins.

    AngularJS support for ReSharper

    Thursday, February 28th, 2013

    In case you haven’t already been introduced, AngularJS is a popular JavaScript framework for creating dynamic web applications. It provides many of the services required to build such applications, not the least of which is a declarative approach to updating the UI. It favours the use of data binding and templates over direct DOM manipulation, and it makes it possible to create complex sites with a minimum of code. For more information, check out the examples on their home page, or take a look at the video tutorials by our very own John Lindquist.

    We’ve just released a plugin that adds ReSharper support for some of AngularJS’ features (here’s a direct download link). It’s an initial version, so doesn’t cover everything, but what it provides should give you a helping hand in creating your sites. Currently, the plugin provides code-completion for Angular’s custom HTML attributes, and a bundle of Live Templates to make building common constructs easier.

    Code completion will include all of AngularJS’ “ng-” attributes when editing HTML files, and include a description tooltip:

    Code completion showing Angular attributes

    It also supports the HTML5 “data-” prefixed versions of the same attributes.

    Code completion with data prefixed attributes

    And of course, since ReSharper has smart matching, you can type initials to quickly get to the start of the attribute you want. For example, you can type “dngbh” to get to the “data-ng-bind-html” attribute:

    Code completion with smart matching

    The plugin also ships with 26 Live Templates, based on the IntelliJ and WebStorm templates by Pawel Kozlowski and John Lindquist, respectively. They are split into functionality for directives, modules, scope, routing, html and global helpers. For example, you can use the “ngindex” template to create a simple HTML page to start your development,  or “ngb” to create a binding expression. These work in HTML or HTML-like files (Razor, ASPX, .html)

    Expanding the binding template in a HTML file

    The JavaScript templates can create code for directives, for loops, modules, routing and scope. These are available in JavaScript files, and within script tags in HTML-like files:

    Expanding a scope function template

    Please check out the templates explorer to get a full list, or to edit, add or remove templates.

    This is just an initial release. We’d love to expand the feature set, supporting custom HTML element directives, navigation to model properties, binding expressions, and more. If there are any features you’d like to see, or if you find any bugs, please add a feature request to the Issues page. And of course, it’s Open Source - if you’d like to see a new feature, how about taking a crack at it? We’ll help.

    Now, go and download it, and make lovely dynamic JavaScript applications.

    ReSharper SDK Adventures Part 9 — Update notifications

    Wednesday, January 30th, 2013

    Welcome to another part of the ReSharper SDK Adventures! One of the problems that many plugin developers face is in being able to update their plugins after they are released, so in this post we’ll take a look at how you can do that with simple update notifications.

    Update Notifications

    Update Notifications are already used by at least two ReSharper plugins – the NuGet plugin and ForTea.

    The user gets informed about plugin updates in two ways. First, there is the Updates tab in ReSharper Options that shows a listing of all the plugins that have pending updates:

    And then there’s a periodic check that ReSharper does. If a plugin has been updated, it will pop up a dialog box to let you know:

    At the time of writing, the notification mechanisms are different, so we’re going to consider Nuget’s implementation here. Essentially, the mechanism for update notification is as follows:

    • Once every 24 hours, a special XSLT file is downloaded from a location of the plugin developer’s choosing.

    • This XSLT file is applied to certain data taken from the environment in order to determine if anything has changed.

    • If something has in fact changed, an update location is acquired and a corresponding update dialog is displayed.

    Please note: update notifications are not the same as automatic updates. Even though the user is informed about the new version being available, it is their responsibility to download and install the updated plugin – you are simply providing the download link.

    Let’s go through each of the files in turn and discuss what’s going on. I’m going to keep the links to the NuGet project here so that you can quickly see the whole file if you need to.

    UpdateNotifier.cs

    The update notification shell component (source) is the component responsible for providing the data from the updates. All of its operations happen in the constructor. At least two things need to be injected into the constructor — the Lifetime of whoever instantiated the component, and an UpdatesManager, which is the ReSharper component responsible for handling updates.

    Inside the constructor, we first create a URI where our magic XSLT file is stored. We’ll discuss the contents of the XSLT file soon, but for now it’s just important to remember that this XSLT is appled to (an XML representation of) a set of variables to determine whether a change is required:

    The above file must obviously be accessible on the web. Note the use of raw.github.com above – the path might be useful if you’re also hosting a project on GitHub.

    Now that we have the URI, we ask the UpdatesManager that we injected to give us a category that’s related to our plugin:

    With the category acquired, we can now proceed to customize the local environment settings for the duration of the lifetime of our component (which is equivalent to the lifetime of the shell). Specifically, what we want to do is customize the local environment information that the XSLT is applied to:

    Let’s discuss the above code. Two things are happening:

    • First, we check that the type of argument that we are customizing is indeed of type UpdateLocalEnvironmentInfoVs.

    • Second, if it is, we overwrite it with our own definition, which incorporates both the original environment and information about our plugin.

    The class PluginLocalEnvironmentInfo from above is also of our own making, and is simply an aggregation of environment info and our plugin info. The class is decorated with appropriate metadata so as to allow subsequent serialization and application of the XSLT file:

    We store the plugin version in a special structure called VersionSubInfo, and it’s acquired in our case via the GetThisVersion() call which simply takes the version of our plugin assembly:

    Finally, the constructor is finished off with the following call:

    This requires a bit of an explanation. ReSharper typically downloads and evaluates the XSLT on a regular basis, but doesn’t re-evaluate it after an install. As a result, if there is a reminder out there to download this or older version of the plugin, we remove it:

    And that’s it for the update notification component!

    Updates.xslt

    The second piece of the puzzle is the update XSLT file. Behind the scenes, the data that we provide ReSharper via PluginLocalEnvironmentInfo gets serialized into XML, and then this XSLT is applied to it. If the latest plugin version number has changed, the XSLT provides ReSharper with new data regarding where the updated version lives, who makes it, how much it costs, and so on.

    Rather than show the whole thing, let’s discuss all the important bits. First of all, the XSLT contains version numbers for the latest version that’s available currently. You update this number when you release a new version of your plugin.

    The XSLT is solely responsible for telling ReSharper that an update is needed. To determine this, it queries the current plugin versions:

    It then does a simple if check to see if something has changed and, if it has, it needs to provide ReSharper with a new <UpdateInfo> structure that contains all the relevant information about the new version.

    I won’t list the contents of the <UpdateInfo> structure here — if you’re interested, please take a look at the updates.xslt file of the NuGet plugin. The only thing I want to point out is that the icon specified in the <IconData> element is simply a base64 representation of a PNG file. Keep in mind that UpdateInfo is, in its original form, a .NET class located in the JetBrains.UI.Updates namespace — you can use this class to figure out which XML elements can be provided, and what they are used for (the class has extensive documentation).

    Hint: to find out more about what the update manager is doing behind the scenes, you can peek at the %LOCALAPPDATA%\JetBrains\ReSharper\v7.1\UpdatesManager.xml file. This file contains information about all the plugins that ReSharper tries to update, and ReSharper itself, of course!

    Conclusion

    Implementing update notifications for ReSharper plugins is not that difficult — simply take the existing files, tweak them a little and you’ve got a mechanism for automatically letting your users know that an update is available. So go ahead, implement this in your plugin right now — your users will appreciate it! ■

    CatelR# - a niche plugin for the Catel framework

    Monday, January 28th, 2013

    Most ReSharper plugins provide general-purpose services – spell checking, style enforcement, unit testing, code generation or context actions for XAML, string manipulation or code quality. The focus is wide, either concentrating on multiple file types or multiple analyses.

    The CatelR# ReSharper plugin takes a different approach, and has a very narrow focus. It provides context actions and analyses specifically for users of the Catel framework.

    Catel is a framework with a focus on MVVM based applications. It provides multiple services to the application developer, including an IoC container, validation, message mediation and argument validation. It also provides MVVM services, such as view model support, commands and behaviours. Check out the extensive documentation for more details of the framework itself.

    The plugin’s aim is to streamline development with the framework, trying to make it as easy as possible to get the most out it. For example, when creating a ViewModel, Model or data object class, CatelR# offers a context action on the class declaration to make it derive from Catel’s ViewModelBase, ModelBase or DataObjectBase classes, automatically inserting the correct using statements.

    Context action to derive from Catel base objects

    And these options only show up once you’ve added assembly or NuGet references to Catel.Core and Catel.MVVM.

    Similarly, it offers context actions to convert a normal auto-property into a Catel property, similar to XAML’s DependencyProperty, which can be used for data binding. Optionally, you can also have it create a method to be used when the value changes.

    Context action to convert auto-property to Catel property

    Resulting in generated code that looks like this:

    Example of generated Catel property

    The generated NameProperty field also has a context action to include or exclude it from serialisation, which alters the parameters to the RegisterProperty method, and another that will convert it back into an auto-property.

    And this is made even easier using the Generate Code menu, which allows converting multiple properties at once.

    Generate multiple Catel properties at once

    A similar code generation workflow is provided that makes it very easy to map between a model and a view model. The view model creates a property that holds the model instance. As long as this property is marked with the ModelAttribute, CatelR# now knows the type of the model, and can generate matching properties in the view model, saving a lot of work. See this blog post for more details.

    The other main feature offered by the plugin is to add argument checking, using the framework’s own methods. This adds context actions to method parameters. For strings, you get to check for null/empty or null/empty/whitespace.

    Add argument check for parameter

    For objects you can assert that it is a specific type or implements a specific interface, and for integers, you get a choice for minimum, maximum or within range. When you select one of these options, CatelR# uses ReSharper’s LiveTemplate hotspots to allow for editing the values, which ReSharper automatically copies to the xml documentation that CatelR# also creates.

    Argument check with hotspot editing

    This plugin provides some very useful features for the users of the Catel framework. The focus is refreshingly narrow and very much aimed at reducing friction for Catel users – quickly implementing the patterns and code necessary to use the framework, allowing the user to concentrate on adding the business value. This is a fantastic approach for a ReSharper plugin, and one that could be used to great effect by other library developers.

    Catel and CatelR# are both open source projects, hosted on CodePlex. The Catel framework can be installed via NuGet, and the ReSharper plugin is available on the CodePlex download page.

    Agent Mulder - supporting IoC in ReSharper

    Thursday, January 24th, 2013

    The almost pervasive use of IoC containers in modern-day enterprise apps presents a special challenge to ReSharper. After all, how can ReSharper possibly know that a type, which for all intents and purposes appears to be unused, is actually configured to be instantiated implicitly by using a dependency injection mechanism?

    Some might say that this is impossible, since the wide variety of IoC containers coupled with various distinct initialization options make the detection of component initialization a real challenge. This challenge was met, however, by Igal Tabachnik (@hmemcpy), the creator of the Agent Mulder plugin.

    At the time of writing, Agent Mulder supports the following containers:

    • Castle Windsor

    • NInject

    • Unity

    • Autofac

    • StructureMap

    • Catel IoC

    Depending on the container in question, Agent Mulder supports two types of component registration:

    • Manual registration involves registering a single component type in the container. This is typically done by providing the component’s type, so for example with Unity one might invoke RegisterType<Foo>() or RegisterType(typeof(Foo),...) to add the component to the container.

    • Convention-based registration allows bulk registration of components in the container via a particular method. For example, Autofac’s InNamespaceOf<T>() method allows the user to register all types that can be found inside the namespace inhabited by type T.

    While it is technically infeasible for Agent Mulder to support every variety of configuration in every container, it does manage to cover a very large percentage of configuration options in the aforementioned containers, as documented in its Wiki pages. But, apart from analyzing container registrations, what does the plugin actually do?

    Ultimately, Agent Mulder does three things:

    • The main goal of Agent Mulder is to suppress unused ispections when a container-registered component does not appear to be instantiated.

    • In addition, Mulder also uses a gutter mark to indicate a container-registered component. One can click this gutter mark to navigate to the exact line where this component is registered:

    • Finally, one can also navigate to registered component right from the statement that performs the registration:

    Mulder is an open-source plugin hosted on GitHub. It appears to have an active user base, so if you are interested in, say, a container it doesn’t support, feel free to open a request or implement it yourself and send a pull request. Meanwhile, have fun with IoC and stay tuned for more plugin reviews!

    ReSharper plugins for unit testing - MSpec, xUnit.net and Silverlight

    Monday, January 21st, 2013

    ReSharper provides comprehensive support for running and debugging unit tests. Out of the box, it works with NUnit and Microsoft’s Visual Studio Unit Testing Framework (henceforth mstest for brevity) for .Net languages, and supports QUnit and Jasmine for JavaScript.

    The same APIs that ReSharper uses to implement this support are fully available to third parties, and there are currently plugins to expand this support to include Machine.Specifications (MSpec), xUnit.net and support for Silverlight projects. More can be added at any time, through the use of the SDK.

    The MSpec project is a “Context/Specification” testing framework, which is a form of BDD tool, focussed more on driving correct behaviour than on testing functionality – building the right thing, rather than building the thing right. It’s a significant change of style to anyone used to the NUnit/mstest style of attributed methods, but it’s not too difficult to follow – test methods are replaced with fields that take lambdas that arrange, act and assert. It’s worth checking out the example projects in the source repository – BankingSpecs is a good place to start.

    Machine.Specifications ships as a NuGet package, which also includes the ReSharper runner. Simply run the InstallReSharperRunner batch file in your packages\Machine.Specifications\tools folder (it includes support for ReSharper 6 and 7). Once installed, ReSharper now recognises MSpec tests in your source code, adding the unit test icons to the gutter in the editor:

    mspec test recognised in the editor

    One of MSpec’s nice features it that the names of the test and the information from the SubjectAttribute are used to generate a natural language description, which, when used with the different grouping options in the test runner can give very readable test results:

    mspec results with natural language descriptions grouped by category

    The xUnit.net framework is a more traditional unit testing framework, similar to NUnit and mstest, but arguably more idiomatic .Net. For example, it still uses attributes to mark methods as tests, but uses constructors and IDisposable instead of SetUp and TearDown attributes. Support is added by the xunitcontrib plugin, giving ReSharper the ability to locate and run xUnit.net tests. Like NUnit and mstest, it can handle parameterised row tests, dynamically adding rows into the results as the tests are run.

    xUnit.net parameterised tests, using random data

    It also works with the “Show Unit Test Usages” option in the filter drop down of the Find Results window. When viewing the results of a find usage search, any usage in a test method or test class is marked with a test icon, rather than an icon representing a method, class or property. Unchecking the “Show Unit Test Usages” option in the “Filter Usages” drop down will hide the test usages in the results, allowing you to focus on the usages in the production codebase.

    Filtering xUnit.net test usages out of Find Usages results

    Unit test providers don’t need to be source based. Most of them are, and display the test icon in the editor gutter, but they also examine the metadata of the compiled assembly, and can potentially find more tests here. Using this technique, it’s possible to run tests created in a source file that ReSharper doesn’t support. For example, we can create an xUnit.net test in F#, and while it’s not detected in the editor, it is still found and run when the assembly is compiled.

    xUnit.net test in F#

    Since the test hasn’t come from source code, you can’t double click the test in the test results to navigate to it. But a failing test will display a clickable stack trace that will navigate to the failure.

    F# test results showing clickable call stack

    This technique can be used to run F# tests using other F# test frameworks, as long as they are based on a unit test framework that ReSharper supports (and this technique can also be used to write a plugin that supports a framework that isn’t based on one of these frameworks).

    Silverlight support is provided by AgUnit, which enables running and debugging your unit tests in Silverlight projects, and of course handles the Silverlight test framework’s AsynchronousAttribute.

    AgUnit debugging an asynchronous Silverlight test

    Perhaps surprisingly, a couple of our own products are also plugins for ReSharper’s unit test runner – dotTrace and dotCover. Although the products register themselves with ReSharper somewhat differently to normal plugins, these products use the same open APIs that the third party plugins use, albeit for a slightly different purpose. Instead of examining source code and metadata to find and run tests, they provide the environment in which tests are run; dotTrace collects profiling information, and dotCover collects coverage information. Both products extend the UI to provide means of running the tests, but dotCover also adds an output pane to the test runner to display the coverage information (and highlights covered and uncovered code in the editor), and of course, this works with third party test providers.

    Unit test runner showing dotCover custom code coverage results pane

    And, just to bring the extensibility full circle, dotCover includes ReSharper’s unit test runner, which is used if ReSharper isn’t installed. Again, NUnit and mstest support is provided out of the box, and there are separate dotCover plugins for xUnit.net and MSpec support (the dotCover MSpec runner is also distributed in the NuGet package, just use the InstallDotCoverRunner batch file in the tools folder).

    ReSharper provides comprehensive unit testing support, in an environment that is very flexible. There is a lot of great support, provided in the box, and just a download away. And it’s all open and extensible – if you don’t see something you want, grab the SDK and get coding!

    R2P: A General-Purpose ReSharper Plugin

    Wednesday, January 16th, 2013

    R2P (short for ‘Refactoring to Patterns’) is a plugin that embodies a collection of features of a fairly experimental nature. It does not have a single theme but, rather, tries to do different things in different areas of ReSharper. Let’s take a look at some of the things it does.

    String Mutations

    One of the key features of R2P is the ability to transform string literals. For example, the string splicing feature brings PHP-style string splicing to C#. Simply use the curly braces to delimit variables and R2P will offer a suitable context action:

    Applying the action replaces the string with a string.Format() call, with the variables moved to the argument list:

    R2P supports several transformations from strings to .NET types. For example, you can define time as a string and convert it to DateTime:

    After invocation, the declaration is replaced with the following:

    R2P supports transformations from string literals into the following types:

    • DateTime

    • TimeSpan

    • XElement

    R2P also comes with a menu item called Paste Verbatim String that pastes strings from the clipboard with correct escapement. This facilitates transformations from strings into something else: for example, you can copy a block of XML from some app, paste it, then use the Convert to XElement context action to turn it into a fully object-oriented declaration.

    In addition to the above, the plugin also supports a few string manipulations, such as:

    • HTML-encoding/decoding of a string.

    • String obfuscation using base64 encoding.

    Code Generation

    The plugin comes with several generators, which all embed themselves into the Generate menu:

    • Binary read/write members — for a given class, generates ReadFrom() and WriteTo() methods that use BinaryReader and BinaryWriter respectively and serialize chosen fields. Special care is taken when serializing known .NET types: for example, for a DateTime, only its Ticks property is serialized:

    • Copy constructor — for a given class creates a constructor that takes this class as a parameter and performs a copy of its properties/fields to the owner class.

    • Disposing members — in addition to being able to correctly identify all disposable fields and generate the appropriate Dispose() declaration, R2P’s implementation also offers to implement the full Dispose pattern.

    • Read-only interface — for a given class Foo, generates an interface IFoo where all properties are exposed as get-only, effectively creating a read-only interface contract for this class.

    Code Inspections

    R2P comes with several computation-related inspections, such as:

    • Inspections that detect inefficient Math.Pow() calls and refactor them to unline multiplication:

    • An inspection and corresponding context action that allows factoring out of common subexpressions:

    • Inspections and fixes relating to possible use of MAD (multiply-add) instruction when using GPU.NET:

    In addition, R2P can help correct misspelt identifiers based on information about the available types:

    Odds and Ends

    R2P comes with a lot more functionality than we can list here. Some of its features include:

    • Refactorings such as Make Singleton (implements the Singleton pattern) and Enum to Class (turns an enumeration into a class with enum cases transformed to member variables).

    • Unit testing helpers such as being able to Assert on all public properties of an object instance, an ability to add a value as a Row in data-driven testing, and a Visual row editor.

    • General-purpose context actions such as code contract generators (generate code contract specifications for parameters), an action to make a method fluent (i.e., return this), and even a context action to treat the ^ operator as a power function.

    • A String format helper window that lets the user build a format string and preview the end result.

    • … and a lot more

    R2P is distributed under a commercial license. For more information, head over to its product site and stay tuned for more plugin reviews!

    ReSpeller: A Spell-Checking Plugin for ReSharper

    Monday, January 14th, 2013

    Those of you who have worked with IntelliJ IDEA and related products know that all those IDEs have incorporated a built-in spell checker for a very long time. With ReSharper, the situation is slightly different in that we have several spell checking plugins that provide similar functionality.

    This post is an overview of a new commercial version of ReSpeller, a plugin, also available in a free edition, which provides spell checking capabilities for ReSharper.

    How It Works

    ReSpeller’s operation is simple: whenever it sees a spelling mistake in an identifier, comment or string literal, it immediately flags it and offers several options for fixing the problem:

    The first option is Replace with… and if you choose it, you’ll get a handy popup over the offending text with some suggestions for fixing it:

    The second option is to Add word to user dictionary, in which case the user can pick the dictionary to save add the word to:

    Finally, there’s an option to Add custom word to user dictionary, in which case the user can edit the word before it gets added:

    Spell Checking Scope

    ReSpeller covers a wide array of code constructs and languages. The elements it checks spelling on are best illustrated via ReSpeller’s Inspection Severity settings page:

    From the list of tags next to the inspection types, you can surmise that ReSpeller supports a very wide array of technologies, including:

    • Programming languages: C#, VB.NET, JavaScript

    • Markup languages: HTML, XML, XAML, RESX

    • Mixed-language files: CSHTML (Razor), ASPX, ASHX

    The spell checker itself doesn’t support just English, but other languages, too. Add a new language and you get spelling corrections from all dictionaries installed:

    Integration Features

    In addition to the above, when you fix a typo in an identifier, ReSpeller automatically fires off a Rename refactoring, making sure that your spelling correction doesn’t result in loss of consistency:

    Note that ReSpeller also highlights spelling errors right in the Rename dialog.

    Typo inspections are also available in aggregate form, so if you open up ReSharper | Inspect | Code Issues in Project/Solution you’ll be able to see them alongside other inspections:

    Conclusion

    There’s a lot of cases where spell checking is critical. For example, as a blogger, I really hate spelling mistakes creeping into my code, because it means I didn’t check what I wrote properly before I posted. Similarly, having a public API with spelling mistakes can be a bit embarrassing, especially if people start using it and you cannot change it afterwards.

    ReSpeller is a plugin that can prevent these kinds of issues. It’s available in two editions: a free edition and a Pro edition with an expanded set of features (such as support for JavaScript, HTML, mixed-language files and different languages). If you’re interested, head over to Ethereal Code for more details. And stay tuned for more plugin overviews!

    Introducing ForTea - a T4 templating plugin for ReSharper

    Friday, January 11th, 2013

    T4 files have sometimes suffered from a lack of love. It’s brilliant that Visual Studio provides an ASP.NET-like template language in the box with Visual Studio, but there is not much support – for example, there is no syntax colouring in Visual Studio, and ReSharper knows nothing about the contents of the file. We have an item on our issue tracker to include support, but I’m very pleased to announce that one of our users has beaten us to it and created a very impressive plugin to do just that – the first plugin we have that provides support for a new file type.

    The ForTea plugin by Julien Lebosquain (who also created the GammaXaml plugin) was released as version 1.0 just before Christmas. You can find it on GitHub – which means it’s Open Source, if you’re interested in contributing – and from the readme on the home page, here is a direct link to an msi download.

    So what does it give you? Well, obviously it provides syntax highlighting for .tt and .ttinclude files, but that’s to be expected.

    Where this plugin really shines is that it integrates with ReSharper’s PSI (Program Structure Interface). In other words, once the plugin is installed, ReSharper gets access to the abstract syntax tree of the file, and uses this to provide familiar code completion, analyses and refactorings.

    Intellisense displayed in T4 template

    As you can see from the screenshot, it supports code completion for T4 directives, and even in this little snippet from a brand new file, is greying out namespaces that aren’t used. And as expected, Alt+Enter on the unused import statements invokes the standard ReSharper context action to remove unused directives.

    Remove unused directives context action in T4 file

    The plugin also recognises C# code blocks, and provides the expected analysis and code completion – notice the light bulb context action icon, the greyed out unused variable name, and the code completion drop-down.

    Intellisense and analyses in T4 file

    It can understand multiple code blocks – this example provides code completion in one code block for a method defined in a separate code block at the end of the file, and also marks the duration variable defined in the first code block as in use. It even suggests that the public method can be made private, and provides a hint that the FormatTimeSpan method could be static.

    Multiple code block support in T4 file

    Of course, renaming works, too:

    Renaming variable across T4 code block

    As does Find Usages, in files:

    Find usages in single T4 file

    And across the solution, even providing syntax highlighted previews:

    Find usages results including T4 file

    One of the nicest features is importing references. ReSharper handles this for C# files – if a type isn’t found, it can suggest to import a namespace or add an assembly reference to the project. But T4 files don’t use the project’s references. Instead, they use namespaces and assemblies declared at the top of the file. Once the ForTea plugin is installed, ReSharper will suggest to add namespaces and references for missing types, but will correctly add them to the file.

    Importing references and namespaces into T4 file

    As impressive as it is for a 1.0 release, there are a couple of limitations. It should hopefully be obvious that there will be conflicts with other Visual Studio extensions that provide T4 support, so any similar extensions will need to be uninstalled. There are also a few things not yet supported. For example, it’s C# only, and there’s no support for outlining (this is a feature of the Visual Studio editor, and not handled by ReSharper). There is no code formatter yet, so ReSharper won’t help with indenting and code cleanup. See Julien’s notes for more details.

    This is a fantastic effort from a member of the ReSharper community, and has produced a very impressive plugin. Please, download it (direct link), use it, and give Julien some feedback. And, of course, it’s open source, hosted on GitHub, so if you’d like to see new features, or find any issues, report them, or grab a copy of the source and submit some pull requests!

    ReSharper SDK Adventures Part 8 — Expression factoring improved

    Tuesday, December 18th, 2012

    In the previous part of the SDK Adventures, we started work on a factoring context action for mathematical expressions. We did quite a bit of work to get the factoring algorithm off the ground, but there’s yet more to be done – for example, we need to take care of addition/subtraction and division/multiplication.

    But first, we’re going to take a look at testing our plugin.

    Testing the Action

    With respect to the context action that we’ve been working on, there are two types of test:

    • Availability tests ensure that the action is available where it should be (and, conversely, not available where it shouldn’t).

    • Execution tests ensure that after firing, the context action brings the affected code to its expected state.

    In ReSharper’s ecosystem, these tests are data-driven: they all depend on separate ‘before’ and ‘after’ files to be located in specific directories. The tests themselves are typically very predictable in terms of content – all they do is describe the action under test. For example, the execution test for our FactorCA context action is likely to look as follows:

    The above test communicates an expectation that files named execution01.cs and execution01.cs.gold can be found in the test\data\Intentions\ContextActions\FactorCA folder. This folder is expected to be just above the solution folder, so if the plugin solution is itself in \src, then \data and \src are expected to be in the same folder. Note that the ‘convention over configuration’ approach is pervasive here: ReSharper expected a context action to be in Intentions\ContextActions. You can, of course, customize these locations if you need to.

    So let’s look at a simple test: one where we change the expression a*x + a to a*(x+1). We make the original execution01.cs file with a typical (valid) class declaration having a method, something like

    In the above, {caret} refers to the position of the caret in the file when the action is executed. Our expected result, with the method body omitted, is thus:

    Oops! Running the test we see it fail, and if we peek into the .tmp file in the folder where the test data is stored we see that the generated expression is, in fact, return a*(x +){caret}; – not even valid code. We need to fix something!

    Specifically, we need to handle the situation where our histogram of terms doesn’t have a single term to add, in which case we put a 1 in there:

    We run the test again, and this time it passes. Great!

    Handling Subtraction

    As you may remember, we previously noted that IAdditiveExpression represents both addition and subtraction and that we don’t handle subtraction just yet. Writing a test that fails is very easy:

    We first run the test to watch it fail miserably, and then fix the problem. The problem is that when we flatten the initial list of additive expressions, we lose track of whether the expression has a + or - sign. To fix this, we introduce the simplest structure possible to retain this information:

    Now all usages of IAdditiveExpression get replaced with CSharpExpressionWithSign. In fact, we can no longer afford to have a generic Flatten<T>() method – we need to specialize it:

    In the above, IsSubtraction() is a simple check on the token that’s being examined, i.e.:

    Finally, our algorithm for outputting the code needs to be changed to handle negative signs, including negative signs of the very first expression:

    And this change is enough to make our latest test pass.

    Division

    Multiplying by x can be treated the same as dividing by 1/x. However, unlike multiplication you cannot ‘factor out’ division at the beginning of the expression. For example, a/x + b/x is not equal to x/(a+b) but is rather equal to 1/x*(a+b). However, if we do this fully, we also get into the thorny business of reconciling expressions such as x*x / a * x, which adds an extra layer of complexity and moves us even closer to writing what is effectively a computer algebra system.

    For now, rather than significantly increase the complexity, we can simply remove division from our list of candidate variables to factor out. To do that, we check if it’s a multiplication or division in a way similar to IsSubtraction:

    Putting this restriction into the appropriate flattening method we ensure that divisions don’t get included in our term histogram.

    Conclusion

    We’re slowly taking our plugin into a territory where it’s becoming something of a CAS rather than just an aide to ordinary programming. Beyond a certain point, CAS systems make a lot more sense, so in the next part of SDK adventures, we’ll take a look at an entirely different area that we can enhance.

    Meanwhile, check out the source code and stay tuned for Part 9! ■