Rory Becker - DevExpress CodeRush Blog
  • New CodeRush Plugin - CR_ReverseArgs

    Hurrah, another new CodeRush plugin.

    The problem minor annoyance

    Occasionally I realise that I’ve passed a couple of arguments to a method in the wrong order.

    What follows is usually a complicated series of…

    • Move Left (Ctrl+Left)
    • Select Right (Shift+Ctrl+Right)
    • Cut Argument (Ctrl+X)
    • Move Right (Ctrl+Right)
    • Paste Argument (Ctrl+V)

    The navigation operations usually need to be repeated several times in order to get into the correct position.

    Additionally there’s that bit where you either…

    • Try to judge which comma to include in the cut/paste operation.
    • Or… Delete the comma, and enter it back again once the paste is complete.

    Add this to the fact that I usually have something useful on the clipboard, which I’d prefer not to have to burn whilst correcting the order of these arguments.

    The whole rigmarole is something to be avoided.

    Enter CR_ReverseArgs

    The new CR_ReverseArgs plugin allows you to just highlight the pair of arguments, and trigger Reverse Args from the CodeRush Smart Tag menu.

    Then CodeRush will do the rest.

    CR_ReverseArgs

    This CodeProvider should work with ints, strings, and all sorts of other objects. The 2 arguments need not be of the same type either. Feel free to switch whichever pairs you like.

    Note: This plugin is NOT a Refactoring. It will affect the functionality of your code.
    If you wish to move both the Arguments and their corresponding Parameters, then you should use the Reorder Parameters refactoring

    Availability

    This plugin is available immediately:

     

  • New CodeRush Plugin - Declare Extension Method

    Another new CodeRush plugin!

    This time one to help declare extension methods on existing objects.

    Introducing Declare Extension Method

    This plugin is really simple.

    Consider the following code with a call to an undeclared method MyNewMethod.

    DeclareExtensionMethodStart

    Place your caret on the call to MyNewMethod and hit your CodeRush Refactor key (Defaults to Ctrl+`)

    DeclareExtensionMethodMenu

    Choose ‘Declare Extension Method’ from the menu.

    DeclareExtensionMethodNewStaticClass

    CodeRush generates a new static class in the same namespace as your calling code, containing the stub of your new extension method.

    The previous syntax error will have disappeared and all that’s left to do, is for you to fill in the implementation of your new method Smile

    Where do I get this Awesome Plugin from ?

    Declare Extension Method is available from

    GitHub: Here you will find the current (and historical) source of the plugin as well as the latest installable version.

    The Visual Studio Gallery: Installing from the Visual Studio Gallery allows VS to locate any updates that are shipped after the initial release.

  • New CodeRush Plugin – Use Extension Method

    Another plugin requested by our community

    To paraphrase:

    It would be great to have something that could recognise that an extension method was being called in the style of a normal method ie Method(Object, Params) and rewrite the call in the form of an extension method call. ie Object.Method(Params)

    Ok well that seems simple enough:

    Introducing the Use Extension Method Plugin

    So given that we have an extension method like this:

    UseExtensionMethodRequest1

    … and some calling code looks like this :

    UseExtensionMethodRequest2

    The Use Extension Method plugin will add an option to your CodeRush SmartTag menu which will convert the method call in question to the following.

    UseExtensionMethodRequest3

    So where can I get this plugin?

    As usual this plugin is available in 2 locations

    GitHub: Here you will find the current (and historical) source of the plugin as well as the latest installable version.

    The Visual Studio Gallery: Installing from the Visual Studio Gallery allows VS to locate any updates that are shipped after the initial release.

  • New CodeRush Plugin – Convert String to AppSetting

    A customer recently tweeted:

    Any chance of a CodeRush plugin to convert a literal to a config (app.config) setting? pretty please

    Well when the request is so polite, it’s hard to say no Smile

    The Convert String to AppSetting plugin adds a new Refactoring to your standard arsenal.

    Simply…

    • Place your caret on the string in question.

      ConvertStringToAppSettingBefore
    • Hit your CodeRush \ Refactor key ( Defaults to Ctrl+` )
    • Choose Convert String to AppSetting from the list of refactorings.

      ConvertStringToAppSettingMenu

    CodeRush will…

    • Create a new App.config file if one doesn’t already exist.
    • Add a new setting deriving it’s name from the text of your initial string.

      ConvertStringToAppSettingAppConfig
    • Replace the original string with a call to ConfigurationManager.AppSettings

      ConvertStringToAppSettingAfter
    • Link the key-text of your new setting with that of the call, so that you can easily rename them as one.

    So where can I get this wonderful plugin?

    This plugin is available in 2 locations

    GitHub: From here you can get the current (and historical) source of the plugin as well as the latest installable version.

    The Visual Studio Gallery: Installing from the Visual Studio Gallery provides the added bonus of VS being on the lookout for any updates that are shipped on your behalf.

  • New CodeRush Plugin Template – NewContext

    What is context?

    The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood.

    What does CodeRush use context for?

    CodeRush uses context (in addition to user input) to decide which functionality to provide you with.

    For example: The <Tab> key is used for indenting text, and also for invoking the Tab to Next Reference (TtNR) feature. When you hit the <Tab> key, CodeRush performs several context checks.

    The context settings for TtNR are fairly complicated, but boils down to IsTheCaretWithinAnIdentifier. If CodeRush judges that this is the case, then it chooses the TtNR functionality, otherwise it chooses the indentation functionality.

    CodeRush Templates and Shortcuts often overload each other in this way, and CodeRush uses the context to determine which overload to use.

    How do I use a context?

    You don’t use a context directly. Instead you choose a feature which is sensitive to context (a shortcut or template will do nicely) and configure it to only work within a given context (or set of contexts)

    Features can be configured to work with a specific context where ever you see this UI.

    ContextPicker

    Each node in the tree is a context. The contexts will either be true or false at a given moment.

    When being tested, a ticked context will be tested at the moment of invocation and the feature\function will only be allowed if that context is found to be true. Alternatively if the context has a cross against it, then the function\feature will only be allowed to proceed if the context is explicitly found to be false.

    What if I can’t find the context I need?

    Well first of all I recommend contacting support@devexpress.com since it’s entirely possible that the context you’re after is there, but perhaps not named or located as you would expect. However, failing that, it is very easy to create a brand new context in a plugin.

    How do I create a context?

    Contexts are analogous to functions which return a boolean value. You check anything you like, (Source code, Project structure, color of the moon) and then set the context to true or false accordingly.

    Creating a context is really really simple… just use the NewContext template. Note This template does not ship with CodeRush. See instructions later in this post for how to acquire the template.

    Once you have the template installed, simply position your caret in the body of your plugin and type NewContext<space>

    The Template will expand like so…

    NewContextTemplate

    You will then need to fill out a few details.

    • A Component Name
      This first name is used to identify the metric component itself within your code. You might be about to create several of these and they all need to be distinct from one another and their methods not confused.
    • A Display Name
      The display name is a short identifier used whenever a group of contexts are listed together to distinguish them from each other.
    • A Description
      Explains to the user ticking or crossing the context, what the context is looking for in order to be considered satisfied.
    • A Provider Name
      This is the path at which the context will be listed. A backslash separated set of strings is required here. ie Editor\XML\InOpenTag

    With these properties filled out, all you need to do is…

    • Implement the ContextSatisfied method
      Perform whatever calculations and discovery you like and then set ea.Satisfied = true; when your context is satisfied
    • Call Register
      Call your newly generated Register method from within your InitializePlugin method.

    Where can I get this template?

    As usual this template is available from within the CodeRush Plugin Templates repository on github

    Download and Import this file using these instructions

    Or if you’ve installed the Template Importer, simply point it at this webaddress and click import.

  • Community Callout: New CodeRush Plugin CR_FluentPoco

    Richard O’Neil, author of the FakeItEasy CodeRush Templates has been at it again.

    This time he’s taken a step up, and built a new CodeRush plugin.

    From his github repository:

    CodeRush expansion plugin to turn a list of private fields into fluent methods.

    I created this to help me build helper classes for an automated testing framework I was making with Selenium and it's WebDriver.

    If you start with code like this…
    CR_FluentPocoStartClass
    

    The generated code will enable you make the following call…
    CR_FluentPocoExampleFluentCall

    Naturally Richard has open sourced his creation for all the world to use, so head on over and give him some feedback.

    For more information see the CR_FluentPoco repository on GitHub

  • New CodeRush Plugin – Add Data Contract – How does it work?

    In my last post I presented the Add DataContract plugin.

    In this post I’ll walk you through what makes it tick.

    Overview

    In essence there are 3 parts to this plugin

    • Add the Namespace Reference (Imports\using directive)
    • Add the DataContract attribute to the class.
    • Add the DataMember attribute to each of the classes properties.

    Structure

    The Add Data Contract plugin is a CodeProvider with the usual CheckAvailability and Apply methods. The basic plumbing of this plugin is created with the NewCodeProvider CodeRush template detailed in this blogpost.

    Add Namespace

    In the DXCore, a using directive (or an imports directive in VB.Net) is called a NamespaceReference

    To add a NamespaceReference to the current file it is first necessary to determine if one already exists. For this we construct a new ElementEnumerable capable of searching the current file for NamespaceReference objects. This is then used to return an IEnumerable<NamespaceReference>

    AddDataContractGetNamespaceReferences

    The list of namespace is queried to determine if the new namespace is already referenced. There is nothing to be gained by referencing the same namespace twice. If it is found, then we return from the apply method without having performed any modifications.

    AddDataContractExitIfNamespaceAlreadyPresent

    Location, Location, Location

    Next we determine the best location to insert our NamespaceReference.

    If there are no existing NamespaceReferences, then the InsertionPoint is set to the start of the current document.

    Alternatively, if there are some pre-existing NamespaceReferences, then the start of the last of these is picked as a sensible default.AddDataContractDetermineNamespaceInsertionPoint

    Code Generation and Insertion

    Next we create our new NamespaceReference object (passing in the string representing the namespace in question) and have CodeRush generate the actual code that represents this object. The last step in generating our NamespaceReference is to queue the insertion of this code at the InsertionPoint determined in the previous step

    AddDataContractGenerateCodeAndQueueInsertion

    A Generic AddAttribute Method

    There are 2 attributes which this plugin adds to various parts of the target class.

    The DataContract attribute is to be added to the class itself. Then we need to iterate through the properties on the class, and add the DataMember attribute to each of those.

    In order to make this as easy as possible, I decided to create a utility method capable of quickly adding a named attribute to any given LanguageElement.

    AddDataContractAddAttribute

    In the method above, an ElementBuilder is used to create the Attribute and then the AttributeSection. For those that don’t know the AttributeSection is the pair of square brackets that the attribute sits inside. (These are angle brackets in VB.Net).

    As before, code is then generated and queue an insert into the ActiveTextDocument at the correct location.

    Putting it all Together

    All of this is drawn together in the body of the apply method.

    AddDataContractWrapInSingleStep

    First we add the System.Runtime.Serialization namespace. Next we decorate the class with the DataContract attribute. Then we iterate through all the properties of the class decorating each of these with the DataMember attribute. We call ApplyQueueEdits to apply each of the queued operations to the document in a single step.

    Finally we reparse the document and call the FormatFile action to perform any additional reformatting that might be necessary.

    Full source code is available

    As usual, the full source code for this plugin is available on github for your perusal.

    Feel free to fork (or just plain copy) the code for your own plugins and see what you can do with it.

  • New CodeRush Plugin – Add Data Contract

    A customer recently requested a way to quickly add the [DataContract] and [DataMember] attributes to the active class.

    Naturally we were happy to oblige.

    The Add Data Contract plugin provides a new CodeProvider available when your caret is within the name of any class.

    When invoked, it will add the [DataContract] attribute to the active class, and decorate it’s properties with the [DataMember] attribute.

    AddDataContract

    Naturally we also:

    • Add a reference to System.Runtime.Serialization.dll
    • Add the System.Runtime.Serialization namespace.

    Where do I get this Plugin?

    This plugin is available on GitHub or via the Visual Studio Gallery

  • More CodeRush Plugins added to the Visual Studio Gallery

    For those of you who didn’t already know, several of our CodeRush plugins are already available from the Visual Studio Gallery.

    Plugins added to the Visual Studio Gallery can be installed from within Studio via the Tools\Extensions and Updates menu.

    Additionally Studio will let you know if a new version is released. Assuming you agree, it will download the new version and install it for you as well.

    So we’ve just added another 5 plugins to those already up there making it even easier to pimp your IDE.

    For reference these are the plugins we’ve just added:

    To browse a full list of CodeRush plugins on Visual Studio Gallery just visit Tools\Extensions and Updates in Studio and search the online section for CodeRush

    Alternatively, just follow this link.

  • New CodeRush Plugin Template - NewMetric

    Note: The template referred to by this post does not ship with CodeRush. To install it, see instructions towards the end of the post.CodeRushMetric

    What is a Metric

    A metric is a measurement of some quality of your code. In this case it is a per-method measurement. CodeRush displays the metric for each member, on left of the member in question.

    CodeRush ships with 3 such metrics:

    • Lines of Code
      Exactly what it sounds like. This metric measures the number of lines occupied by the method. This is a pretty basic metric which includes the signature and braces of the method.
    • Cyclomatic Complexity
      A measurement of the number of paths through your code. The higher this value, the more tests will be needed to cover the method’s behaviours correctly.
    • Maintenance Complexity
      This metric weights each element of the method according to how it affects the maintainability of said method. You can read more about this metric here

    You can choose which metric CodeRush displays, by clicking the current value and choosing another metric from the list. CodeRushMetricChoice

    The NewMetric Template

    As you’ll have guessed based on previous posts in this series, the purpose of the NewMetric template is the quickest way to create your own metric?

    Usage

    As with other plugin templates, this one is intended to be expanded (NewMetric<space>) in the body of your plugin class.

    It will produce code that looks like this:

    TemplateNewMetricExpanded

    As with other plugin templates, you’ll have to give your Metric 3 names.

    As a quick reminder, these are:

    • Your own reference.
      The first name is your own reference. The phrase you type here, is used to name the objects and associated methods of your Metric.
    • Internal name
      This value is used internally by CodeRush. It should be unique, since it will be used to add your Metric to an internal dictionary. Later you can use this name to get a reference your Metric from another plugin.
    • Display Name
      This value is used for the text displayed when your provider is added to the drop down list of metrics provided inline.

    Next up, you’ll have to call the registerXXXX method (just generated and named) from within your plugin’s InitializePlugin method.

    Finally you need to implement your plugin’s new metric. This is achieved by adding code to the GetMetricValue handler (also stubbed out by the template).

    Typically you’ll examine the source of your project and perform some sort of calculation based on the LanguageElement passed to you in e.LanguageElement. Then you’ll assign the result of this calculation to e.Value.

    So if you were looking to replicate the lines of code metric, you might use code similar to:

    LinesOfCodeMetric

    ..and that’s it.

    In Summary…

    • Expand NewMetric template
    • Call RegisterXXXX from InitializePlugin
    • Implement your metric (possibly in a single line of code).

    …and you’re done.

    Where do I get this template?

    As usual this template is available from the CodeRush Plugin Templates repository on GitHub

    If you have any suggestions to improve any of the templates in this series, feel free to contact me via email or on twitter.

    If you so inclined you could even fork the project, make some changes and send me a pull request.

1 2
3
4 5 6 7 8 9 10
LIVE CHAT

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

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

FOLLOW US

DevExpress engineers feature-complete Presentation Controls, IDE Productivity Tools, Business Application Frameworks, and Reporting Systems for Visual Studio, along with high-performance HTML JS Mobile Frameworks for developers targeting iOS, Android and Windows Phone. Whether using WPF, ASP.NET, WinForms, HTML5 or Windows 10, DevExpress tools help you build and deliver your best in the shortest time possible.

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