This is a mirror of official site: http://jasper-net.blogspot.com/

C# Code Generation

| Wednesday, December 1, 2010
Code generation is a big part of most modern frameworks. .NET is full of code generators that you've probably used - maybe without even knowing it. XAML files are converted to .g.cs files that are then fed to the compiler at compilation time. WCF is bundled with a code generator that will convert a WSDL file to a client to easily connect to existing web services. Today's tutorial will cover how to use objects provided by the .NET framework to build your own code generator.

The code we're going to generate today won't be especially useful, however it will demonstrate a lot of the available functionality. I'm going to use C# to generate another C# class that can hold part of someone's Twitter feed.

The .NET namespace that makes all this possible is System.CodeDom. Much like the name implies, these classes allow you to build a "DOM" of class hierarchies and then dump them out to text.

The first thing you should check out before starting is a Twitter feed - I would suggest Switch On The Code's. There's a lot of available elements in a feed, however I'm only really interested in a couple for this tutorial - date, text, and source.

All right, let's start generating some code. Like any other C# class, we're going to need to start with a namespace.

using System.CodeDom;
using Microsoft.CSharp;
using System.IO;

namespace CodeGeneration
{
 class Program
 {
   static void Main(string[] args)
   {
     CodeCompileUnit compileUnit = new CodeCompileUnit();

     // Add a namespace.
     CodeNamespace twitterNamespace = new CodeNamespace("TwitterClient");
     compileUnit.Namespaces.Add(twitterNamespace);

     // Write the code to a file.
     using (var fileStream = new StreamWriter(File.Create(@"C:\outputfile.cs")))
     {
       var provider = new CSharpCodeProvider();
       provider.GenerateCodeFromCompileUnit(compileUnit, fileStream, null);
     }
   }


Read more: Switch on code

Posted via email from .NET Info

0 comments: