What a Great Week!

What a Great Week!


This week I was the University of Northern Colorado Symphony Orchestra, David Thomas Bailey, Brandi Shearer, and Grace Potter. I was elected an alternate delegate to our county Democratic Convention. I stepped out of my safe little sandbox to join a group of architects who maintain a far broader view of the world than I have. I wrote a code generation template preprocessor – twice. I was able to take advice from my son. I’m winning overall against the cold I’m fighting. I started a diet. I managed to unwind myself when I got overly stressed out.


Check out your local music scene. I don’t spend enough time with our two college music departments at Colorado State University and UNC. The UNC concert featured a Frank Zappa orchestral piece called G-Spot Tornado. That was followed by Shostakovich’s Cello Concerto #1 played by Joseph Miller – a doctoral candidate at UNC. This piece was written for the great cellist Mstislav Rostropovich. It is both technically demanding and calls for the deepest spirit as I think this is what Shostakovich wanted showcase in his friend Rostropovich. My favorite movement is definitely the cadenza which is a very long solo that draws scattered cadenza-esque themes together as it approaches the end and the orchestra fills in below the cellist. Both it and the Zappa piece show feel amazingly modern while remaining largely tonal. And what better way to follow these pieces after intermission than a brilliant performance of Beethoven’s 5th?


David Thomas Bailey played during the happy hour of the inaugural Denver IASA event. He was fabulous. Loud enough to be appreciated, but in the background as we met each other. Definitely catch him in Denver if you’re a jazz fan.


The Grace Potter concert was scheduled for Friday, but weather along the way held her up. They rescheduled at the Bluebird on Saturday and it was fun to visit the theatre with a friend who had been watching movies there around the time I was born. I didn’t even know who the opening act was, and Brandi Shearer just blew me away. Check her out.


Then Grace Potter came on. One of the pals still gets carded although he’s in his thirties and is active in the music scene. He said I was younger than the average age which is way not true. But it was a pretty mixed crowd. I was down near the front dancing to those wild rock and roll tunes. So you can imagine me fearing for my nose as the guy in front threw his head around, with a nice bespectacled cool engineer dude on one side and one of the young pals we’d brought on the other. But even with the modern horrid mixing habit of drowning the vocals there is just little like the passion and talent of Grace Potter backed by three amazing musicians. The held to no boundaries doing both a solo acappella gospel tune and a drum only number with all four of them on the kit.


I may talk another time about how good it is for me to step into places that make me and my .NET skills feel rather a small part of the picture. Or about how stressful Friday was as I realized the preprocessor I had written was fundamentally flawed. Or colds, or diets, or unwinding.


It’s so easy to postpone what’s going on around you, particularly the high school and college performances in your area. And to be overwhelmed by the number of artists, most of which you’ve never heard of, that play the bars and restaurants within a 100 miles of you. But don’t miss out on all that great music and whatever moves you – rocking in a sea of people you don’t know or jiving to good jazz in a comfy chair.


Speaking of that – Hot Club Nouveau is slowing down. They’ll be at Dazzle in Denver on Feb. 27, March 16, and April 23. They’ll bet at the Savoy in Fort Collins this Friday and next Saturday. They’re at the 303 in Casper on May 3, but that’s all they’ve got posted and they’ll be splitting up as Colorado loses James and London gains him. So, if you live in the area and haven’t seen their unique style of gypsy jazz don’t postpone it any longer.


 

XML Literal Code Generation – Code again

OK, that code listing got friend on load. Let me try again.

    Private Function MemberDataPortalFetch() As String      Return _<code>   Private Overloads Sub DataPortal_Fetch(ByVal criteria As Criteria)      Using cn As New SqlConnection(<%= mObjectData.ConnectionStringName %>)         cn.Open()         Using cm As SqlCommand = cn.CreateCommand            cm.CommandType = CommandType.StoredProcedure            cm.CommandText = “get<%= mObjectData.ClassName %>            <%= From prop In mObjectData.PrimaryKeys Select _               <code>            cm.Parameters.AddWithValue(“@<%= prop.Name %>“, criteria.<%= prop.Name %>)               </code> %>             Using dr As New SafeDataReader(cm.ExecuteReader)               dr.Read()               With dr                  <%= From prop In mObjectData.Properties Select _                     <code>                  m<%= prop.Name %> = <%= GetReadMethod(prop) %>(“<%= prop.Name %>“)               </code>.Value %>                   ‘ load child objects                  .NextResult()                  <%= From child In mObjectData.Children Select _                     <code>                  m<%= child.Name %> = <%= child.Name %>.Get<%= child.Name %> (dr)                      </code>.Value %>               End With            End Using         End Using      End Using   End Sub</code>.Value    End Function


 

XML Literal Code Generation

