locked
Advanced Code Snippets RRS feed

  • Question

  • Hi,

    I don't know if this is possible, but I would like a code snippet that prompts for some data, and then generates stuff with it. (Sounds very vague, I know). Let me give an example:

    I want to create a code snippet for the reactive-ui properties like this:

    private bool _IsConnected;
    public bool IsConnected
    {
        get { return _IsConnected; }
        set { this.RaiseAndSetIfChanged(x => x.IsConnected, value); }
    }

    I want VS2012 to propmt for the type and the name of the property (so in this case i could fill in "bool" and "IsConnected"). When you encapsulate a field (with the standard Refactor=>Encapsulate field), it prompts for the name you want to give to the property.

    Can this be done? If so, how?


    Sincerely, Brecht

    Wednesday, October 24, 2012 7:41 AM

Answers

  • Refactoring and code snippets are different beasts so you can't really draw a comparison.  Refactoring can use code snippets but the UI they show are custom.

    Snippets aren't as powerful as you might imagine.  They haven't gotten any real focus since their initial release.  You can specify literals in a snippet which become replaceable values in the snippet itself.  For example you could define a literal for the type and a separate literal for the name.  The user will be able to select the type literal in the snippet and change the value.  Any references to that field will then be updated.  For an example try using the Visual C#\prop which basically does just that.

    If the base snippet functionality isn't sufficient then you're going to have to go outside the box.  I personally use CodeRush to get full template support.  It doesn't really do custom UIs either but it allows for full access to the existing code model so you can create conditional logic to build the template you want.  For example when I enter /xnull above a property it generates an exception XML tag.  If I enter the same thing over a method it generates a different exception XML tag.  It also supports templated-replacement like snippets do. 

    There are other tools that also provide templating capabilities but I can't speak to their features as I'm a CodeRush user.  DevExpress has a free version available but its templating is more limited. You'd have to buy a license to get the full template support.  But any good templating tool is going to require a purchase so you're best bet is to take a look at what is available and choose the best one for you.

    Michael Taylor - 10/24/2012
    http://msmvps.com/blogs/p3net

    • Proposed as answer by Lisa ZhuModerator Thursday, October 25, 2012 7:19 AM
    • Marked as answer by BrechtVsk Thursday, October 25, 2012 2:29 PM
    Wednesday, October 24, 2012 3:10 PM
    Moderator