Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
hi,

in my application (.net MVC, c#) im using a fixed structure for public methods of one of my modules.

When im adding a new public method to this module i need to add the following code:

1) a code segment in an existing file, something like:

[...attribute...]
[...attribute...].public ... {Method-Name}(...)
{
   ...init code...
}


2) two code files defining two classes. The name of these classes is built using the method name ({Method-Name}) appended with some suffix, for example:

using System...;

namespace ...
{
    public class {Method-Name}Model
    {
        public {Method-Name}Model()
        {
        }

        ...common code...
    }
}



I need to generate this code once (for each new method) - after which i edit the files and add the specific details & logic.

Currently i just copy the code of existing methods and modify it.

I've tried doing the above using T4 Text Templates, however i could not find how to:

- run manually T4 scripts?
- run T4 scripts with parameters?
- run several T4 scripts one-after another?
- run a T4 script within an existing code file to add a code fragment template inside that file?

For example the following T4 template to generate the class from above:

<#@ template language="C#" #>
<#@ parameter type="System.String" name="MethodName" #>
<#@ output extension=".cs" #>

using System ...

namespace ...
{
    public class <#= MethodName #>Model : ...
    {
        public <#= MethodName #>Model()
        {
        }

        ...common code...
    } 
}
Posted
Updated 1-Nov-15 23:39pm
v4

1 solution

Code Snippets[^] may be worth the look. You can use them to insert predefined code blocks with customized element names.
 
Share this answer
 
Comments
yaron gilboa 2-Nov-15 6:14am    
ok - that almost did it ;)

One question though - is there a way to generate files using snippets?
phil.o 2-Nov-15 6:26am    
Not directly (at least as far as I know, I never tried to use the snippets programmatically). But I may be wrong on that, and a subsequent search could be worth the time.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900