views:

45

answers:

1

I'm working on a project that is going to be heavily templated, but the templates I'm creating might also work well in future projects as CodeSnippets for Visual Studio.

So, I was wondering, is there a way to access Visual Studio's system of loading, parsing, and displaying the CodeSnippets in any way, shape, or form?

For example, it would be really slick to be able to do something like this:

var snippet = LoadSnippet("~/path/to/code.snippet");
if (snippet != null)
{
    snippet.TryReplace("$token$", "Some Value");
    // and then do something with snippet.ToString(), or...
    Console.WriteLine(snippet.GetCSharpString());
}

I know I could just load the .snippet files as XML and manipulate them manually, but in terms of taking advantage of the other things it does such as fill in default token values, execute functions to replace tokens, or control the editability of the tokens in the snippet file, that's more work than I want to duplicate if I don't have to.

Ideas?

Thanks!

+2  A: 

You should consider a "real" templating tool such as CodeSmith, or the new feature of Visual Studio 2010. These templates support "code-behind" during execution. Not sure of the Visual Studio toolset, but CodeSmith can be executed via API.

Snippets are much much much simpler. Don't try to make them something they are not. If you wish to use snippets there are some free-download tools (Snippet Editor, http://www.codeplex.com/SnippetEditor) to help better design them, take advantage of the features, etc, so you aren't in the raw XML so much.

Jennifer Zouak
You're absolutely right about keeping snippets simple. My so-called "templates" would be built up of many snippets, I just thought that the snippets would be nice to have in VS as well as my application. I'll take a look into CodeSmith; thanks for the suggestion.
Cory Larson
You are welcome. I suggest that in the longer term, formal templates will be easier to maintain. You can design the template to allow you to regenerate without losing custom code.
Jennifer Zouak
I see that CodeSmith has something called ActiveSnippets - "Imagine Visual Studio 2005 snippets, but with the full power of CodeSmith available to execute any logic or access any complex metadata (including database schema and xml data) to control the output of your snippets." ~ That sounds exactly like what I could use.
Cory Larson
Just an update here -- I ended up splitting the templating work between NVelocity, CodeDom, and simple XML transforms to get the job done. I tried to weigh the benefits of reusing snippets but it's just not worth the extra effort. Thanks again for the suggestion.
Cory Larson