T4 Templates and the answer to life, the universe and everything


[This is the third in a series of posts on getting started with the new features in Entity Framework 4 based on the demos I did in my session at TechEd Europe in Berlin last week (Nov 2009).]

Entity Framework 4 relies significantly on the Text Template Transformation Toolkit (T4) to generate code from the EDM.

I thought it would be useful to show a really simple example of T4 in action which is nothing to do with Entity Framework.

In a Visual Studio 2008/2010 solution, add a new item of type Text Template:

image

Edit the “output extension=” pragma to generate a “.cs” file and add some C# code for a very simple class which has a single method TheAnswer which contains a single WriteLine. In the WriteLine use a T4 <#= #> block. <#= represents the start of a simple evaluation block, in this case the evaluation is to add 41+1:

image

NB: I am using the Tangible T4 editor to give me syntax highlighting and intellisense. You will need to add this into Visual Studio using the Extensions Manager.

Next build the project or click on Transform Templates in the Solution Explorer:

image

You will now see a new C# file in your project, SimpleTemaplate.cs:

image 

In summary a T4 template is composed of:

  • Blocks of text: text that simply is copied into the output file(s)
  • Directives: meta information for the template such as “output extension=” enclosed in <#@ … #>
  • Statements: code enclosed in <#...#>
  • Expressions: code that is evaluated to a string <#= …#>

The above is pretty much the most basic example of T4 I could come up with. However there are plenty of other great resources on T4 out there. Oleg Sych has been heavily involved with T4 for many years and has many great posts. You may want to start with this tutorial done as a series of posts.

author: Eric Nelson | posted @ Friday, November 20, 2009 9:22 AM | Feedback (0)

Tangible T4 Editor – a life saver


I have been working with T4 (Text Template Transformation Toolkit) lately thanks to the Entity Framework team moving their code generation model over to T4 in Visual Studio 2010. However by default Visual Studio 2008 and 2010 do not include syntax highlighting or intellisense support for T4 files, which makes it rather difficult to work with them (very difficult at times!). Thankfully there are partners who address this. The one I am using with Beta 2 of Visual Studio 2010 is the Tangible T4 editor. You can easily add this into Visual Studio using the Extensions Manager from the Tools menu:

image

Once added, it will change this:

image

Into this:

image

Sweet!

author: Eric Nelson | posted @ Friday, November 20, 2009 9:18 AM | Feedback (0)

Getting Started with Entity Framework 4 - Templated Code Generation


[This is the second in a series of posts on getting started with the new features in Entity Framework 4 based on the demos I did in my session at TechEd Europe in Berlin last week (Nov 2009).]

Code generation from the Entity Data Model (EDM) has changed significantly in version 4 of the Entity Framework. The product does retain a backwardly compatible model of code generation but also now includes T4 templates for code generation. This is a fantastic addition to the Entity Framework as many developers want to (easily) control the code generated from the EDM to meet their specific needs, which was very difficult to do in version 1 as it depended on the CodeDom. T4 gives us:

  • Full control over the code generation from an EDM
  • The ability for developers to easily customise the templates produced by Microsoft
  • The ability for Microsoft to easily add additional templates in the future
  • The ability for developers to easily share templates between projects, teams and companies

T4 was first introduced in Visual Studio 2008 and stands for Text Template Transformation Toolkit – a code generation tool similar in capabilities to the likes of CodeSmith.

T4 was largely overlooked in Visual Studio 2008, in the main because there was no real UI for T4. In general  I come across very very few developers who have heard of or understand the power of T4. However, now that the Entity Framework team (and the ASP.NET MVC team) have adopted T4 wholeheartedly I expect T4 will itself get the attention it deserves.

The EF team include a single T4 template in Beta 2 but add a further template in CTP2 for self tracking entities  (In Beta 1 they also had a singel template but added an additional two in the companion CTP1).

By default you are not using T4 if you add a new EDM or if you open a version 1 EDM. You need to enable T4 code gen for your EDM. You do this by right clicking on the EDM design surface and then add in the template(s).

