Rory Becker - DevExpress CodeRush Blog
  • Extending Selection Embedding with CodeRush

    In my last post, I showed you around some of the Selection Embeddings that ship with CodeRush. 

    Like many CodeRush features, Selection Embeddings are user extensible. In this post I’m going to show you around the options for Selection Embedding and how you can make your own custom Selection Embeddings.

    As an Example:

    Let’s imagine you have some text in a HTML file that looks like this…

    SelectionEmbedding5Items

    … and that you’d like to have it look like this

    SelectionEmbedding5ItemsAfter

    That’s the Selection Embedding we’re going to create.

    Options

    In order to create or alter a Selection Embedding, you need to access the corresponding options page.

    • Press Ctrl+Shift+Alt+O and the Options screen will appear.
    • Select Editor \ Selections \ Embedding from the tree of pages on the left.

    You will be presented with the Selection Embedding configuration page.

    Ensure you have the correct language settings for the file you want to target. This dropdown is at the bottom of the page.

    Since this time we’re going to create a HTML Selection Embedding, we’ll select HTML from the language drop down.

    SelectionEmbeddingLanguageSelection

    Next press the green plus symbol at the top left of the page. You’ll be presented with a template for a new Selection Embedding.

    SelectionEmbeddingNewEmbedding_thumb[2]

    Let’s walk through the various parts of configuring your new selection embedding available on this page.

    Naming

    The Caption field represents the text value which you will see on the Code \ Embed Selection submenu.

    The Name field is used if you wish to bind the embedding to a shortcut later on.

    SelectionEmbeddingOptionsNameCaption

    Set the Name and Caption of our embedding to ‘Unordered List ‘

    Style offers 5 alternate styles of selection embedding.

    SelectionEmbeddingOptionsStyles

    With Style 1 you are able to enter text for the Top, Bottom, Left and Right of your selection.

    • Text entered for left and right will be repeated for each line of your selection.
    • Text entered for Top and Bottom, will be added above and below your selection.

    SelectionEmbeddingOptionsStyle1

    In Style 2 you are able to enter text for the Top and Bottom of your selection.

    • Text entered for Top and Bottom, will be added above and below your selection .

    SelectionEmbeddingOptionsStyle2

    In Style 3 you are able to enter text for the Left and Right of your selection.

    • Text entered for Left and Right will be repeated for each line of your selection.

    SelectionEmbeddingOptionsStyle3

    In Style 4 things change a little:

    • The Top Text is moved to the Left of the Top line of your selection replacing the Left text from Style 3 and Style 1.
    • The Bottom text is moved to the Right of the Bottom line of your selection replacing the Right text from Style 3 and Style 1.
    • Note how text which will appear in the Bottom Left and Top Right sections, is copied in the screenshot from the appropriate Middle Line text.

    SelectionEmbeddingOptionsStyle4

    Style 5

    In Style 5

    SelectionEmbeddingOptionsStyle5

    Set the Style of our Selection Embedding to ‘Style 1’

    Text Options

    If you select a style with Left and Right Text (any style except Style 2) then the following set of options will be enabled

    SelectionEmbeddingOptionsLeftRight

    These options specify where you would like the Left and Right text to be placed relative to the selection they wrap. Experiment with these and see what a difference they can make to your Embeddings.

    In our case choose ‘Start of code’ and ‘End of code’ respectively.

    The last options allow you to enter TextCommands and StringProviders into your Embedding to produce numerous effects when the expansion happens.

    SelectionEmbeddingTextCommands

    We don’t need these options for our selection embedding, but it’s worth knowing they’re here.

    The last part of the configuration is the most important. You need to specify the various pieces of text that will surround your selection.

    You’re fully configured Selection Embedding, should look something like this:

    SelectionEmbeddingUnorderedListWithHighlights

    Click Ok, and you’re done.

    Once you have completed the previous steps, all you have to do is

    • Select your text
      SelectionEmbeddingSelectText
    • Hit your CodeRush\Refactor key and Select Unordered List from the Embedding menu.
      SelectionEmbeddingSelectOrderedList

    and CodeRush does the rest.

    As I’ve stated many times before. One of the best features of CodeRush is it’s extensibility. If the features don’t ship out of the box just the way you like them, you can adjust, configure and augment to your hearts content.

    Feel free to share any custom Selection Embedding ideas in the comments below.

  • Selection Embedding with CodeRush

    Selection Embedding is one of those CodeRush features that doesn’t get a lot of mention, but it is extremely powerful.

    It provides the user with the ability to wrap some text (code, mark-up, comments) around some existing code already in place.

    Selection Embedding is available from your the Code section of your CodeRush SmartTag menu (As well as via several custom shortcuts)

    Each Selection Embedding is context sensitive, so that only those for the current document type are shown to you.

    Below is an example of the selection embeddings available from within the C# editor.

    SelectionEmbeddingCSharp

    These are produced when I highlight some text in the HTML editor.

    cSelectionEmbeddingHTML

    Selection Embeddings do not have to be picked from the SmartTag menu. As mentioned, some have associated shortcut keys.

    Try highlighting 1 or more lines of C# code and then …

    …pressing T causes your code will be wrapped in a try..catch..finally block.
    …pressing C causes your code will be wrapped in a try..catch block.
    …pressing F causes your code will be wrapped in a try..finally block.
    …pressing B or { causes your code will be wrapped in a brace (ie { and } ) block.
    …pressing ( or ) causes your code will be wrapped in parenthesis.
    …pressing R causes your code will be wrapped in a #region…#endregion block.
    …pressing U causes your code will be wrapped in a using block.
    …pressing W causes your code will be wrapped in a waitcursor block.

    Some of these are pretty simple wrapping effects. Others put CodeRush fields and text commands in place to enhance your experience further.

    Here the using embedding places your caret within the using expression so you can more easily fill it out.
    Additionally, when you press enter, your caret is moved to the bottom of the expression ready for further code.

    SelectionEmbeddingUsing

    Here CodeRush provides a specialized try..finally block…

    SelectionEmbeddingWaitCursor

    • Saves your current cursor
    • Sets your cursor to the WaitCursor.
    • Executes your original code.
    • Restores your cursor to it’s original state, regardless of the success of your code.

    This is all boiler-plate code, but it’s boiler-plate code you don’t have to write yourself. This reduces the chance of typos or, worse still, logic errors.

    As you can see, Selection Embedding can be a very powerful tool, providing you with boiler-plate code in a fraction of the time, with fewer keystrokes and reducing the chance for typewritten errors across the board.

    As with most CodeRush features, Selection Embedding is user extensible.

    In my next post, I’ll show you how to make your own Selection Embeddings.

  • New CodeRush Plugin – SplitTag

    This is certainly one of the more simplistic plugin’s I’ve written, and yet it’s also one I use all the time.

    Imagine that you have the following fragment of HTML and you’d like to split it in half.

    SplitTagBefore

    • Simply place your caret where you’d like to split the tag.
    • Hit your CodeRush \ Refactor key

    SplitTagMenu

    • Select ‘Split Tag’ from the menu
    • … and CodeRush will break your single tag into 2 of the same type.

    SplitTagAfter

    This plugin can be particularly useful when creating <li> tags within various lists.

    CR_SplitTag

    Availability

    This plugin is available from either The Visual Studio Gallery or from GitHub

    The source is available on Github

  • New CodeRush Plugin – CR_CollapseXML

    Another new plugin! This one requested by a customer so they could collapse some XML (or HTML) on command.

    Is there any way to have CodeRush collapse HTML or XML elements which have a ‘name’ or ‘id’ attribute?

    The theory behind this is that those elements with an id or name attribute, are typically the ones that hold the high level structure. Collapsing these items will cause the structure of the HTML to be revealed.

    In some ways it ‘s like CodeRush’s own Collapse to Projects functionality in solution explorer.

    The user wishes to get a high level view of their HTML so that they can decide which area to drill back down into.

    Now CodeRush doesn’t naturally support this functionality for HTML/XML out of the box, but you guys know me by now Smile

    Yeah I wrote a plugin Smile

    CollapseXML for CodeRush

    CollapseXML works (despite it’s name) on both HTML and XML. It adds a new command (CollapseXML) which you can bind to any key you like.

    Once installed and configured, simply place your caret within an XML or HTML file, and invoke the command using your configured key.

    CodeRush will happily collapse your XML/HTML from…

    HTMLExpanded

    … to…

    HTMLCollapsed

    Availability

    This plugin is available from either The Visual Studio Gallery or from GitHub

    The source is available on Github

  • New CodeRush Plugin – Sort Format Tokens

    Some programmers feel that they have some sort of very minor OCD. Despite no real rational reason, they feel that certain things should be a certain way. The world seems out of place, slightly of kilter, slightly more irritating or distracting when these things are not quite as they would like them to be.

    Of course when I say ‘Some programmers’, I certainly include myself in that group.

    Today’s plugin is kind of an OCD plugin. It’s just my personal attempt to scratch a little itch. I’d be amazed if this helps anyone else at all. I’m just putting it out there as an example of just how flexible CodeRush can be.

    When I set out to create it, I had no other purpose in mind, than the appeasement of that part of my brain, which objected every time I didn’t adjust my code to this specific pattern.

    That said, the plugin does have some benefits as a natural consequence of the way it works.

    Sort Format Tokens

    This plugin operates on a subset of the String.Format calls.

    Consider the following call:

    SortFormatTokensExample1

    It’s simple and it does exactly what you need it to. However over time you might feel the need to add more elements to the message:

    SortFormatTokensExample2

    Something about this statement irks me. Something just doesn’t sit right. So I find myself rewriting it

    SortFormatTokensExample3

    This new code operates exactly the same as the old code. There isn’t even a performance benefit here.

    However my particular brand of very minor OCD feels better and I’m able to scan through the code and comprehend it quicker.

    The Problem

    Changing one statement into the other is a manual task. There is the risk of typos and logic errors, and of course it takes time to achieve.

    Not very much time I guess, but every moment that I spend thinking about this sort of thing, is less time spent on solving business problems and adding value.

    Therefore I did what I usually do when I spot a coding task I’d prefer not to have to do manually, which has an predictable pattern to it….

    I wrote a plugin Open-mouthed smile

    The Solution –> Sort String Tokens for CodeRush

    This plugin does exactly what it says on the tin.

    It rewrites the a String.Format call so that…..

    • The string tokens are (where appropriate) in numerical order.
    • The arguments that follow the string are in the same matching order.

    Simply place your caret within the first argument of a String.Format call and choose 'Sort Format Tokens’ from the Code subsection of your CodeRush\Refactor Smart tag menu.

    SmartTagMenuSortFormatTokens

    Bonus Features

    Beyond the original spec of “Sort my string tokens so that they look nice”, SortFormatTokens is also careful to correctly interpret several corner case scenarios.

    • It deals correctly with sequences of tokens with missing items.
      Gaps in the sequence are removed.  “{1} – {3} – {6}”  becomes “{0} – {1} – {2}”.
    • It deals correctly with string tokens that have formatting information.
      Formatting information is retained within the renumbered token. “{1:00} – {0} – {2}” becomes “{0:00} – {1} – {2}”
    • It deals correctly with duplicate usage of a token within a string.
      The 2nd and further instances of any given token are renumbered the same way as the first instance. “{1} – {0} – {1}” becomes “{0} – {1} – {0}”.
    • It also removes any unreferenced arguments from the call, optimizing your call to be faster in the process.

    Where can I get this wonderful plugin from?

    As usual this plugin is available from the Visual Studio Gallery and from GitHub.

    The source code is available on GitHub

  • New CodeRush Plugin – CR References Metric

    Just a quick little post to announce a tiny little plugin which provides member reference counts in the form of a metric.

    Simply click the metric tile and choose ‘References’ from the dropdown.

    ReferencesMetric

    CodeRush will then display the Reference count of each member next to each one.

    Availability

    As usual this plugin is available from the Visual Studio Gallery and from GitHub.

    The source code is available on GitHub

  • New CodeRush Plugin – CR_CorrectReturnType

    In my previous post I was extolling the virtues of Convert to Function.

    You’ll recall that it is used to alter the return type of the current function, from void to the value of the expression on the return statement at the caret.

    MethodReturningIEnumerableInt

    Well what if you have a pre-existing function which returns a string, and you need to alter the function to return an int.

    Convert to Function is only available if the method is of type void. It is not available if the function returns anything else.

    Enter CR_CorrectReturnType

    My latest plugin, Correct Return Type provides the same functionality as Convert to Function, however it works where Convert to Function does not.

    If the active function’s return type is non-void, and differs from that of the return statement at the caret, then Correct Return Type will become available instead of Convert to Function.

    CorrectReturnType

    Availability

    As usual this plugin is available from both the Visual Studio Gallery and from GitHub.

    The source code is available on GitHub.

  • CodeRush – Feature Spotlight – Convert to Function

    Assuming you want to create a new function, there are a few ways you could build it.

    For now let’s focus on the function’s return type…

    Type First

    In this case, you know the type of the value which your function will return.

    You have decided that you want to return a integer.

    The simplest way to do this is using the mi<space> template, which will result in the code below.

    MethodReturningInt

    All that’s needed is:

    • An appropriate name.
    • Any required parameters.
    • The body of the method.

    …and you’re done.

    But what if, in that first moment, you don’t know what type you’d like to return from your method?

    Type Last

    If you’re not entirely sure of the type your method should be returning, don’t worry…. Just don’t specify one …. yet.

    Use CodeRush’s m<space> template to generate the method which has no return value. Otherwise known as a void proc.

    MethodReturningVoid

    As before you have to specify:

    • An appropriate name
    • Any parameters
    • The body of the method.

    However let’s suppose that you’ve done this and you have your brand new Return42 function.

    MethodReturning42

    You’ll notice that at this point our function doesn’t compile. This is, of course, because we are attempting to return an int from a method which specifies a return type of void.

    This is clearly unacceptable and needs fixing. Ordinarily we’d visit the signature of the function, highlight the word void and overtype it with int.

    This can be rather annoying. However CodeRush has our back.

    Simply place your caret on the return keyword and select Convert to Function from the smart tag menu.

    ConvertToFunction

    CodeRush deduces the type of the expression being returned, and alters the signature of the method to int rather than void.

    In our example, the involved type was easy to deduce and relatively simple, but the procedure works with more complex expressions as well.

    MethodReturningIEnumerableInt 

    Summary

    People aren’t all the same, and work in a myriad different ways.

    I’m one of those people who tend not to think in terms of the specific type I’m returning, until the point of actually returning a value.

    CodeRush doesn’t force me to think about this, and is happy to wait until I’m ready.

    When I am ready, CodeRush still has my back with tools to help achieve my goals in my way.

  • New CodeRush Plugin – CR_RemoveStringToken

    A new plugin… What does it do?

    Example 1

    So imagine we have the following code..

    RemoveStringTokenExample1

    Imagine now, that we decide that it’s not important to explain ‘where’ we were searching, when reporting this error.

    Normally we would…

    • Highlight the string token {1} (including it’s associated text).
    • Hit delete.
    • Highlight the “Y” argument (including it’s leading comma).
    • Hit delete.

    RemoveStringToken allows us to remove the token and it’s associated parameter in a single step.

    • We place our caret on the token we want to remove ({1} in this case)
    • Choose Remove String Token from the Code menu.

    RemoveStringTokenExample1a

    A little tidying is required to remove ‘ in ‘, but that’s a whole lot simpler than before.

    Example 2

    In this next example, things are slightly more complicated.

    RemoveStringTokenExample2

    Users aren’t terribly good with codes, so we’ve decided to remove token {1} from the message.

    The manual steps to achieve this are mostly the same as the previous example.

    • Highlight the string token {1} (including it’s associated text)
    • Hit delete.
    • Highlight the “Y” argument. (including it’s leading comma)
    • Hit delete.

    However this time there is an additional requirement.

    Since we’re removing a string token from the middle of the sequence, we need to renumber the tokens that are numerically higher than the one we’re removing.

    So this time our manual steps would also include:

    • Renumber references to {2} so they reference {1} instead.

    Of course if we had additional references to {1} in your string, we’d have to remember not to renumber those other tokens.

    I’m sure you agree that’s a bit of a pain.

    RemoveStringToken handles the token removal, the parameter removal and the token renumbering, all in a single step.

    RemoveStringTokenExample2a

    Once again there are some additional characters in need of a trim. but these are easily dealt with.

    Checks and Balances

    It’s worth noting that with any simple sequence of steps that a human might make, there is always the possibility of mistakes.

    RemoveStringToken checks several things automatically every time, so you don’t have to.

    • Arguments are only removed if there are no remaining references to the target token.
    • Tokens are only renumbered if there are no remaining references to the target token.
    • Console.WriteLine and String.Format are both supported.
    • If no tokens remain within the string, and the outer call is to String.Format, then this outer call is removed.

    Availability

    As usual this plugin is available from the Visual Studio Gallery and from GitHub.

    The source code is available on GitHub

     

  • New CodeRush Plugin–CR_ReverseOperands

    This plugin is a natural follow up to my previous CR_ReverseArgs plugin

    As you might imagine, this plugin changes the order of the selected operands.

    CR_ReverseOperands

    This might seem like a fairly trivial reason to create a plugin, but it happens often that it irritates me, and it does solve the problem. Hopefully it will also save you some time.

    Availability

    As usual this plugin is available from The Visual Studio Gallery and from GitHub.

    The source code is also available on GitHub.

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