Click here to Skip to main content
15,861,125 members
Articles / Mobile Apps
Article

Customizing Visual Studio's Code Generation Templates

Rate me:
Please Sign up or sign in to vote.
4.70/5 (52 votes)
12 Dec 2003CPOL6 min read 139.5K   96   15
A simple tutorial showing how we can customise the templates used by VS when it generates source code for us.

Introduction

In this brief snippet of fun and silliness, I am going to quickly go over how to customize the code that Visual Studio makes for you when you create a new item to add to your project. It may be that many people already know how to do this, or it may be that not many people care, but I am a self confessed fussy-pants when it comes to code aesthetics and so I'm just going to publish this, should anyone come across it and find it useful! :-)

Background

I really like Visual Studio (as a code making environment, not as a web page builder!). It has loads of great tools and tricks built in to help you make better code, faster.

One of the things it does is provide code skeletons for you when you create new items, such as new web forms, new user controls and so on.

Now, if you are anything like me, you may like your code formatted and ordered in a particular way. For example, I personally like curly brackets to appear on the same line as the method declaration/if statement and so on. Also, I don't like the fact that when making a Winform, the code initially generated has comments in places where I don't want them. Perhaps more importantly than your particular stylistic preferences, your company may prefer to use a particular code template and stylistic conventions when starting a new source file.

Prior to using the technique that I will talk about in a moment, the first thing I would have to do after adding a new item, would be to delete and rearrange much of the code that VS had just generated. Not exactly a huge problem as such, but it does become a tad tedious after a while.

The Solution

The actual solution to this little problem is actually very straightforward. As you probably guessed, Visual Studio uses templates in order to create the generated code. Given that the template files are written in plain text, all we need to do is manipulate the files until we're happy with what the template will produce.

In the particular example that I'm going to go over, we will use C# as our weapon of choice and we will change the default code generated when adding a new Winform, to something more appealing (to me!).

The necessary template files are stored according to the language that they correspond to, and the function the template is to carry out. For example, the template used for creating a new WinForm is stored at:

C:\<installation root>\Microsoft Visual Studio .NET\VC#\VC#Wizards\CSharpAddWinFormWiz\Templates\1033\

The folder C:\<installation root>\Microsoft Visual Studio .NET\VC#\VC#Wizards contains numerous folders corresponding to all the C# wizards that Visual Studio knows of. Each wizard folder has a number of bits and bobs in it, but the thing we're interested in today sits in the Templates folder.

The actual template file that we're going to change is: NewWinForm.cs.

Note: Before you go poking around and changing files such as these ones, make sure you have a backup in a safe place incase you bugger something up! I tend to just change the extension of the files I'm changing to .old. Also note, that anything you do to your own installation is entirely at your own risk. If you aren't confident that you know what you're doing, then don't touch anything and go hide under your blanket until you feel better. Having said that, this isn't rocket science by any measure so just take the usual precautions and everything will be fine.

Now that you've made a backup of the template file, open the file in your favorite text editor and you'll see:

C#
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace [!output SAFE_NAMESPACE_NAME]
{
    /// <SUMMARY>
    /// Summary description for [!output SAFE_CLASS_NAME].
    /// </SUMMARY>
    public class [!output SAFE_CLASS_NAME] : System.Windows.Forms.Form
    {
        /// <SUMMARY>
        /// Required designer variable.
        /// </SUMMARY>
        private System.ComponentModel.Container components = null;

        public [!output SAFE_CLASS_NAME]()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <SUMMARY>
        /// Clean up any resources being used.
        /// </SUMMARY>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <SUMMARY>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </SUMMARY>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.Size = new System.Drawing.Size(300,300);
            this.Text = "[!output SAFE_CLASS_NAME]";
        }
        #endregion
    }
}

One thing that you'll notice is the fact that the contents of the template file is very similar to the final result that appears in Visual Studio. In fact, given that the file type is still listed as .cs, you can open it in Visual Studio and still receive all that nice syntax highlighting just as normal.

If you have ever had to do a mail merge in a word processor then you'll be able to see immediately what's going on. The code listed above is exactly the same code that VS makes for you, apart from the fact that there are various markers placed strategically throughout the code. Markers such as [!output SAFE_CLASS_NAME] are used by VS at runtime in order to plop dynamic information into the generated code on the fly.

Given that the templates used by Visual Studio are so simple, it is very easy to change the template in anyway we want. As I mentioned before, I don't like the comments that are inserted by default and I prefer opening curly brackets to be placed on the same line as the method or conditional statement (e.g. if, while, for). Also, when making a new WinForm I like to place the auto generated code into a region out of my way. You or your company may have a convention by which certain information is always placed at the top of source files - for example revision details. Lets have a quick look at how that might look:

