Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Generating code with T4

From: Visual Studio 2010 Essential Training

Video: Generating code with T4

Visual Studio includes a code generator that creates files from a simple template definition. It has an awkward name; it's known as the Text Template Transformation toolkit. Most of us just call it T4. I am inside Visual Studio, and I have opened the CodeGenWithT4 project. Let's think about what we are going to do for a minute. I have code that I write over and over again that has some replaceable bits. So what I am going to create is a scaffolding of the basics of my code, and then I am going to have these little replaceable parts that the code generator will replace on my behalf.

Generating code with T4

Visual Studio includes a code generator that creates files from a simple template definition. It has an awkward name; it's known as the Text Template Transformation toolkit. Most of us just call it T4. I am inside Visual Studio, and I have opened the CodeGenWithT4 project. Let's think about what we are going to do for a minute. I have code that I write over and over again that has some replaceable bits. So what I am going to create is a scaffolding of the basics of my code, and then I am going to have these little replaceable parts that the code generator will replace on my behalf.

To create this code template, I need to add a T4 template, by right-clicking and choosing Add > New Item. And I'll type in "template" in the Search dialog and pick this simple Text Template right here, and then I am going to call this one SimpleDemo and click Add. I get warned by Visual Studio that this template may harm my computer. I am going to go ahead and risk it by clicking OK. At the top of this template is some instructions of what to build. It's going to create a C#-specific class, and the extension on the file that it's going to generate is txt.

So if you come over here and look underneath these SimpleDemo.tt file, by expanding this node, you'll see that there is a text file there. I want this to be a C# file, so I am going to change the extensions from .txt to .cs, and then I am going to build the application. I'll accept the risk. And if you look over in the Solution Explorer now, you'll see that this it says SimpleDemo.cs. Next, I'll create the basic scaffolding.

Some of this text is never going to change, like a Using statement, at the top of my screen, using System, or public class Customer. This is known as a text block, which means it's entered exactly as I type it here. Watch what happens now when I do a build. I'll choose Build Solution, click through these dialogs. Then I am going to open the SimpleDemo.cs file, and you see it's starting to generate some code for me.

There are more sophisticated kinds of instructions you can put in your template. You can create something called an expression block. That computes the value, and then inserts it into your output file. You can also create something called the statement block, which allows you to run any arbitrary code. You can also create something called a class feature block, which allows you to embed code sections within the template. Let me show you how to do an expression block. I'll switch back to the template, "public void DoWork".

What the DateTime.Parse () method does is it takes a string and tries to convert it into a DateTime. I am going to get the time from the operating system. So inside these double quotes, I am going to put my expression block. I need the special symbol for T4, which is the open angle bracket, pound sign, and then the pound sign and a close angle bracket. And then I'll use the assignment operator here, equal. I think I've got my code correct.

Let's see if it compiles. Excellent! Now let's go back to SimpleDemo.cs, and you'll see that it created this function and inside the function is this line of code that's declaring a variable, and here is the piece of data that came from the code template generator. Rather than write a bunch of code, I am now going to switch over to this MakeFunction.tt file, which is a more complete example. Here is the same bit of code I showed you few minutes ago. I am also creating a variable here and asking the computer for the machine name. I am then going to declare a variable that's going to hold the list of string, one of the generic types in .NET.

And then look what is happening here. I am calling a function that I declared in my template code. So down here in this section, with this special starter--angle bracket, pound, plus sign, then it ends here on line 36-- I've declared a function called PrintFileNames, which basically goes out, given a folder name, and looks to see if the directory exists. If it does, it walks through all of the files in that folder and prints their name out to my code file, and then I call that function up here. Let's see what happens when I run this example.

Here is that code: var fileName = new List, and then I am using the initializer syntax to add these string names to the list. Another really exciting thing to do with templates is to work with a database. So in this project, I added a database file, this Northwind.mdf file, and then I created the data model for that, a linked data model. Now I can go to this code template, this CreateBusinessClasses code template, and in this section right here, I am calling that Northwind data using this thing called the NorthwindDataContext. And then I am foreach-ing over the database, and finding each table inside that database. And I am looking to see if it starts with the word "dbo.", and if so, then I am stripping some of the database characters off of it, so that I have a class name that makes sense in my C# code.

Then down here, I am declaring a class, and I am saying I want that tableName. Then within the class, I am doing a foreach over the DataMembers--this would be like the column names of the table--and I am writing a little bit of code here to create a public property. So when I run this template, what I end up with is a list of classes that map to the database. That's why they call it Object Relational Mapping. There is a table named Categories. I created a class called Categories. There was a Territories up here, and it has a TerritoryDescription; that's the column name inside the database, and that becomes a public property on my type.

This is a very powerful mechanism. I've used it very successfully on some big projects, where we generate our schemas automatically. And if somebody changes the database schema, the next time we build our code, let's say they change this column name in the database, it automatically changes our codes to reflect the real name inside the database. I think code generation done right, it can be a productivity boost for you and your development team. The included T4 Editor is a little sparse, but you can always install a free Visual Studio extension from a company called Tangible, for better syntax help.

Show transcript

This video is part of

Image for Visual Studio 2010 Essential Training
Visual Studio 2010 Essential Training

