Microsoft Cloud Authors: Andreas Grabner, Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

My Generation: A Fresh Approach to Code Generation

The makings of a great code generator

My Generation is a very flexible, powerful code generator and it's 100% free. MyGeneration executes templates to transform database meta-data or schemas into object-oriented architectures, stored procedures, XML, HTML, ASP.NET pages, and more. Templates can be written in VBScript, JScript, C#, and VB.NET. All four template languages provide the ability to toggle between literal content and executable code via the standard <% %> tags. The two scripting languages have full access to COM via CreateObject() and the two .NET languages have full access to the .NET namespaces. Anything is possible! Templates are a very flexible way to generate code, as opposed to wizards or other fixed user interfaces that would hem you in and force you to work in a certain way.

As its main source of input, MyGeneration uses the metadata within your DBMS system. This metadata is, in many ways, an excellent description of your application. This is especially true when creating n-tiered applications that have a data-access layer and a business logic layer. MyGeneration can easily generate your particular n-tiered architecture or you can use the architecture shipped with MyGeneration which is named dOOdads (see Figure 1). MyGeneration supports Microsoft SQL, Microsoft Access, Oracle, IBM DB2, MySQL (instances running on Microsoft platforms), PostgreSQL, FireBird, Interbase, SQLite, and VistaDB.

MyGeneration ships with many sample templates, including templates that can generate the dOOdads architecture in C# or in VB.NET. However, you can think of MyGeneration as a clean sheet of paper ready to record your thoughts and generate whatever you need. MyGeneration Software even hosts an online template library that allows its users to register and publish templates to be shared with other users. Some of the templates published include templates that generate ASPX pages, ASCX controls, Gentle.NET classes, XML Documents, SQL Migration scripts, and more.

So what does a template actually look like? The code in Listing 1 is a sample template that will write out all of the column names from the SQL Server Northwind Employees table, their C# language types, and their driver types. After looking at the results of Listing 1, it should become clear how easy it would be to make an object that encapsulated the Employees table.

One of the most unique features of MyGeneration is that it allows you to create your own user interface for your template within the template itself. A MyGeneration template consists of two parts: the template body and the template user interface. MyGeneration first executes the user interface section of the template and then ensures that the user selections are made available to the body portion of the template, which is executed next.

In Figure 2 the template scripting engine (or body) is set to Microsoft Script, which means it will be written in either JScript or VBScript. However, the GUI scripting engine is set to .NET Script, which means it will be written in either C# or VB.NET. Notice how you can mix and match engines and languages to suit your needs within the same template. Using ".NET Script" as your user interface language will grant you full access to the System.Windows.Forms namespace.

The code used to create the user interface shown in Figure 3 was written in VBScript and is actually embedded in the template itself. Controls are added to the template portion of a script as in the following:

ui.AddLabel "lblNamespace", "Namespace: ", "Provide your objects namespace."
ui.AddTextBox "txtNamespace", "Your.Namespace", "Provide your objects namespace."

Later, in the body of the template, the input is gathered as in the following:

Dim namespace
namespace = input.Item("txtNamespace")

There is a finite set of controls that you can use in your VBScript or JScript user interfaces. For instance, the DataGrid is not available. However, remember that MyGeneration's .NET template languages will effectively grant you full access to the System.Windows.Forms namespace, allowing you to create your own fully functional user interface complete with DataGrids and third party controls. Are you thinking of creating your own Object Relational Mapping (ORM) tool and an accompanying architecture? MyGeneration supplies everything that you need.

Mapping DBMS Types
MyGeneration allows you to map your native DBMS data types to any desired computer language type and to any desired driver type. Mappings are entered in the dockable windows shown in Figure 4. For example, you can map the Microsoft SQL Server bit data type to the C# bool type or to the VB.NET Boolean data type. You can also map the bit type to the SqlClient type of SqlDbType.Bit. Once mapped, during script execution you can access the Column.LanguageType or the Column.DbTargetType property to retrieve the proper value for any given column or stored procedure parameter type. MyGeneration ships with preset mappings for most DBMS systems into VB.NET and C#. However, there is nothing to prevent you from adding entries for J#, Java, or other languages.

MyGeneration Plugins
You can expand MyGeneration via its plug-in architecture. A plug-in is simply a .NET class library with no user interface that provides some kind of service to MyGeneration templates. In fact, the MyMeta metadata engine is a plug-in. Below is a snippet from the plug-in XML file showing the MyMeta plug-in entry. Recall from Listing 1 that we accessed the MyMeta object without actually creating it in our template. This is because each plug-in is available to all templates as an intrinsic object:

    <IntrinsicObject assembly="MyMeta.dll" classpath="MyMeta.dbRoot" varname="MyMeta" />

The assembly attribute references the DLL and the classpath attribute is the .NET class that will be instantiated to represent the intrinsic object. The varname attribute is the name of the variable as it will appear to the template. The plug-in architecture offers all kinds of opportunities.

The MyMeta Plug-in
The MyMeta engine is a plug-in that provides extensive metadata from many different DBMS systems. Figure 5 is an image of the MyMeta Properties window displaying many of the properties available for a column that is contained in a table or a view. The MyMeta Browser shown in the treeview in Figure 1 and the MyMeta Properties shown in Figure 5 are synchronized. To see the properties of an object in the MyMeta Properties window, you simply click on the desired object in the MyMeta Browser.

The MyMeta plug-in was written in C# and is exposed via COM interop to give VBScript and JScript access to the metadata. The metadata provided by the MyMeta plug-in is exposed via interfaces. For instance, a column in a table or a view is represented by the IColumn interface. The IColumn interface remains the same across all DBMS systems. As mentioned earlier, MyGeneration ships with a free .NET architecture named dOOdads. A single template creates dOOdad business entities for Microsoft SQL, Microsoft Access, Oracle, and Firebird. This is possible because the MyMeta plugin makes all DBMS systems appear the same through these interfaces. The interfaces supported by MyMeta are as follows: IDatabase, ITable, IView, IColumn, IIndex, IForeignKey, IProcedure, IParameter, IResultColumn, and IDomain. Each of these interfaces also has a corresponding collection. For instance, IColumns is the collection for IColumn.

