.NET
  Home arrow .NET arrow Page 12 - Outputting Code
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
.NET

Outputting Code
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 5
    2004-10-04

    Table of Contents:
  • Outputting Code
  • Understanding Script Directives
  • Understanding Other Features of the Generation Harness
  • Extending the Harness
  • Examining Code Generation Mechanics
  • Exploring Details of XSLT Code Generation
  • Creating Named Templates
  • Creating Match Templates
  • Supporting Stylesheets
  • Exploring Details of Brute-Force Generation
  • Creating a Class
  • Creating the Support Template
  • Understanding Types
  • Building a CodeDOM Graph
  • Building the Code Structure
  • Outputting Assignments
  • Creating Arrays
  • Exploring Other Features
  • Working with the CodeDOM

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Outputting Code - Creating the Support Template


    (Page 12 of 19 )

    The FileOpen method outputs the same file header as the XSLT code generation template. You can see additional supporting methods and the template code that outputs the remainder of the sample in the download from the Web site. The fileName and genDateTime are explicitly passed as parameters. The Split method of the framework splits the import parameter at commas to output separate Imports statements and uses a framework method to retrieve the filename from the full path:

    Public Shared Sub FileOpen( _
    ByVal inWriter As CodeDom.Compiler.IndentedTextWriter, _
    ByVal import As String, _
    ByVal fileName As String, _
    ByVal genDateTime As String)
    inWriter.WriteLine("Option Strict On")
    inWriter.WriteLine("Option Explicit On")
    inWriter.WriteLine("")
    inWriter.WriteLine("Imports System")
    For Each s As String In import.Split(","c)
    inWriter.WriteLine("Imports " & s)
    Next
    MakeRegion(inWriter, "Description")
    inWriter.WriteLine("'")
    inWriter.WriteLine("'" & IO.Path.GetFileName(fileName))
    inWriter.WriteLine("' Last Genned on Date: " & genDateTime)
    inWriter.WriteLine("'")
    inWriter.WriteLine("'")
    EndRegion(inWriter)
    End Sub

    Winding Up Brute-Force Code Generation

    That’s it for brute-force code generation. You can extend these ideas to build any code you want. The key to success is breaking the process down into discrete steps as follows:

    • Break code outputting away from metadata extraction.

    • Split outputting into individual template classes that each output a single file pattern.

    • Within each template class, use an entry-level method.

    • Use a different method for each region.

    • Use additional methods as regions become longer and more complex.

    • Use supporting methods for reuse wherever possible.

    Exploring Details of the CodeDOM

    CodeDOM generation is interesting for a number of reasons. It’s a full abstraction of the nature of programming languages. In other words, it breaks code down into the parts of byte speech—the grammar of your programs. When you write code to this abstraction, a .NET or third-party provider (see footnote 5) can build output code in any target language. It’s also cool that Microsoft provided something developed for its own use. Visual Studio uses CodeDOM generation for the strongly typed DataSet, the class created for each ASPX file, the CodeDomSerilizer, and a few other purposes. If you look at the problems that arise in outputting code for entirely different languages, it’s an amazing piece of software in itself.

    NOTE: The CodeDOMSerializer also uses the CodeDOM. So, if you’re working with CodeDOMSerializer, everything in this section applies, and you may find this tutorial helpful. I’m not discussing details of the CodeDOMSerializer because it isn’t related to application-wide code generation. Instead, it allows you to control the code produced by Visual Studio when it creates the region labeled Windows Form Designer generated region in your form. If you’re interested in using this, you can find articles on the Web that discuss how to tie it to your class using attributes and other unique aspects of convincing Visual Studio to generate your code correctly. Search for CodeDOMSerializer at MSDN or on Google to find more information.

    The CodeDOM has the narrow purpose of outputting code in any language that has a language provider, and Microsoft supplies providers for C#, VB .NET, and J#. (see footnote 6) Unfortunately, the effort you have to go through to achieve this flexibility— the real cost to you—is high. For almost all applications, settle on a language and use one of the other mechanisms for code generation.

    Footnote 5. There aren’t any third-party providers yet, but the CodeDOM is designed for new languages to be incorporated into it.

    Footnote 6. If you’re generating code for J#, please read the “CodeDOM, For Java Language” section in the .NET Help. Among a few other details, you have to reference the language-specific compiler.  

    NOTE: You might not want to flip past this section just yet. If you’ve never chopped up code to see it in the perspective of its atomic grammar units—the adverbs, nouns, and adjectives that make up the grammar of common code—it’s a useful exercise to explore the CodeDOM. You’ll get past differences such as VB .NET’s declaring variables with the name followed by the type versus C# declaring the type followed by the name (Dim iVar As System.Int32 versus System.Int32 iVar). You’ll also discover some of the things your language does for you that exceed interpreting syntax because those things don’t work well via the CodeDOM. Universities often require a compiler course for Computer Science (CS) graduates so they understand the underlying programming “parts of speech” and how they’re put together different ways in different languages. Maybe it’ll help you find a deeper Zen connection with your code. On the other hand, there’s a chance that you’ll never use the information in the rest of this chapter.

    In this section, you’ll find out just how ugly it can be to output via the CodeDOM. If you’re thinking about using the CodeDOM for code generation, you’ll want to be realistic about how much work it takes to use the CodeDOM and the limitations on what you can accomplish. You’ll spend considerably more than twice as much time writing and maintaining the code, compared to the other code generation mechanisms. You’ll see a payoff only when you need to maintain absolute symmetry between your C# and VB .NET output or when maintaining parallel testing is impractical. If that’s the case, you’ll want to use the CodeDOM, and you’ll find a real shortage of information about it. Because of this void, this is a core tutorial to understanding the underlying technology. This basic understanding will open up the CodeDOM Help to you, which in most cases isn’t half bad once you know what you need. I won’t walk through what it takes to create a full class, but you’ll see enough basics to work through building one if you decide to continue with the CodeDOM.

    NOTE: CodeDOM creates plain-vanilla code based on common syntax. Each compiler does a few back flips to make your life as a developer easier. The CodeDOM supports basic syntax, not these extra features. For example, the CodeDOM doesn’t support the Handles clause of VB .NET or its supporting WithEvents. Appendix D covers VB .NET and C# features that you can’t do in the CodeDOM. Much of the missing stuff is specific to one of the compilers and not supported by the other. If you need something other than this plain-vanilla code, you’ll have to extend the CodeDOM, which isn’t for the faint of heart (or you’ll need to use snippets, which are a really nasty construct).

    NOTE: CodeDOM is a write-only technology. If you want to read the structure of existing code, you’ll need to parse the code or explore the automation model of Visual Studio .NET. Named the FileCodeModel, the Visual Studio automation model resides in the EnvDTE namespace. For C#, the FileCodeModel is read/write, but it’s read-only for VB .NET (the current trade-off for some cool VB–-specific development environment features).

    Like the other code generation approaches, there’s no certainty that the code you output will compile. Although the nature of the CodeDOM means certain types of gross syntax errors aren’t going to happen, the CodeDOM leaves you plenty of room to output code that won’t compile in one or more languages or won’t do what you intended when it compiles.

    CAUTION: The CodeDOM will allow you to do dumb things without any complaint. Because of the variety of invalid code it’ll happily generate, test your output by compiling in multiple compilers. It’s not a bad idea to do a code review of a few output files with any of the code generation techniques, but this is especially important with the CodeDOM.

    Using an Object Hierarchy

    At the root of the object model is the CodeDOM graph. The CodeDOM graph is a tree of objects that describes elements of your code in abstract terms. The graph is contained in an object called a CodeCompileUnit, which describes your code in terms of its elemental parts—expressions, statements, members, and so on. Figure 3-2 shows the tree approach of the CodeDOM graph. Each CodeDOM graph outputs one file, but it can contain multiple classes. Using multiple CodeDOM providers, you can create output for this code in multiple languages.

    Dollard

     

    Figure 3-2. The CodeDOM is a tree of code elements.

    NOTE: It’s a little confusing that the terms CodeDOM graph and CodeCompileUnit are so closely related. To be precise, the CodeDOM graph is the abstract hierarchy of code elements, and the CodeCompileUnit is the specific class whose objects contain this hierarchy. But in practice, you can probably treat these terms as being synonymous.

    NOTE: The CodeDOM parallels reflection in that they both work with abstractions of your code. But the CodeDOM is primarily a mechanism for creating and outputting code, and reflection is primarily a mechanism for retrieving information about an existing assembly. Reflection is also assembly focused, but the CodeDOM is organized in terms of .NET namespaces—with a collection of namespaces making up the CodeDOM graph.

    Figure 3-3 shows key elements of the CodeDOM. Namespaces contain type declarations, types contain members, and so on. I excluded a lot of information to keep this figure simple. The interesting part of the CodeDOM starts with the CodeMemberMethod. The CodeEntryPoint, CodeConstructor, and CodeTypeConstructor derive from CodeMemberMethod. The CodeConstructor is the instance constructor, and the CodeTypeConstructor is the Shared or static constructor for the type. These four methods, along with the closely parallel CodeMemberProperty, contain Statements. At the statement level, you begin to break your code down to a molecular level that may be unfamiliar to you. Looking at a human language analogy, the statement is the sentence, the method is the paragraph, the class is the chapter, and the assembly is the book or volume. Applications can consist of many volumes. 

    Dollard

    Figure 3-3. An object model of part of the CodeDOM.

    This chapter is from Code Generation in Microsoft .NET by Kathleen Dollard (Apress, 2004, ISBN: 1590591372). Check it out at your favorite bookstore today.

    Buy this book now.

    More .NET Articles
    More By Apress Publishing


     

    .NET ARTICLES

    - The Transformed XML Explorer in MFC
    - List Control and Property Grid with the MFC ...
    - Font, Shell and Masked Edit Controls for MFC
    - Color, Link and Image Editor Controls for M...
    - New Controls for MFC
    - The Windows Ribbon Framework
    - Markup Language for the Ribbon Framework
    - Visually Upgrade Your MFC Project
    - New Features for the Statusbar in MFC
    - Working with the Statusbar in MFC
    - Iron Speed Design v60 Review
    - Binary and XML Serialization
    - Using CrystalReportViewer to Display Crystal...
    - Creating Summary .Net Crystal Reports
    - More on Commands, Input and the WPF





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    Stay green...Green IT