In Beta 1 this was called (confusingly) Add New Artifact Generation Item:

image 

In Beta 2 it is renamed to Add Code Generation Item:

image

This will display the available choices:

Beta 1 with CTP 1

image

Beta 2 with CTP 2

image

Once you have added a template you will notice that the Custom Tool generation for the EDM is now blank (It normally is the value EntityModelCodeGenerator):

image

In my case I have added the POCO Code Generator (which was available in CTP1 for Beta 1 and will reappear in a future CTP for Beta 2). My solution now contains two T4 files – one to generate the Object Context class and another responsible for the generation of a class (and C# file) per Entity in the EDM. Note that a single T4 template can generate several files:

image

If we take a brief look at the contents of SimpleModel.Context.tt:

image

We can see that the text wrapped inside <# #> is evaluated by T4 to ultimately generated the resulting C# files. The code outside is just text in the final output. This approach should feel very familiar to anyone who has developed web sites using classic ASP. For example, this section of SimpleModel.Types.tt:

image

generates the partial class code in the C# file Order.cs:

image

All pretty straightforward really – although a lot of “smarts” is contained within those .tt files! I will add a more general post on T4 shortly.

author: Eric Nelson | posted @ Thursday, November 19, 2009 1:47 PM | Feedback (0)

SQL Azure slides and links from EdgeUG session


A big thanks to all those who attended http://edgeug.net/ last night to hear about SQL Azure and SQL Server 2008 R2. I really enjoyed it and once again “Merry Christmas”!

Links

Slides

author: Eric Nelson | posted @ Thursday, November 19, 2009 11:42 AM | Feedback (0)

Getting Started with Entity Framework 4 – Simple Model First Example


[This is the first in a series of posts on getting started with the new features in Entity Framework 4 based on the demos I did in my session at TechEd Europe in Berlin last week (Nov 2009). ]

When adding an Entity Data Model to a project you are given the option to:

  • Generate the Model from an existing database (SQL Server, Oracle etc) or
  • Start with an Empty Model and create your conceptual model (sometimes referred to as Application Model or Domain Model) first – adding new Entities and Associations between Entities.

Unfortunately in version one of the Entity Framework the button “Empty model” was one of those “buttons that should never be pressed” (Reference the Xmas episode of Dr Who). Put simply – it took you down a path to many, many issues which were best avoided and the recommendation in the v1 days was to never use it.

Fortunately in the betas of Entity Framework 4 things have got a lot better. You can now safely click on “Empty Model” and continue to sensibly create a working solution.

Hence, lets start with an Empty model.

image

Once you have your empty model you can add Entities and Associations by right clicking on the design surface:

image

 

 

 

Lets add two Entities – Category and Product, which you will likely be used to from the sample database Northwind. Once these are added we can then add a single association between Category and Product which is visualised in the design surface as the Navigation Properties on each Entity and the 1:Many association:

image 

We now have a “finished” conceptual model but with no mapping to database tables. Interestingly there is no way to start to map Entities to tables until you do at least one “Generate Database from Model”:

image

Which gives you the Generate Database Script Wizard:

image

When you click Finish two things will happen.

  • A DDL script will be written to the file system and will be included into the project. In this case ModelFirstModel.edmx.sql
  • The Entity Data Model will be updated – a new mapping file and store schema file will be generated. Remember that the Entity Data Model (EDM) is made up of three schemas – Conceptual, Mapping and Store

You get the option to update the Entity Data Model or not – but TBH the only option is to go with Yes. The update of the EDM is 100% destructive:

image

Note the DDL script is not automatically run against your database. Which is a good thing as it is also 100% destructive:

image

Hence all that is then left to do is to actually execute the DDL script to create the database, which for me I tend to do inside SQL Server Management Studio. You will then see that the Entities and Associations are now mapped and you can begin to customise those mappings.

That has covered the simple stuff with Model First but I plan to revisit this topic in the near future and look at why and how you might use it in a real solution.

author: Eric Nelson | posted @ Tuesday, November 17, 2009 10:30 PM | Feedback (0)

Using SQL Server Management Studio R2 with SQL Azure


As I mentioned earlier this week, we now have a CTP release of a version of SSMS that is SQL Azure aware.

I thought it might be useful to share my first few minutes with it. First up, I cleared out my SQL Azure account using the portal (dropped all my databases).

image

And I made sure the firewall setting would allow me to connect: (for simplicity I just opened up everything. Don’t do that!)

image 

Then I downloaded (155MB) SSMS R2 Nov CTP (32bit or 64bit) and installed it:

ssms installed

Which gave me a new menu group for R2:

image

Launching SSMS R2 I filled in my server name, admin name and password copied over from the portal:

image

Which then gave me the usual catalogue view:

image

And allowed me to do a Create Database using the new SQL Azure templates (no dialogue boxes):

image

Which was there waiting for me in the portal:

image

I have not done an exhaustive check – but looks like we have SQL Azure templates for most/all :-)