Preserving Hand-Coded Modifications
The MyGeneration dOOdad business entities use inheritance to avoid regeneration problems. A generated dOOdad (C# or VB.NET class) is abstract and is never hand edited. Instead a class is derived from the generated class, thereby making it concrete. It is within the concrete class that users add custom business logic. Because the generated or abstract class is never hand edited, there are no regeneration problems. However, HTML, stored procedures, XML, and other formats really don't have the inheritance option. There will be times when you just have to hand edit generated files. MyGeneration has a solution for this situation: Preserve Regions.

Suppose you want to generate, insert, and update stored procedures for all of the tables in your database. This is no problem for MyGeneration. However, suppose that a handful of these stored procedures need to write to an audit table when a record is updated. There is no metadata lying around in your DBMS system (accessible in your template) that will relay this requirement. One option is to simply hand code it into the generated stored procedures. But what if you later change a column in one of your tables, and you have to regenerate a stored procedure that you have hand edited? Will you lose your changes? Certainly not. You would protect any hand-coded areas with a Preserve Region.

The first step is to register your Preserve Region format with your template. This is done by giving it the file name of the original file on disk (usually derived from the table name during script execution) and the comment begin and end blocks. Everything between the comment begin and end blocks will ultimately be preserved. In this case, you are trying to preserve hand-coded comments in an SQL Server stored procedure. Thus, you would use SQL's /* */ syntax. The Preserver Region is registered as follows:

output.setPreserveSource("proc_" + objTable.Name + "_Update", "/o", "o/")

After you have registered the Preserve Region format, you are ready to use one or more Preserve Regions within your template. In this case the name of the Preserve Region is "AuditTrail." To actually declare a Preserve Region you would use this syntax in the spot within the template where you want to make your hand edits:


This will result in the following code being injected into your output:

/o PRESERVE_BEGIN AuditTrail o/
/o PRESERVE_END AuditTrail o/

You can now edit your newly generated stored procedure on disk and add code within the Preserve Region. Notice that this is done in the generated code itself, not in the template:

/o PRESERVE_BEGIN AuditTrail o/
/o PRESERVE_END AuditTrail o/

The next time you regenerate the stored procedure, everything within and including the Preserve Region will be preserved. You can even move the output.preserve("AuditTrail") region around in your template, and your custom code will move to the new location the next time you regenerate. If you remove the output.preserve("AuditTrail") region from your template, the next time you regenerate that region will be gone. There is an example of this in the "HTML Database Report" template provided with MyGeneration, but it uses the HTML comment syntax.

Project Files
For your application you might need to generate stored procedures, business entities, and HTML documentation for your data model. These artifacts would most likely be generated by three different templates. Project files provide the ability to regenerate all or part of your application via a single mouse click (see Figure 6). A project file is a hierarchical collection of templates arrayed in the order of your choosing. Project files also contain the prerecorded settings necessary to regenerate your project at any time. These settings are actually gathered and recorded as you add templates to the project file.

You can select any template or folder in the project tree and regenerate from that point onward. To regenerate the entire project, you simply select the root and execute. There is also a command line utility that can execute a project file or an individual template.

I hope you have seen the makings of a great code generator. MyGeneration has taken the "have it your way" approach. MyGeneration offers four template languages. There are hooks for global and local user metadata. There is also a template browser than can list templates by file name or template namespace. The template browser can even refresh templates from the MyGeneration Web site. MyGeneration leverages the very powerful Scintilla editor and uses a powerful window docking library for most of its user interface. MyGeneration is also very fast and can generate tens of thousands of lines of code in seconds. On the MyGeneration Web site you will find links to an interactive template library that allows users to both collaborate on and share templates. There are also online forums for support. Full MSDN style help is available for all of MyMeta, dOOdads, and the template engine.

More Stories By Mike Griffin

MyGeneration is the result of a partnership between Mike Griffin and Justin Greenwood. Both are architects for leading Indianapolis consulting firms. The MyGeneration Web site can be found at www.mygenerationsoftware.com

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
Tapping into blockchain revolution early enough translates into a substantial business competitiveness advantage. Codete comprehensively develops custom, blockchain-based business solutions, founded on the most advanced cryptographic innovations, and striking a balance point between complexity of the technologies used in quickly-changing stack building, business impact, and cost-effectiveness. Codete researches and provides business consultancy in the field of single most thrilling innovative te...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
CloudEXPO has been the M&A capital for Cloud companies for more than a decade with memorable acquisition news stories which came out of CloudEXPO expo floor. DevOpsSUMMIT New York faculty member Greg Bledsoe shared his views on IBM's Red Hat acquisition live from NASDAQ floor. Acquisition news was announced during CloudEXPO New York which took place November 12-13, 2019 in New York City.
OpsRamp is an enterprise IT operation platform provided by US-based OpsRamp, Inc. It provides SaaS services through support for increasingly complex cloud and hybrid computing environments from system operation to service management. The OpsRamp platform is a SaaS-based, multi-tenant solution that enables enterprise IT organizations and cloud service providers like JBS the flexibility and control they need to manage and monitor today's hybrid, multi-cloud infrastructure, applications, and wor...
The Master of Science in Artificial Intelligence (MSAI) provides a comprehensive framework of theory and practice in the emerging field of AI. The program delivers the foundational knowledge needed to explore both key contextual areas and complex technical applications of AI systems. Curriculum incorporates elements of data science, robotics, and machine learning-enabling you to pursue a holistic and interdisciplinary course of study while preparing for a position in AI research, operations, ...
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
Intel is an American multinational corporation and technology company headquartered in Santa Clara, California, in the Silicon Valley. It is the world's second largest and second highest valued semiconductor chip maker based on revenue after being overtaken by Samsung, and is the inventor of the x86 series of microprocessors, the processors found in most personal computers (PCs). Intel supplies processors for computer system manufacturers such as Apple, Lenovo, HP, and Dell. Intel also manufactu...