5,317,180 members and growing! (17,481 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Intermediate

Customizing Visual Studio's Code Generation Templates

By sh856531

A simple tutorial showing how we can customise the templates used by VS when it generates source code for us.
.NET 1.0, .NET 1.1, CE 2.11, CE 3.0, NT4, Win2K, WinXP, Win2003, CE .NET 4.0, CE .NET 4.1, CE .NET 4.2, Windows, WinCE, .NETMobile, WinMobile2002, Dev

Posted: 12 Dec 2003
Updated: 12 Dec 2003
Views: 73,770
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
50 votes for this Article.
Popularity: 7.38 Rating: 4.34 out of 5
0 votes, 0.0%
1
1 vote, 2.0%
2
5 votes, 10.0%
3
12 votes, 24.0%
4
32 votes, 64.0%
5

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:

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:

/*
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

sh856531


Well hello everyone. I doubt anyone will go to the trouble of reading this, but just in case ...

I am a relatively recently graduated developer. Graduated from Stirling(Scotland, UK) in 2003 with a pretty good degree in Computing Science.

My main forte is Java, Database development and increasingly .Net and the new push towards internet development.

I have a broad range of interests - many of them academic, but I hope that doesnt mean I don't have any friends! These interests range from current affairs, politics, medicine to economics, philosophy and law. So quite a broad range of things.

I enjoy learning and being involved in the whole learning process. Thats why I'm registered on the codeproject - its helped me a lot in the past, and I like helping others in the forums.
I've been writing a few tutorials for junior developers and so I'll hopefully be publishing them for comments very soon.

I'll look forward to speaking to you all on the site!

Take care and thanks for making the codeproject such a great resource for so many people

Simon
Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular .NET Framework articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 15 of 15 (Total in Forum: 15) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralSuper COOL :)memberazamsharp12:27 29 Jul '05  
GeneralOther articlememberEmil Åström13:38 29 Jul '05  
GeneralRe: Super COOL :)membersh8565316:08 30 Jul '05  
GeneralTemplate for existing project?sussAnonymous7:45 1 Oct '04  
GeneralRe: Template for existing project?membersh8565314:17 4 Oct '04  
GeneralGreat article, good timesaver!memberclover24119:05 6 Jan '04  
GeneralWay cool!membersaxgirl13:52 15 Dec '03  
GeneralSomething that may be of interestmembersh8565317:13 15 Dec '03  
GeneralWow! Thanks!membersh8565312:26 15 Dec '03  
GeneralGood Articlemembermokah1:42 15 Dec '03  
GeneralNice OnememberOwen Hines1:13 15 Dec '03  
GeneralVery goodsussvbnetuk20:22 14 Dec '03  
GeneralFantasticmemberColin Angus Mackay10:52 14 Dec '03  
GeneralRe: Fantasticmembersh8565314:21 15 Dec '03  
GeneralRe: Fantasticmemberkdowns20:39 15 Dec '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Dec 2003
Editor: Smitha Vijayan
Copyright 2003 by sh856531
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project