image

Nice and simple. I also just spotted a similar post – check that out as well.

Enjoy

DotNetKicks Image

author: Eric Nelson | posted @ Friday, November 13, 2009 3:06 PM | Feedback (0)

TechEd Europe 2009 Highlights and Lowlights


It is Friday 13th Nov 2009 - which means it is the last day of TechEd Europe in Berlin. Overall I have had a good week – high quality sessions, lots of time with customers and colleagues and a very smooth conference throughout.

I spent the week doing a bunch of things. 9am Monday I was presenting on Entity Framework 4 after 4 hours of sleep and using a brand new VPC after my original failed to load following yet another blue screen from the host (the machine will be flattened next week – perhaps literally!). Then Monday, Tuesday and Wednesday I manned the .NET Framework pod in the Technical Learning Centre which was great fun – lots of random questions mixed in with some really fun chats with old and new friends. I also managed to record a some short podcasts which will ultimately get published here on Channel 9. They were:

  • Mike Flasko of the ADO.NET Data Services team talking about Entity Framework 4 and N-Tier (Mikes EF4 session was standing room only)
  • David Robinson of the SQL Azure team talking about SQL Azure today and future and the release this week of a version of SQL Server Management Studio that works with SQL Azure
  • Peli de Halleux and Nikolai Tillmann of the Pex team talking about Pex, Stubs and Moles
  • Peli de Halleux and Nikolai Tillmann talking about their sister teams Code Contracts technology

My discussions with Mike and David left me feeling positive about the next 12 months for technology areas I spend a lot of time on and the Pex guys impressed me so much with where they were taking their technology. They need developers to keep trying it and to keep giving them feedback. Lets not let them down – install Pex today.

Highlights

  • All the developer sessions I did attend were good to very good. No bad ones at all. Which is good as I didn’t get to attend that many.
  • The conference was smooth and the facility worked well
  • The expo area, hands on lab area and TLC area all were great – you could fill the week by taking advantage of those 3 and not attend a single session
  • The 6 interactive theatres that delivered sessions even during lunch were a great addition
  • It was fun to be in Berlin on the 20th anniversary of the wall coming down. Nice one Microsoft.
  • The food and free beer!

Lowlights

  • The keynotes on Monday. Awful. Sorry – but they were.
  • Lack of “general” development session on .NET Framework 4.0 and Visual Studio 2010. I was told that around 45% of the sessions were dev but it never felt that way. The 45% included “edge sessions” like embedded and windows mobile that I think many of the developers attending would ignore (myself included) which sometimes meant you only had 2 or 3 sessions to choose from in any slot. Shame. Presumably we are “keeping our powder dry”  for PDC next week.
  • Distance from conference centre to hotel/central Berlin. For me it required a bus and a train – 45mins door to door, sometimes longer.
  • Lack of developer announcements – but to be expected with PDC just around the corner.

