Scott Hanselman

T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret

October 14, '08 Comments [30] Posted in ASP.NET | Programming | Tools
Sponsored By

Rob beat me to it. Blogging about T4 (the Text Template Transformation Toolkit) had been on my list literally for a year. He and I were singing its praises last night. Hopefully I can add something small to the conversation.

What's the story? Well, T4 is a code generator built right into Visual Studio. To be clear, you HAVE THIS NOW on your system…go play. Now's the time to introduce code generation to your company. If you're doing something twice or more, manually, in your company, generate it.

However, it's not deep-deep built in, because there's no item templates in File | New Item and there's no intellisense or syntax highlighting.

You don't need this, but if you want really get the most out of T4, first, head over to Clarius Consulting and get their "T4 Editor Community Edition." That'll get you some basic coloring. They have a pay version that gets you more if you want.

Now, go into Visual Studio and make a Console App (or any app) and add a Text File, but name it something with a .tt extension. You'll get a warning since it's a generator, that someone could generate evil. Click OK if you are cool with potential evil. ;)

Security Warning

imageNow, look in Solution Explorer at the .tt file. If you're using C#, you'll have a sub .cs file, or if you're using VB, a sub .vb file. That's the file that will hold the result of the generation. This is the same visual metaphor used to the express the template/generated file relationship with .designer files you've seen elsewhere in Visual Studio.

If you look in the Properties for the .tt file, you'll see it's using a CustomTool listed as the "TextTemplatingFileGenerator." This custom tool extensibility point is how things like XSD and WSDL code generators hook in to generate their artifacts.

T4 can generate any kind of text file, not just code. Whatever you like. You can use it in your projects, as above, or you can call T4 from the command-line.

Aside from Kzu and the folks at Clarius, Rob notes that Oleg Sych has a great collection of T4 resources. He's got some great Tutorials:

Here's some of the links from Oleg's blog.

Oleg also has a CodePlex project called T4 Toolbox that is a library of T4 templates that get added to File | New Item.

Also, check out Damien Guard's T4 templates that are a wholesale replacement of code that LINQ to SQL generates. Here's an example, where I use Damien's T4 templates against the sample Chinook Database.

image

Notice that I've named the .tt file the same as the .dbml, so Damian's code can find it. I also continue to let original LINQ to SQL generate it's .designer.cs file, but make that file's Build Action "None" so it's not ever compiled. That effectively puts Damian's code in charge.

Here's a screenshot showing a bit of Damian's T4 template using the syntax highlighting from the Clairus T4 Visual Studio free download. If I'd pay them, I'd get intellisense and syntax highlighting inside the code blocks also. It looks like a lot like ASP.NET Web Forms, or Velocity, or any templating language really. The code blocks are where your logic is and outside the codeblocks is the template for whatever you want to generate. Notice how Damien gets input and sets output. You have full control, you can read files off the file system, from with your project, etc. He sets the output extension also. I like to use .g.cs or .g.vb, myself. In this example his generated file is Chinook.generated.cs.

I particularly like Damien's example because he's swapping out parts of LINQ to SQL that he didn't like (the generated code) while keeping the part he did (the general mode, the designer, the dbml file.) If you don't like something, fix it.

Plus, it all works in Visual Studio without installing anything.

image

If you're doing Code Gen, or thinking about it, check out T4 as it's a great place to start. Also, search my blog for "Code Generation" as I was livign and breathing it with CodeSmith for the many years I worked at Corillian. Have fun!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Silverlight 2 is out!

October 14, '08 Comments [16] Posted in ASP.NET | ASP.NET Dynamic Data | ASP.NET MVC | PDC | Silverlight
Sponsored By

Bam. Silverlight 2 is out. There's the expected stuff, like the final SDK, Expression, and Silverlight tools:

And from Tim's blog:

And from ScottGu's blog, the Epic GuPost. But there's also http://www.eclipse4sl.org/. Yes, that means you can code Silverlight in Eclipse. Details and progress at the Eclipse Tools for Silverlight Blog. It'll be licensed under the EPL 1.0 License.

Love the free tools. You can also code Silverlight with the free Visual Web Developer Express, so you don't need to pay for a working development environment to try out Silverlight.