You must use VB for XML Literal Code Generation. Sorry, that’s life. I don’t have a crystal ball on this, but for now even if you’re a C# programmer you’ve got to suck it up and use VB. The code you output can be VB or C# however, but the template itself has to be written in VB. If you’re allergic to VB, get shots.


So, what does a microcosmic view of a XML literal template look like? I’ve translated a section of a CSLA template. CSLA is Rocky Lhotka’s architecture and this is a version 2.1 because I think it clarifies the template process:

   Private Function MemberDataPortalFetch() As String      Return _<code>   Private Overloads Sub DataPortal_Fetch(ByVal criteria As Criteria)      Using cn As New SqlConnection(<%= mObjectData.ConnectionStringName %>)         cn.Open()         Using cm As SqlCommand = cn.CreateCommand            cm.CommandType = CommandType.StoredProcedure            cm.CommandText = “get<%= mObjectData.ClassName %>            <%= From prop In mObjectData.PrimaryKeys Select _               <code>            cm.Parameters.AddWithValue(“@<%= prop.Name %>“, criteria.<%= prop.Name %>)               </code> %>             Using dr As New SafeDataReader(cm.ExecuteReader)               dr.Read()               With dr                  <%= From prop In mObjectData.Properties Select _                     <code>                  m<%= prop.Name %> = <%= GetReadMethod(prop) %>(“<%= prop.Name %>“)               </code>.Value %>                   ‘ load child objects                  .NextResult()                  <%= From child In mObjectData.Children Select _                     <code>                  m<%= child.Name %> = <%= child.Name %> .Get<%= child.Name %> (dr)                     </code>.Value %>               End With            End Using         End Using      End Using   End Sub</code>.Value

   End Function


This is .NET code, which you can see because the template output is inside a .NET function named MemberDataPortalFetch which returns a string constructed with XML literals. By offsetting with XML literals, the code of the function is easily seen – it’s in gray. All of the gray code will be in the output, none of the yellow, blue or black code will be in the output, although it will certainly affect the output.


Where replacements are necessary, XML literals have “embedded expressions” which I have the habit of calling “expression holes.” I’ll talk in another post about what mObjectDatais, but an embedded expression can contain whatever expression you need. An expression is something that returns a value within a single line. So, you can call methods and properties, but you can’t call a subroutine.


Embedded expressions can contain LINQ as shown in the third embedded expression. Here we want to add parameters for all the primary keys.  Within the LINQ Select clause, I can use any string. Including the nested code block creates a more readable template and consistency, among other things.


A quick glance may leave you thinking that this is just a variation of the ASP.NET style template syntax used by CodeSmith, CodeBreeze, MyGeneration and others. However, it’s quite different. To begin with its organized into members of a template class. Then, the logic is expressed in expressions, not direct template logic. Finally, you can nest back and forth between output text and code to any depth you require. The code blocks within the LINQ statements above contain embedded expressions. These embedded expressions could be further LINQ statements with further code blocks, etc.


I think there are right and wrong ways to build templates with XML literals. I’ll spend the next couple of posts talking about template organization and metadata handling.


 

Let’s Talk Templates

Code generation templates have several competing pressures – they need to be easy to use and they need to be powerful. They need to be flexible but encourage best practices. If you ever say “my templates got me started then I had to customize them” you’re templating can be better. I’m not aware of any situation where you can’t isolate the handcrafted code from the generated code sufficiently to keep code generation active for the entire life of your application.


When I say full life cycle, I mean from initial prototypes to finally pulling the switch in a decade. Yep a decade. Code generation should aim for evolution and extremely long project life cycles. The metadata of the project can far outlive the technology, even outlive the database. That requires a deep commitment to code generation, and if you don’t have that commitment, the flip side is that code generation can pay back today. At that moment when it feels easier to pull a file out of code generation, or to repeat a similar block of code in two places instead of pushing it into your code gen templates, that’s where the commitment comes in. With or without it, you get payback; it’s just greater the deeper your commitment is to the metadata and templates.


My current client pushes me because he is even more committed to the decade long lifecycle based on code gen than I am. And he’s right. Every time he’s pushed to get something into templates or do code gen better, it’s taken less work and gotten us further in the short term than I expected.


What if you could combine the simplicity of CodeSmith with the power of XSLT?


And what if you could do it primarily in a language and architecture you already know, or should be learning anyway?


Interested?


This is the first post in a blog series to present this templating style. I also covered in a.NET Rocks show I recorded yesterday. I’m very excited about it, but I want to introduce the basics before I tell you the real punch line. This template style is the best way to generate code today and it’s based entirely on tools you’ve got on your desktop right now.

Look for more here and in the .NET Rocks TV episode scheduled to appear Feb. 15th. The beautiful thing about the techniques I’ll show is that you can smoothly transition from simple to complex templates dialing in the exact complexity appropriate for your organization and application. And, just wait for the punch line.