Welcome to MSDN Blogs Sign in | Join | Help

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.

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!

Posted by Eric Nelson | 0 Comments
Filed under: ,

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).

Read the rest of this post (with lots of screen grabs) over on my primary blog http://geekswithblogs.net/iupdateable

Posted by Eric Nelson | 0 Comments
Filed under: ,

SQL Azure slides and links from EdgeUG session

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

Links

Slides

Posted by Eric Nelson | 0 Comments
Filed under: ,

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

Posted by Eric Nelson | 0 Comments
Filed under: ,

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.

Posted by Eric Nelson | 0 Comments
Filed under: ,

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
Posted by Eric Nelson | 0 Comments
Filed under:

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

Posted by Eric Nelson | 0 Comments
Filed under:

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.

Posted by Eric Nelson | 0 Comments
Filed under: ,

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).

Did you know Microsoft makes a mocking tool? Meet the latest version of Pex

No? Nor me. (If you are wondering what Mocking is, check out my previous post on Mocking, Stubs and Test Doubles.)

I am at TechEd Europe this week in Berlin, speaking on Entity Framework 4.0 and manning the .NET Framework stand. Behind the .NET Framework stand is the Pex and Code Contracts stand manned by the two lead developers of Pex, Peli de Halleux and Nikolai Tillmann. I looked at Pex many months back but was completely unaware of a great new feature they added in September 2009 – Stubs and Moles. Peli and Nikolai kindly took me through the new features in Pex and also recorded a short podcast which I hope to get published asap on our UK MSDN Podcast on channel9.

Stubs and Moles in Pex gives us:

  • The ability to mock using freely available Microsoft tools. Nice.
  • The ability to mock any .NET method (including static methods). Very, very nice!

The ability to mock any .NET method (i.e. methods you don’t have source code for) is something that few mocking tools can do on the .NET platform. Actually I know of no free tools that do it (please let me know if there are some) and instead I always point people at the commercial tool TypeMock if they need that level of functionality.

Moles in action

This example shows a typical use of moles where we detour the DateTime.Now property getter to our custom delegate.

The Pex Download works with both Visual Studio 2008 and Visual Studio 2010 Beta 2.

As a reminder, Pex is an incubation project for Visual Studio, developed by Microsoft Research, and currently available via http://msdn.microsoft.com/devlabs

UK MSDN Flash Poll for November 18th: Do you think you will develop solutions for SharePoint 2010?

SharePoint development has always been a little bit “lumpy” but Visual Studio 2010 and SharePoint 2010 plan to make thing much easier – yet offer more control and power. There are some great resources popping up to help you get started such as:

But – will you be one of those developers targeting SharePoint?

Posted by Eric Nelson | 0 Comments
Filed under: ,

Summary of the Entity Framework 4 changes introduced with Beta 2 and CTP 2

I thought it would be useful (at least to me!) to summarise the new stuff in Entity Framework 4 given it actually comes in 2 parts.

The list is a simplified and categorised version of this and this.

General

  • Foreign Keys now added: EF 4 now includes a new type of associations (Foreign Key Associations) that allow you to have Foreign Key properties on your entities. They are the default although the EF v1 Independent Associations remain.
  • Lazy Loading on by Default in new Models: Also name change from Beta 1. context.ContextOptions.LazyLoadingEnabled = true is placed in the constructor
  • Support for Binary Keys: The EF now allows you to have binary property types (and varbinary storage columns) mapped as Entity Key / Foreign Key.
  • ObjectMaterialized event: Can write logic that is executed immediately after an object has been materialized. 
  • Improved Database Generation: SQL CE support has been added plus customization of database generation is significantly simpler.
  • More Improvements to the generated SQL
  • LINQ to Entities improvements

POCO

  • Improvements to POCO Support: Automatically fixes nav properties and FKs on DetectChanges and SaveChanges. Collections can also be declared as ISet<T>
  • EntityDataSource support for Query Extenders and POCO: EntityDataSource now includes support for the new ASP.NET Query Extenders and POCO entities.