86 video lessons · 30522 viewers

Walt Ritscher
Author

 
Expand all | Collapse all
  1. 2m 3s
    1. Welcome
      1m 2s
    2. Using the exercise files
      1m 1s
  2. 7m 19s
    1. Understanding the Visual Studio versions
      3m 51s
    2. Setting up your developer computer
      3m 28s
  3. 58m 2s
    1. Creating a Visual Studio project
      4m 58s
    2. Working with Solution Explorer
      6m 32s
    3. Working with big projects
      3m 53s
    4. Taking a tour of the Integrated Developer Environment (IDE)
      8m 36s
    5. Introducing drag-and-drop UI design
      7m 38s
    6. Working with the Properties window
      6m 44s
    7. Looking at Server Explorer
      7m 4s
    8. Exploring the new Help engine
      6m 41s
    9. Setting options for the IDE
      5m 56s
  4. 39m 25s
    1. Creating a simple WPF application
      1m 32s
    2. Building the UI with the editors
      9m 14s
    3. Working with the application code
      3m 37s
    4. Communicating with the web site
      7m 15s
    5. Connecting your data
      8m 4s
    6. Binding to an RSS feed
      5m 4s
    7. Packaging and deploying the application
      4m 39s
  5. 39m 46s
    1. What languages are supported in Visual Studio 2010?
      1m 17s
    2. Exploring basic settings for the Code Editor
      5m 35s
    3. Writing a C# program
      6m 48s
    4. Writing a VB program
      6m 29s
    5. Working with C++
      6m 38s
    6. Working with F Sharp
      6m 9s
    7. Font and color options
      6m 50s
  6. 1h 5m
    1. Formatting your code
      6m 43s
    2. Navigating your code
      7m 44s
    3. Using the Task List
      2m 26s
    4. Commenting your code
      2m 45s
    5. Documenting your code
      8m 26s
    6. Using IntelliSense effectively
      7m 0s
    7. Working with code snippets
      6m 25s
    8. Refactoring your code
      5m 15s
    9. Understanding code generation
      2m 10s
    10. Generating code with T4
      6m 29s
    11. Using the Class View, Class Designer, and Class Diagram tools
      5m 51s
    12. Refactoring VB with CodeRush Xpress
      4m 33s
  7. 1h 11m
    1. Working with project and item templates
      8m 38s
    2. Creating a console application
      7m 5s
    3. Creating a class library
      6m 26s
    4. Creating a web site with ASP.NET
      7m 37s
    5. Creating a rich internet application with Silverlight
      6m 57s
    6. Creating a classic Windows application with Windows Forms
      10m 31s
    7. Creating a dramatic Windows application with Windows Presentation Foundation (WPF)
      4m 41s
    8. Creating a WCF service
      9m 1s
    9. Using an existing WCF service
      6m 38s
    10. Navigation UI designs with the Document Outline view
      3m 41s
  8. 33m 18s
    1. Creating a data project with SQL Project
      6m 24s
    2. Clarifying the confusion on .NET Data
      3m 31s
    3. Using ADO.NET in your application
      6m 50s
    4. Creating typed datasets
      7m 55s
    5. Using the data binding tools
      8m 38s
  9. 30m 13s
    1. Debugging code
      9m 32s
    2. Working with the Watch and other debug windows
      7m 46s
    3. Other debugging techniques
      6m 50s
    4. IntelliTrace historical debugging in Visual Studio Ultimate
      6m 5s
  10. 17m 56s
    1. Understanding Visual Studio editions and test tools
      2m 22s
    2. Verifying your code with unit tests
      8m 58s
    3. Running performance and load tests
      6m 36s
  11. 34m 5s
    1. Building your application
      4m 19s
    2. Customizing the build process with MSBuild
      6m 36s
    3. Setting assembly information
      2m 12s
    4. Deploying a basic Windows application
      2m 19s
    5. Creating an installer with Visual Studio
      7m 39s
    6. Creating a ClickOnce application
      5m 13s
    7. Setting up IIS for deploy
      2m 9s
    8. Deploying a Silverlight or ASP.NET application
      3m 38s
  12. 14m 0s
    1. Understanding source control
      2m 9s
    2. Setting up Team Foundation Server source control
      3m 5s
    3. Using Team Foundation Server source control
      8m 46s
  13. 17m 31s
    1. Understanding the .NET Office integration
      4m 16s
    2. Making a Word 2010 application
      7m 54s
    3. Making an Excel 2010 add-in
      5m 21s
  14. 31m 34s
    1. Understanding the extensibility model in Visual Studio
      2m 17s
    2. Adding external tools to the Tools menu
      4m 42s
    3. Creating macros
      7m 16s
    4. Using the Extension Manager
      5m 1s
    5. Creating an MEF add-in
      7m 9s
    6. Deploying and installing an add-in with VSIX
      5m 9s
  15. 25m 34s
    1. Working with configuration files
      5m 37s
    2. Using the Settings Editor
      7m 30s
    3. Using the Resources Editor
      6m 59s
    4. Localizing your resources
      5m 28s
  16. 1m 17s
    1. Goodbye
      1m 17s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Visual Studio 2010 Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.