C#
/*
File Created by: mushentgrumbble
Date: 04/02/1866
Copyright Notice:

Class Description:

Notes:

Revision Log - Please mark significant changes in source code in the following format:

Date  -  Time -  Reviewer  -  Comments
11/11/03  -    2.34pm  -  Rebecca White  -  Bug #457 Fixed - Code released to testing

*/


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace [!output SAFE_NAMESPACE_NAME]{
    ///
    ///
    ///
    public class [!output SAFE_CLASS_NAME] : System.Windows.Forms.Form{
        private System.ComponentModel.Container components = null;

        #region Private Variables


        #endregion

        #region Properties

        #endregion

        public [!output SAFE_CLASS_NAME](){
            InitializeComponent();
        }

        #region Auto-generated code

        private void InitializeComponent(){
            this.components = new System.ComponentModel.Container();
            this.Size = new System.Drawing.Size(300,300);
            this.Text = "[!output SAFE_CLASS_NAME]";
        }

        protected override void Dispose( bool disposing ){
            if( disposing ){
                if(components != null){
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #endregion

        #region Event Handlers

        #endregion
    }
}

As is hopefully reasonably clear, my version of the code is functionally identical although I have removed, moved and added various pieces of code to suit my preferences.

The image below is how the code looks in Visual Studio. The differences are subtle but if you're anything like me, subtle things are sometimes just enough to bug you into action!

Conclusion

So there you have it - a really easy way to change the auto-generated code that Visual Studio makes. As I understand it, you should be able to do this to the other installed languages - just poke around and see what you find. I actually didn't know that this could be done initially. One day I just got fed up with the way that VS was formatting the code and so I figured that there must be some sort of template system in action. I went poking about under the Visual C# directory and that's where I found the VC#Wizards folder. I'd be interested to know if anyone else has any similar tips regarding what goes on in Visual Studio.

This is my first article for the CodeProject that I've actually published and I am a bit worried about what people will think of it. CodeProject is great and there are so many talented people sharing their knowledge that I hope my writing doesn't suck too much! However, in the event that it does, feel free to leave your comments and I'll do my best to respond to any issues that are raised. I am always open to new ideas on how to improve articles, so if anyone has any suggestions on how I can make them better then get in touch!

History

Very first draft - first Code Project tutorial! Go easy on me guys! :-)

License

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


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSuper COOL :) Pin
azamsharp29-Jul-05 11:27
azamsharp29-Jul-05 11:27 
GeneralOther article Pin
Emil Åström29-Jul-05 12:38
Emil Åström29-Jul-05 12:38 
GeneralRe: Super COOL :) Pin
sh85653130-Jul-05 5:08
sh85653130-Jul-05 5:08 
QuestionTemplate for existing project? Pin
Anonymous1-Oct-04 6:45
Anonymous1-Oct-04 6:45 
AnswerRe: Template for existing project? Pin
sh8565314-Oct-04 3:17
sh8565314-Oct-04 3:17 
Hi Anon,

I'm afraid as far as I'm aware, you can't use the templates described to alter prior projects. I think the *only* point in which the templates are considered is when the IDE is making a new item - be it project, web page or whatever. That is their one and only purpose.

If you think about a bit further though you can probably see why this is the case - how hard would it be to run some sort of template over some arbitary code? How would the IDE know what you wanted and where? OK, it wouldnt be impossible, but probably far too much work for something that most people wouldnt consider too important. I guess you'll just have to take advantage of the feature now that you know about it. Sorry about that.

On another somewhat related note - if you want complete customisation of code and actual code generation according to a template that you like and use frequently, you can save masses of time using a Gode Generator application. For example,

I recently used CodeSmith to generate my *entire* data access layer including stored procedures. That took about 10 minutes to download a freely available template, and then about 5 - 10 seconds for the template to be applied

CodeSmith(http://www.ericjsmith.net/codesmith - Very Cool

I really would give it a shot. It's easy to use and can giver you infinite control over templates and generated code etc.

Take care and thanks for posting

Simon



Voice or no voice, the people can always be brought to the bidding of the leaders. That is easy. All you have to do is to tell them they are being attacked, and denounce the pacifists for lack of patriotism and exposing the country to danger.

- Hermann Goering
At the Nuremberg Trials after World War II


GeneralGreat article, good timesaver! Pin
clover24116-Jan-04 8:05
clover24116-Jan-04 8:05 
GeneralWay cool! Pin
saxgirl15-Dec-03 12:52
saxgirl15-Dec-03 12:52 
GeneralSomething that may be of interest Pin
sh85653115-Dec-03 6:13
sh85653115-Dec-03 6:13 
GeneralWow! Thanks! Pin
sh85653115-Dec-03 1:26
sh85653115-Dec-03 1:26 
GeneralGood Article Pin
mokah15-Dec-03 0:42
mokah15-Dec-03 0:42 
GeneralNice One Pin
Owen Hines15-Dec-03 0:13
Owen Hines15-Dec-03 0:13 
GeneralVery good Pin
dotnetsql14-Dec-03 19:22
dotnetsql14-Dec-03 19:22 
GeneralFantastic Pin
Colin Angus Mackay14-Dec-03 9:52
Colin Angus Mackay14-Dec-03 9:52 
GeneralRe: Fantastic Pin
sh85653115-Dec-03 3:21
sh85653115-Dec-03 3:21 
GeneralRe: Fantastic Pin
kdowns15-Dec-03 19:39
kdowns15-Dec-03 19:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.