Sessions I would recommend watching when they become available:

  • DAT04-IS Patterns with the Entity Framework – full room!
  • DEV314 A lap around Microsoft Visual Basic - Lisa Feigenbaum rocks at putting lots of content into a session slickly
  • WIA305 What’s New in ASP.NET MVC – nicely done
  • DAT303 Building applications with SQL Azure – well paced session
  • DEV204 Unit Testing Best Practice – this was the same slot as DAT303 which I went to – but lots of folks told me at the pod that DEV204 was great
  • WIA03-IS Securing Microsoft Silverlight – good interactive session that I dozed through – but that was me, not Shawn Wildermuth who did a great job
  • WIA404 Data Driven ASP.NET – Dynamic Data comes of age in .NET 4. Check it out
  • WIA303 ASP.NET AJAX – another good session from Stephen Walther
  • WIA402 Debugging ASP.NET  - Tess Fernandez rocks at this stuff. I don’t really have the need but it was cool to watch
  • There was also a lot of content on SharePoint 2010. SharePoint dev is finally coming of age (and sparked me to create this poll for next weeks MSDN Flash. Feel free to vote)

Oh, and I just had a sneak peak at the eval scores for the event and although we are not quite done yet, the top ranked dev session is… drum roll… DEV307 Parallel Computing for Managed Developers.

DotNetKicks Image

author: Eric Nelson | posted @ Friday, November 13, 2009 11:52 AM | Feedback (4)

Pictures of TechEd Europe 2009 – brussel sprouts for the win!


Some pictures from the awesome TechEd Europe.

My favourite – “Xmas Lunch” on the Thursday:

SNC00220

The rather large entrance

SNC00203 SNC00204

The Berlin wall (outside a restaurant!)

SNC00214

The amazing hands on lab area:

SNC00216 SNC00217

A typical session (AJAX in this case):

SNC00218

The expo:

SNC00222

The community doodle wall:

SNC00223SNC00224

I suspect Andrew Fryer was at work:

SNC00225

And a panel discussion:

SNC00226

author: Eric Nelson | posted @ Thursday, November 12, 2009 6:41 PM | Feedback (0)

SQL Server Management Studio now supports SQL Azure


I have had a bit of a “SQL Azure” day at TechEd Europe. I sat through David Robinsons excellent intro to SQL Azure development (smooth, on time, great Q&A), caught up with David afterwards to exchange stories on SQL Azure and find out what I will be missing at PDC next week and then grabbed the chance to capture a short 10minute podcast which I will publish up on Channel 9 next week.

David did his demos using a new version of SQL Server Management Studio which works with SQL Azure and announced that it would be publicly available today. And it is.

You can download SSMS in 32bit and 64bit flavours (Unfortunately I can not – as my hotel free internet is blocking it!)

These links are taken from the Microsoft® SQL Server® 2008 R2 November Community Technology Preview - Express Edition download page.

Also check out this "getting started post" of my first few minutes with SSMS.

author: Eric Nelson | posted @ Wednesday, November 11, 2009 10:31 PM | Feedback (0)

Entity Framework 4 at TechEd Europe – standing room only


On Monday at 9am (9th Nov 2009) I presented a session on Entity Framework 4 to several hundred attendees at TechEd in Berlin (DEV305). I have presented EF to developers many times before but this was the first time I had shown the new EF 4 in any detail. I was really interested in the questions and feedback after the session. The tone was much more positive. Developers recognise that we are addressing their concerns with v1 and that v4 includes many very welcome improvements. They just want to get started using it. Which is very cool!

Hence I made a special effort to swing by the other EF4 session which took place the following day, again at 9am. This time it was delivered by Mike Flasko from the Data Services team.

Wow. 9am and the room was full.

SNC00201

Not only was it full (as to be fair it was a smaller room than on Monday) but folks were watching the session through the windows at the back! True dedication.

SNC00200

I also spotted Entity Framework turning up in other sessions. e.g. the ASP.NET Dynamic Data session that ended today had plenty of EF4 in the demos.

It is great to see EF 4 being received so well at last. Well done to the product team for acting on community feedback.

NB: Entity Framework 4 will ship with .NET Framework 4 and Visual Studio 2010 and is currently available in Beta 2 of those products (plus an additional download of CTP 2).

author: Eric Nelson | posted @ Wednesday, November 11, 2009 10:07 PM | Feedback (0)