Self Tracking Entities

  • Object Services API improvements to enable N-Tier and Self Tracking Entities: ObjectStateEntry.GetUpdatableOriginalValues method provides a access to an updatable data record that you can use to establish the original state of an entity at the property level.
  • Works with Foreign Key associations: Including Fix-up logic has been tidied up to be aware of FKs.
  • Support for Silverlight 3 via WCF
  • Better Silverlight and WPF Databinding support: Generated entity types now implement INotifyPropertyChanged and use ObservableCollections
  • Richer concurrency control support: Original values are preserved for all required properties according to their concurrency mode in the Entity Data Model.
  • Fewer Round Trips: The approach for managing entities with dangling references has been reengineered to avoid unnecessary database round-trips.
  • New and improved methods: AcceptChanges, StartTracking, StopTracking where added and the existing MarkAsX methods are now extension methods.
  • Generated code improvements and refactoring: The ApplyChanges implementation has been moved to the Context template.

Code Only

  • Fine Grained Control over model: Specify Navigation Property Inverses, Property Facets and Complex Types

  • Customizable Mappings: Change Table and Column Names. Support Custom Inheritance Strategy. Enable Entity Splitting and Join Table Mapping

Designer

  • Navigation Property Management: Users can now delete and add navigation properties, enabling the creation of one-way associations.
  • New Extensibility APIs: New APIs enable custom code to run on model wizards etc.
  • Auto Generation of Complex Types from Stored Procedures: Plus auto update when a stored procedure definition changes.
  • Greatly Improved Facet Management in the Designer 

The relationship between Entity Framework 4 betas and ctps explained

There seems to be enough confusion about the betas and ctps of Entity Framework 4 to warrant a brief post. Hopefully this should clear things up nicely.

Put simply:

  • Most of Entity Framework 4 (EF4) will ship with .NET Framework 4 and Visual Studio 2010 (.NET4/VS2010), however not all of it will.
  • Most of EF4 is therefore in the beta releases of .NET4/VS2010, however not all of it is.
  • The missing bits of EF4 appear in EF4 Feature CTP releases “soon after” the release of a beta.

Right now (Nov 6th 2009), we have:

  • A fairly old .NET4/VS2010 Beta 1 + Entity Framework Feature CTP 1. CTP 1 only works with Beta 1.
    • CTP1 adds:
      • Self Tracking Entities
      • POCO Templates
      • Code Only
  • A very recent .NET4/VS2010 Beta 2 + Entity Framework Feature CTP 2. CTP 2 only works with Beta 2.
    • CTP2 was released 4th Nov 2009
    • CTP2 adds:
      • Lots of new stuff to Self Tracking Entities
      • Lots of new stuff to Code Only
      • Does not include the POCO Template from CTP 1

The missing POCO template stuff will be resolved in a future CTP.

Beta 2 of EF 4 added a fair amount of new features, as does CTP 2. Therefore the obvious right choice to go with is Beta 2 + CTP 2 – but expect breaking changes to your code. I haven’t tried looking into taking the CTP1 POCO stuff onto Beta 2 but it should be doable. However the “in built” POCO support in Beta 2 is far better than Beta 1, hence (I assume) not all the templated code is now needed.

P.S. In case you were wondering, I am doing my TechEd session using Beta 1 + CTP 1 as Nov 4th was just too late for me to switch over plus I didn’t really have any space in the session for the new Beta 2/CTP 2 stuff anyway!

The Plan B is all my DEV305 Entity Framework 4 demos as slideware

Next week I will be presenting Entity Framework 4 at TechEd Europe. At least that is what I hope to do. However my Lenovo T61P seems to have some other plans.

  • A year back the screen packed in. The nice IBM man replaced it. All was well.
  • Last week the screen packed in again. The nice IBM man replaced it. All was well … with the screen.

However since then I am getting blue screens (whenever I really don’t want them) and drive errors and the odd bit of corruption of files. I need to flatten – but now is not the time.

As it happens my demos rely on a large file (a 14GB Virtual Machine) and on not blue screening.

I therefore needed a Plan B. The ideal Plan B would be a second reliable notebook. But that isn’t an option.

Therefore I have settled on:

  • Keeping my fingers crossed
  • Taking the VM on an external drive and have asked for a spare demo machine at the event. But I am on at 9am and fly in 9:30pm the eve before. Not ideal.
  • Capturing 90% of my demos as screen shots in a ppt (which i liked as a least the effort would also be useful for some future EF 4 blog posts)

I have uploaded the demo slides on slideshare. They have been highlighted with “digital ink” in places which slideshare appears not to cope with. But the file should be fine if you download it.

More Posts Next page »
 
Page view tracker