There's a bunch of new stuff in this, the Release of Silverlight 2. Check out Tim Heuer's blog for lots of good details on Controls, ADO.NET Data Services, Text Rendering improvements, and more. Also, there are (and will be more) videos, screencasts, samples and demos at my team's site at http://www.silverlight.net, so check it out.

Also, be watching the Silverlight Dynamic Languages SDK and CodePlex Site as I hope they'll update their stuff to the release of Silverlight very soon. It's fun to write IronRuby and have it running in a browser.

The Dynamic Languages SDK contains support for writing Ruby, Python, and JScript applications in the browser. However, since this project provides a bridge between Silverlight™ and the Dynamic Language Runtime (DLR), any language running on the DLR will be enabled to build Silverlight applications.

Also, if you're going to be at PDC, please come to my talk and see what Grant Archibald and I have been working on.

Microsoft .NET Framework: Overview and Applications for Babies

Join Scott Hanselman for this lots-of-code-minimal slides talk that walks through the sheer joy of building out a .NET Framework application with Visual Studio using many of the new advances in the .NET Framework 3.5SP1 and 4.0. We have a data layer with Entity Framework, use REST web services with WCF and ADO.NET Data Services, write an ASP.NET site for reporting using Dynamic Data and MVC. All the data will come from a WPF client application and a Silverlight application that the audience will run live! All this, plus it's an application that babies and toddlers will love!

Have fun!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Survey Time: What .NET Framework features do you use?

October 14, '08 Comments [32] Posted in ASP.NET | ASP.NET Dynamic Data | ASP.NET MVC | PDC | Web Services | Windows Client | WPF
Sponsored By

iStock_000006694182XSmallUPDATE: This survey is closed. For two reasons actually. First, we got just 3500 responses in less than a day, so that's good. The bad part is that these survey guys (whom I paid, BTW) deleted the survey and my account without asking. Fortunately I got the data out in an export before this happened. Sheer luck. I bet there were upwards of 5000 responses. Very unprofessional and disappointing. I'd have appreciated a heads up from them. Next time I'll just use Survey Monkey. I'll publish the results after I fancy-chart them in Excel.
Thanks to everyone for participating!

UPDATE 2: Not sure what's up with these guys, but the survey is back up, so I'll keep collecting data for a few more days.

Hey folks, as I've said before, one of the things I like to do is take your comments, questions and feedback directly to the right folks inside Microsoft.

They have all sorts of scientific methods, analysts, and smarties that give them information, usage details, etc. Sometimes, however, I like to throw the product planners the occasional totally RAW web survey, just to make sure that there's fewer layers between me and the bosses.

That said, please take 10 seconds and fill out this ONE QUESTION SURVEY. Feel free to tweet it on Twitter, forward it to your friends, or blog it.

http://www.tinyurl.com/dotnetsurvey (here's the FULL URL)

Yes, the survey is missing things. It's a survey about larger framework subsystems, not languages, not Silverlight, etc. You'll see. It's still very useful to me and others.

I'd like to get 2500 responses before I give it to the bosses. Any less doesn't really seem like a lot, you know?

I'll blog the results later! Thanks.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Here Comes Trouble

October 13, '08 Comments [24] Posted in Musings
Sponsored By

Looks like the 10 month old is walking. As The Wife says, "now we're screwed, they're both mobile!" We've spent the weekend chasing this little man all over the house. He's already insane and now his speed has doubled. ;)

It's interesting how the 10 month old has done things (sign, talk, walk, solid food) considerably faster than the now 2 (almost 3) year old. He's desperately trying to keep up with his older brother. They chase each other all over the house, they take turns locking each other in the pantry. Just today we found the young one half-way up the stairs! In a day he's gone from sitting on the first stair to going half-way up the flight!

DSC_0123DSC_0122DSC_0117

DSC_0113DSC_0112

DSC_0121DSC_0119DSC_0118

What a joy it is to watch these little men develop into bigger men.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

ASP.NET MVC and the new IIS7 Rewrite Module

October 10, '08 Comments [9] Posted in ASP.NET | ASP.NET MVC | IIS
Sponsored By

