.NET
  Home arrow .NET arrow Introducing Code Generation
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

Introducing Code Generation
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 9
    2004-12-08

    Table of Contents:
  • Introducing Code Generation
  • Generating a Simple Program
  • Creating the Template
  • Running the Template
  • Plain-Vanilla Code
  • Picking the Right Mechanism
  • Breaking Down the Code Generation Process
  • Writing Handcrafted Code
  • Tying It Together: Implementation and Testing
  • The Strongly Typed Dataset
  • Performing Real-World Code Generation
  • Generating a Simple Class via CodeDOM
  • Generating a Simple Class via XSLT Templates

  • 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


    Introducing Code Generation


    (Page 1 of 13 )

    Code generation--or code that writes code--can speed up the creation of new applications by letting you automate much of the process. Kathleen Dollard explains how to build the templates behind the process. (This article is from chapter one of Code Generation in Microsoft .NET by Kathleen Dollard, Apress, 2004, ISBN: 1590591372.)dollardIntroducing Code Generation Principle #1: You have control of the templates that generate your code and can change them as required.

    CODE GENERATION IS CODE THAT WRITES CODE.

    By letting you automate the creation of a large portion of your application, code generation offers a radical shift in development. In addition to the obvious benefit of turbo-charging your development, code generation lets you maintain consistent code quality and allows your code to evolve quickly in response to metadata changes (including database changes). Code generation lets you extend reuse to include code with similar patterns, as well as code with identical code segments. The result is increased speed, reusability, agility, and consistency in your application development.

    In the end, code generation can be as simple as supplying an Extensible Markup Language (XML) file with a few pieces of information and clicking a button, and— voilà!—the repetitive portions of your application (stored procedures, middle tier, and user interface) are complete and ready for you to extend with your own customization. The purpose of this book is to teach you the process that lies behind that click. It’ll seem complex at times, but don’t lose sight that you rarely deal with the complexity of the underlying tools and only occasionally deal with the complexity of the templates themselves. Code generation is about building these once and reusing them many, many times—within and between applications.

    ***********************

    NOTE Both code generation and object-oriented inheritance allow you to reuse common functionality. They differ in that inheritance only allows you to reuse specific code segments that you can then override or modify in the derived class. Code generation allows you to reuse patterns in your code as well as code segments. Code generation and object inheritance are very effective when used together.

    Generating code isn’t new. What’s new is that it actually works in the real world. In the past, I haven’t been excited about using code generation supplied with frameworks and templates because they couldn’t provide the control and flexibility I demanded. I felt like I was in a whitewater rapid without a paddle, rushing along quickly but quite uncertain which boulder I might hit. I even know one shop that abandoned its multiyear commitment to stored procedures, replacing them with dynamic Structured Query Language (SQL) to accommodate the limitations of a purchased framework.(1)

    Sure, we could have done our own code generation three or even ten years ago, but code generation used to be hard work, and we didn’t have enough collective knowledge to recognize patterns easily. A number of recent developments, including XML support, inheritance features in .NET, XSL Transformations (XSLT) processing, and wide-scale pattern recognition, make the time ripe for code generation to become part of your development process. I’ll show you how to incorporate your own code generation, meaning you stay in control of the architecture you’re implementing. I’ll provide tools that support whatever techniques and patterns you use, and I’ll provide samples you can use to generate applications as soon as you understand the underlying techniques. I’ll share those techniques, along with guidelines for making code generation a valuable part of your development strategies. Those guidelines will include steps and principles that keep your code generation effective and high quality.

    You can use several mechanisms for code generation. In this chapter, I introduce the three most important approaches for application code generation in .NET, along with the benefits and drawbacks of each. This lets you compare them and decide which fits you best. Chapter 3 has further details of using each mechanism. Continuing to walk through all three would be too cumbersome, and I want to focus on the underlying process common to them all. So, in later parts of the book, I’ll focus on one mechanism.

    In addition to showing the mechanisms, this chapter presents the five steps you’ll use to make code generation a coherent process. Chapters 2–5 cover these steps in more detail. But, before I go any further in describing the five steps to code generation, I want you to see what code generation looks like. Generating a “Hello World” application in each of the three mechanisms illustrates code generation in its barest form.

    ***************

    1. The point here isn’t whether stored procedures or dynamic SQL is a better approach but that critical decisions such as this should be made by your own organization, not a vendor.

    Exploring Mechanisms for Code Generation

    The mechanisms for code generation in this chapter include an obvious approach, a Microsoft-provided approach, and a novel approach. The obvious approach is simply to write code that outputs code as text to a stream—.NET code directly writing .NET code. I call this brute-force code generation. I don’t intend that name to be taken negatively. This is the direct approach of simply opening a stream and writing out code.

    Microsoft provides the CodeDOM mechanism, which is designed specifically for generating code. The CodeDOM provides a layer of abstraction that lets you output code in C#, Visual Basic .NET (VB .NET), J#, and perhaps additional languages in the future—from the same template code base. Most developers don’t have a compelling reason to output code in multiple languages, and you pay for this flexibility with significantly increased complexity and reduced capabilities.

    The novel approach uses XSLT templates. You can use XSLT to create any type of text output, including .NET code. Although all three code generation mechanisms have their place, I’ll show you why I think XSLT templates are the preferred solution for many code generation scenarios. Later examples in the book use XSLT templates, but the focus remains on the underlying ideas that are valid with any approach to code generation.

    You could also create variations of these approaches. For example, I’ve worked a little on a preprocessor for XSLT. I’ve also worked with an alternate brute-force approach using token replacement that was simpler than XSLT. The complexity of XSLT makes such a simplified solution appealing. However, as you deal with more complex templates, you’ll quickly move beyond token replacement to template logic for loops, conditionals, functions such as string manipulation, and calculations. You wind up rebuilding much of XSLT with a proprietary syntax. If you want to do code generation with any variation of the techniques in this book, you can extend the discussion to your scenario. This works because much of the book isn’t about how you actually output code; it’s about how you construct the surrounding processes to make code generation highly effective, and it’s about what to consider when building any set of application templates.

    In each of the three approaches, a pattern is expressed based on the meta-data provided. Metadata is the information specific to your application that’s collected from your database structure, entered manually, or retrieved from other sources. Chapter 2 discusses a variety of metadata sources. The pattern for your code is contained in an XSLT stylesheet for XSLT code generation and a dedicated class for brute-force or CodeDOM generation. In all cases, I use the phrase template to refer to whatever holds the pattern, whether it’s an XSLT template or a .NET class.

    Mechanisms Not Covered

    Visual Studio and related technologies present many options for generating code. Because this book sets out to change the way you write applications by giving you a full-scale development approach, I’ll only cover those mechanisms that work well for full-scale application development in at least some scenarios. But you might be curious about other approaches.

    .NET provides the Reflection.Emit namespace that allows you to emit Microsoft Intermediate Language (MSIL). All .NET languages compile to MSIL for deployment. The Just-In-Time ( JIT) compiler that translates your MSIL into machine code takes MSIL as input. Because MSIL is designed to make the JIT compiler’s job easier, MSIL has more similarities to machine language than to high-level human readable languages such as C# and VB .NET. In order to use Reflection.Emit for code generation, you have to either write your application templates to output MSIL or create your own precompiler. With the great high- level languages, tools, and compilers available, why would you want to work directly with MSIL for general application development? Reflection.Emit might be interesting if you want to generate classes on a small scale at runtime, but features of the CodeDOM also provide runtime compilation.

    The Visual Studio environment exposes an extensibility layer that allows you to access your source code through the Visual Studio automation model. The automation model might be useful if you want to integrate your code generation into the Integrated Development Environment (IDE), but I’m not convinced you’d gain much, and integrating into Visual Studio is really a separate issue from the process of generating code. The Visual Studio code automation model can output C# code but is read only for VB .NET. VB .NET trades outputting code through an automation model for its boatload of cool IDE features.

    Two other approaches are Enterprise Templates and Visio code generation. I skip them because they don’t provide a full cycle of development and regener ation. Without an incredible amount of work, Visio only outputs method stubs, and no amount of work with the current version provides a regeneration cycle. In the future I hope you’ll be able to harvest Unified Modeling Language (UML) metadata from Visio, but even this is quite difficult currently. See the “Additional Reading” section of Chapter 2 if you’re interested in Visio code generation. Finally, the Enterprise Templates feature may play a role in your development, but it’s not a full application approach to code generation. The templates are intended as a starting point and don’t support regeneration.

    Table 1-1 later in this chapter summarizes these techniques, along with the ones I’ll discuss in detail. 

    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

    - Building Applications with Windows Workflow ...
    - Building the Data and Business Layers Using ...
    - 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...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek