in

CodeSmith Community

Your Code. Your Way. Faster!

Paul Welter

  • PLINQO - CodeSmith LINQ to SQL Templates

    PLINQO, which stands for Professional LINQ to Objects, is a collection of CodeSmith templates that are meant to replace and extend the LINQ to SQL designers that are included with Visual Studio 2008.

    Features

    • Generate or update a LINQ to SQL dbml file from a database schema.
      • Includes all tables, stored procedures, functions, and views with the ability to exclude objects based on regex patterns.
      • Ability to automatically remove object prefix and suffixes (ie. tbl_ and usp_).
      • Dbml file can still be customized with the normal Visual Studio 2008 designer.
      • Dbml file can be refreshed based on the current database schema without losing customizations. (See Safe Attributes)
    • Generation of the LINQ to SQL DataContext class.
    • Generation of the LINQ to SQL entity classes.
      • Generates one file per entity instead of one massive file.
      • Generates partial classes where custom code can be written and won't be overwritten.
      • Generated entity files are added to the project as code behind files to their corresponding custom entity files.
    • Generation of entity manager classes.
      • Adds customizable business rules engine to enforce entity validation, business and security rules.
      • Provides access to common queries based on primary keys, foreign keys, and indexes.
      • Common queries are exposed as IQueryable so they can be extended.
    • All templates can be customized to meet your needs.

    Read More

    http://community.codesmithtools.com/blogs/pwelter/archive/2007/08/08/plinqo.aspx

    Download 

    http://www.codeplex.com/codesmith/Release/ProjectReleases.aspx 

  • PLINQO - Supercharge LINQ to SQL

    Table of Contents

    Overview

    PLINQO, which stands for Professional LINQ to Objects, is a collection of CodeSmith templates that are meant to replace and extend the LINQ to SQL designers that are included with Visual Studio 2008.

    Features

    The templates have the following features.

    • Generate or update a LINQ to SQL dbml file from a database schema.
      • Includes all tables, stored procedures, functions, and views with the ability to exclude objects based on regex patterns.
      • Ability to automatically remove object prefix and suffixes (ie. tbl_ and usp_).
      • Dbml file can still be customized with the normal Visual Studio 2008 designer.
      • Dbml file can be refreshed based on the current database schema without losing customizations. (See Safe Attributes)
    • Generation of the LINQ to SQL DataContext class.
    • Generation of the LINQ to SQL entity classes.
      • Generates one file per entity instead of one massive file.
      • Generates partial classes where custom code can be written and won't be overwritten.
      • Generated entity files are added to the project as code behind files to their corresponding custom entity files.
    • Generation of entity manager classes.
      • Adds customizable business rules engine to enforce entity validation, business and security rules.
      • Provides access to common queries based on primary keys, foreign keys, and indexes.
      • Common queries are exposed as IQueryable so they can be extended.
    • All templates can be customized to meet your needs.

    Quick Start

    Use the following steps to get started using the Linq to Sql templates.

    1. Create a new Class Library project in Visual Studio 2008.
    2. Add a new CodeSmith project file to the Visual Studio project. (Figure 1)
      Figure 1 - Sample Solution
    3. Add a new Output to the project file for the Dbml.cst template. (Figure 2)
      Figure 2 - Add Dbml Output
    4. Add another Output to the project file for the Entities.cst template. (Figure 3)
      Figure 3 - Add Entities Output
    5. Optionally, Add an Output for the Managers.cst template. (Figure 4)
      Figure 4 - Add Managers Output
    6. Set the Sample.csp -> Output Options -> Add Outputs to Project to unchecked.  The templates update the project for you.
    7. Finally, Generate the Outputs. (Figure 5)
      Figure 5 - Sample Generated

    Dbml.cst Template

    The Dbml.cst template is used to create a LINQ to SQL dbml file.  The file conforms to the Microsoft DbmlSchema.xsd schema.  This is the same document that the LINQ to SQL designer uses.  The generated dbml file from this template can also be edited from the LINQ to SQL designer. 

    The template will create a new file if it doesn't exist.  If the file does exist, the template will read it in and update it.  This allows you to make changes to the file and not have it overwrite if the template is re-ran.  However, only some of the attributes are safe from overwriting.  Here is a list of safe attributes.  They will be listed as an xpath.

    Safe Attributes to change in the Dbml file ...

    • Database/@Class - The name of the DataContext class that will be generated.
    • Database/@EntityNamespace - The namespace for the entity classes.
    • Database/@ContextNamespace - The namespace for the DataContext class.
    • Table/@Member - The property name for the table in the DataContext class.
    • Type/@Name - The name of the entity class.
    • Column/@Member - The property name for the column in the entity class.
    • Column/@Storage - The private field LINQ to SQL will us to assign values to.
    • Association/@Member - The property name for this association.
    • Association/@Storage - The private field LINQ to SQL will us to assign values the association to.
    • Function/@Method  - The name of the method for the database procedure.
    • Parameter/@Parameter - The method argument name that maps to the database procedure parameter.

    Warning: Be aware that the template will drop tables, columns and associations that it did not find in the database.

    Properties on the Dbml.cst template:

    Property Description
    CleanExpression List of regular expressions to clean table, view, column and procedure names.  Any matched text found will be removed from the name.
    IgnoreList List of regular expressions used to ignore tables, views and procedures when generating mapping.  Any database objects that match one of these regular expressions will be ignored.
    IncludeFunctions Include stored procedures and user functions in mapping.
    IncludeViews Include views in mapping.
    SourceDatabase The source database to generate the dbml file for.
    ContextNamespace The namespace to use for the context class file.
    EntityNamespace The namespace to use for the entity class files.
    DbmlFile The path to the dbml file to generate.

    Entities.cst Template

    The entities template generates the entity classes needed by LINQ.  The classes are generated from a dbml file.  You can modify the names for classes and properties by editing the dbml file.  See Dbml.cst for a list of safe attributes to change in the dbml file.

    The template will generate 2 files for every Type in the dbml file.  One file will be the generated partial class that can not be changed as it is overwritten when the template is re-ran.  It will have the following file name... <entity>.Generated.cs

    The second file is a partial class that can be modified as it will not be re-generated.  You can implement the partial methods in this file.  Some partial method stubs are created by default. This file will be named... <entity>.cs

    If you set the project file property on the template, the generated files will be added to the project.  The file that can not be modified will be hidden under the file that can be changed.

    Properties on the Entities.cst template:

    Property Description
    DbmlFile The path to the dbml file used generate the entities from.
    OutputDirectory The folder to save the generated files.
    ProjectFile The Visual Studio project file to add the generated files to.

    Managers.cst Template

    The manager template is for helping you get started with business logic for the LINQ entities.  The managers will have common queries that are created from keys and indexes on the table.  The manager will also have rules for the entity properties to make sure required fields are not null and that the length of a string does not exceed the max length the column allows.

    The template works by creating a second DataContext class that has a Manager property.  The manager will then have a property for each entity that has a manager. Here is a sample of the syntax for using the managers:

    SampleManagerContext db = new SampleManagerContext();

    // use the primary key

    Task task = db.Manager.Task.GetByTaskID(taskId);

    // use a foreign key

    var myTasks = db.Manager.Task.GetByAssignedID(userId);

    // the methods return IQueryable so you can add expressions

    var openTasks = db.Manager.Task.GetByStatusID(statusId).OrderBy(t => t.CreateDate);

    The manager also provides a business rules engine to your entities. In addition to the default validation rules that are generated, you can add custom rules by implementing the AddRules partial method in the custom entity class.

    static partial void AddRules()

    {

        // Rule allows the Name property to be a max of 150 characters.

        RuleManager.AddShared<Task>(new LengthRule("Name", 150));

        // Rule that validates the value of the property using regex.

        RuleManager.AddShared<Task>(new RegexRule("Name", ".*"));

        // Rule allows only users in certain security roles to update.

        RuleManager.AddShared<Task>(new UpdateRule(

            new string[] { "Administrator", "Updaters" }));

    }

    Properties on the Managers.cst template:

    Property Description
    SourceDatabase The source database to keys and indexes from for generating the manager classes.
    DbmlFile The path to the dbml file used generate the manager classes from.
    ManagerContextName The class name of the DataContext that supports the managers.
    ManagerDirectory The folder to save the generated manager files.
    ManagerNamespace The namespace to use for the generated manager class files.
    ProjectFile The Visual Studio project file to add the generated files to.

    Known Issues

    • The generated DataContext does not set the connection string like the LINQ to SQL designer

    Roadmap

    • Improve manager template
    • Unit test generation
    • Web service generation
    • ASP.NET, Winforms and WPF UI generation
    • Visual Basic support

    Download

    Download the latest release from CodePlex.

     

  • Introduction to CodeSmith Project Files

    Introduction to CodeSmith Project Files

    Mapping File SettingsOverview

    A new feature in CodeSmith 4.0 is the ability to manage groups of CodeSmith templates and their outputs with a single file called a CodeSmith Project. CodeSmith Projects enable you to define and run an entire code generation process quickly and easily using the environment of your choice. They were designed with flexibility in mind to let you define the way you work.

    This introduction will show how to use a csp (CodeSmith project) to organize your code generation in a development environment. The example will use the sample Wilson ORMapper templates that are included in CodeSmith.  To use the generated code, a copy of the Wilson ORMapper is needed.

    Creating the CodeSmith Project File

    The ORMapper templates are split into three separate groups of templates.  The first set of templates is the MappingFile.cst.  Use this template to start out your csp.

    The first step is to  load up CodeSmith and select the Mapping.cst template. Set the properties as needed.  This example will use the sample Petshop database that comes with CodeSmith.

    Once you have the properties values set, click the Save icon.  This will create the start of a csp file.

    Managing the CodeSmith Project File

    Now use the Explorer context menu on the csp file and choose Manage Outputs.  In the manage outputs dialog, add the second template that is need for the ORMapper.  For this example, add the CSharp.ClassGenerator.cst template.  Set the properties values for the template and click ok to close the dialogs.

    Manage Outputs

    Add Template to Project

    Generating with a CodeSmith Project

    Now the csp file has been created, it can be used to generate code.  There are several ways to generate with the project file, see Using a CodeSmith Project to Generate Anywhere in the User's Guide.

    Generate Code

    CodeSmith Project in Visual StudioVisual Studio and CodeSmith Project Files

    CodeSmith 4.0 has a new Visual Studio addin that allows you to use a csp right in Visual Studio, see Using a CodeSmith Project inside Visual Studio in the User's Guide.  Including the csp file in Visual Studio will help to keep the project clean and make it much easier to re-generate code when needed.  The csp file can be added to the solution as a Solution Item or to a project directly.  When the csp is added to a C# or VB project, more options are available, including adding the outputs to the project. 

    In the example above, the created Petshop.csp file can be added a Petshop Visual Studio solution.  Now, any time there is database change, the Petshop.csp file can regenerate the ORMapped class files savings a ton of time.

    Conclusion

    The CodeSmith Project feature makes automating your code generation process really easy and consistent whether you are working from inside of Visual Studio 2005, MSBuild, Windows Explorer, a command line / batch file, or CodeSmith itself.

  • Tips & Tricks: Debugging

    Overview

    CodeSmith supports debugging by using the CLR's Just-in-Time debugger.  This article will show some tips and tricks in setting up CodeSmith templates to use the debugger.

    Allow Debugging in Template

    The first step to allow debugging a template is to set the Debug attribute on the CodeTemplate declarative to true.

    <%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="True" %>

    Setting a Break Point

    In order to get the Just-in-Time debugger to load and stop at a point in your code, you need to use the Debugger.Break() statement.

    Debugger.Break();

    If you are setting a break point in a code behind file or included class, you need to include the namespace for the debugger class.

    System.Diagnostics.Debugger.Break();

    Using the Debugger

    When you execute a template in CodeSmith Studio and it encounters a break point, you will see the following dialogs.

    User Defined Break Point
    When you see the user-defined breakpoint dialog, choose Debug.

    Just-In-Time Debugger
    Choose the Debugger you want to use.

    Microsoft CLR Debugger

    Debugging in Windows Vista

    There are some problems with using the Just-In-Time debugger in Windows Vista.  First you need to make sure you have all the latest service packs installed. Next, the debugger in Vista will cause CodeSmith to hang when you finish debugging.  You can work around this issue by updating the Just-In-Time debugger setting DbgJITDebugLaunchSetting.  The setting is found in the registry at [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework].  Change the value of DbgJITDebugLaunchSetting to 2.  This will cause the debugger dialog to be displayed immediately when your code hits a breakpoint.  This will also allow control to return to CodeSmith when you continue the execution of the template from the debugger.

    Troubleshooting

    • If you are having trouble with the debugger, try using the CLR debugger as that tends to work better.
    • If you are getting the message, "There is no source code available for the current location.", you need to change the default editor for .cst files in Visual Studio to be the "Source Code (Text) Editor".
    • If you are having further issues in Vista, make sure to run CodeSmith with full administrator rights by right clicking and choose run as administrator.
  • CodeSmith 4.0 Public Beta Released

     

    CodeSmith 4.0 Beta 2 has been released and is now available to the public.  Here are just a few the new capabilities in CodeSmith 4.0:

    • CodeSmith Projects (.csp) - This feature makes automating your code generation process really easy and consistent whether you are working from inside of Visual Studio 2005, MSBuild, Windows Explorer, a command line / batch file, or CodeSmith itself.
    • ActiveSnippets - Imagine Visual Studio 2005 snippets, but with the full power of CodeSmith available to execute any logic or access any complex metadata (including database schema and xml data) to control the output of your snippets.
    • CodeSmith Maps (.csmap) - This feature will allow you to create dictionary style maps of things like SQL to C# data type mappings.
    • .netTiers 2.0 - The .netTiers templates have been greatly enhanced and included with CodeSmith 4.0.
    • Extended Property Management - You can now edit and add new schema extended properties inside of CodeSmith Studio.
    • Property Persistence - CodeSmith now remembers the property values from the last time you executed a template.

    You can read the announcement here.

Copyright © 2008 CodeSmith Tools, LLC
Powered by Community Server (Commercial Edition), by Telligent Systems