Last year I noticed that there were 11 ways to get to my blog. Literally 11 different URLs and it wasn't helping me my ranking in the search engines. I wrote about this in detail and how I used ISAPI_Rewrite to fix it up.

Fast forward to this year and the IIS7 team has been taking advantage of IIS7's modular design to release a bunch of new modules out-of-band.

Both the newest ISAPI_Rewrite and Apache's standard mod_rewrite module uses distributed configuration files or .htaccess files.

Here's just part of my .htaccess file that makes sure that all the incoming URLs end up at the final canonical http://www.hanselman.com/blog/

RewriteRule /blog/default\.aspx http\://www.hanselman.com/blog/ [I,RP] 
RewriteCond Host: ^hanselman\.com
RewriteRule (.*) http\://www.hanselman.com$1 [I,RP]

RewriteCond Host: ^computerzen\.com
RewriteRule (.*) http\://www.hanselman.com$1 [I,RP]

RewriteCond Host: ^www.computerzen\.com
RewriteRule (.*) http\://www.hanselman.com/blog/ [I,RP]

After you've installed the IIS7 Rewrite module, you can bring rules in a couple ways. The nicest is by importing them directly. Notice the tree view in the screenshot below. It gets updated in as you type.

Note that the importer only really understands rules in the mod_rewrite syntax. It doesn't fully support ISAPI_Rewrite so some things like Host: and [I] aren't supported in this release, but I'm hoping (and I've formally asked) that they'll support them for the final RTW (Release to Web). If you have ISAPI_Rewrite rules, you can either convert them then manually edit them to tidy up (what I did), or you can convert them to mod_rewrite syntax first.

For example, in the rule importer UI I could have replaced the ISAPI_Rewrite directive "Host:" with "%{HTTP_HOST}" and "[I]" with "[NC]" (meaning case insensitive). Or, I can just edit the incorrectly imported rules.

image

This is useful for importing existing rules like mine, but it's still hard since we're talking obscure formats left and right. There's also an Add Rule wizard:

Add rule(s)

It's REALLY easy with the User Friendly URL dialog to interactively create mappings between the URLs your app uses and the URLs you want. See in the screenshot below how the combo-box is dynamically populated based on the example I put in the top text box?

Add rules to enable user friendly URLs (2)

The User Interface for this module is surprisingly deep in functionality. There's a Regular Expression tester built into it, which makes Regular Expressions suck by about -2.

Test Pattern

ASP.NET MVC and SEO

I noticed a post by Jason Young recently on ASP.NET and SEO (Search Engine Optimization). He's concerned about trailing slashes

Ultimately I don't think it's that big of a deal since the URLs that your application generates are always consistent. Your app is what teaches search engines what to ask for. As long as your application is generating URLs that look the way you want them, you're cool.

The only real problem happens when other humans link to you and they make a mistake. Perhaps they include a trailing slash when you don't want one. Still, not a huge deal, but if you feel strongly about it, that's where a rewrite module comes in useful. I think that the Rewrite module would fit Jason's requirements.

Matt Hawley at eXcentrics World wrote a Legacy Route using ASP.NET Routing which is a clever idea as well. He could have certainly used this Rewrite Module, but ultimately as long as you're returning HTTP 301's (redirect permanent) or HTTP 302 (temporary redirect) as you fine appropriate, then use what makes you happy.

What's really important is that both these guys respect the permalink. A 404 is never a good thing.

Every site is different, but if I add a basic rule like this to my ASP.NET MVC site…

image

…and request http://localhost/rewritetest/Home/Index, the resulting HTTP Headers look like this, as the module forces the trailing backslash (of course you could also force NO backslash if it makes you happy):

GET /rewritetest/Home/Index HTTP/1.1
Accept-Encoding: gzip, deflate
Host: localhost
Connection: Keep-Alive

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=UTF-8
Location: http://localhost/rewritetest/Home/Index/
Server: Microsoft-IIS/7.0
X-Powered-By: ASP.NET

I'm not a regular expression expert, but searching the web for "mod_rewrite" rules will keep you busy for next 50 years. Here my favorite reference for .htaccess and mod_rewrite rules.

Learning the basics of the IIS7 Rewrite Module:

Functionality reference

Video walkthrough

Enjoy.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.