Real-World LINQ to SQL!

If you are attending the Microsoft TechEd Conference taking place June 2-6, 2008 in Orlando, Florida, if even if you’re not, this is the place where you can get slides, code samples and hands-on labs for my presentation on “Real-World LINQ to SQL”:

RW-L2S Slides
RW-L2S Hands-on Labs

To complete the labs, you’ll also need a slightly modified version of the AdventureWorks sample database. Click the previous link to download the database (about 3 MB compressed), then attach it to an instance of SQL Server (Standard or Express), and add it as a data connection in the Visual Studio Server Explorer. To run the client, you’ll also need to install the free Xceed WPF Data Grid.

There is a common misconception that LINQ to SQL is intended to be used only for RAD applications or simple proof-of-concepts, but is not cut out for real-world line of business applications. However, the reality is that L2S has a great deal of support for real-world scenarios, and you shouldn’t be afraid to use it in a production environment. I like to divide L2S’s real-world features into two categories: 1) service-orientation and 2) production-readiness. Here is a summary of what L2S has to offer in each of these areas:

  • Service-Oriented LINQ to SQL
    • Entity Serialization
    • Attaching Disconnected Entities

       

  • Production-Ready LINQ to SQL
    • Concurrency Management
    • Stored Procedures for CRUD Operations
    • Extensibility Points for Business Logic
    • Transaction Support

While most L2S examples have LINQ to SQL on the client talking to a back end SQL Server database, there is fairly good support for utilizing LINQ to SQL with service-oriented application architectures (also referred to as n-tier), where you might have a WCF service that acts as a Data Access Layer (DAL) and encapsulates communication with the database, providing Plain Old C# Objects (POCO) to the client. In this scenario the client has no knowledge of LINQ to SQL, or any other persistence technology, and is said to be persistent ignorant (hopefully). The designer-generated data context that you get when adding a “LINQ to SQL Classes” item to your service project has a Serialization property which you can either set to None (the default) or Unidirectional (there is a corresponding parameter for the SqlMetal command-line tool). What this means is that entities will be marked with a [DataContract] attribute, making them serializable, and association properties representing one-to-many relations will be marked with a [DataMember] attribute.

What unidirectional serialization means is that relations that go in the opposite direction, many-to-one, are not given a [DataMember] attribute. So, for example, if you have an OrderDetail table with a ProductID that acts as a foreign key to a Product table, the OrderDetail entity has a Product property representing the many-to-one relation. In a 2-tier application with L2S on the client, all you have to do is traverse the Product property of OrderDetail to get the ProductName or other field from the Product entity. However, with unidirectional serialization, the Product property of OrderDetail is not assigned a [DataMember] attribute and therefore is not part of the entity that is serialized and sent to the client from the WCF service.

The way to overcome this limitation is to create a partial class for OrderDetail that includes a ProductName property with a [DataMember] attribute. In the property getter all you have to do is reference the ProductName property of the OrderDetail’s Product property. There’s no need for a property setter, since the underlying Product property is populated when the OrderDetail is loaded from the database. You just have to make sure to eager-load Product with OrderDetail by creating a DataLoadOptions object, calling LoadWith to specify the Product property, and the setting it to the LoadOptions of the data context. The hands-on labs for my TechEd presentation contains step-by-step instructions for doing this, along with “before” and “after” code samples.

Because we want to use POCO objects on the client, there needs to be some mechanism for tracking object changes on the client and then communicating those changes to the service. For a high-level object, such as Order, we can have separate service operations for CreateOrder, UpdateOrder and DeleteOrder. However, we would ideally like to handle creating, updating and deleting OrderDetails when we update a specific order, and we would only like to pass into the service those order details that have been modified. To pull this off, we need an agreed-upon data schema to represent object state. For our purposes an enum will do fine. My example has a TrackingInfo enum marked with [DataContract] that has values forUnchanged, Created, Updated, Deleted, each of which are marked with a [EnumMember] attribute.

On the client there needs to be a smart change-tracking collection that sets a TrackingState property on order details and has a GetChanges method that returns only modified items. Because my samples use a WPF client, I have a ChangeTrackingCollection<T> that extends ObservableCollection<T> (it’s just as easy to extend BindingList<T> for Windows Forms clients). It overrides both InsertItem and RemoveItem, adding removed items to a private Collection<T> before calling base.RemoveItem. It also constrains T to implement INotifyPropertyChanged so that it can mark an item as Updated when a property value has changed. This works because by default entities that are generated when adding a WCF service reference to a client application all implement INotifyPropertyChanged, in order to support two-way data binding. On the service-side, we simply inspect the TrackingState property of order details and invoke the appropriate API on the data context for attaching, inserting or deleting entities. Again, the hands-on lab will take you though the steps for achieving this result, and I will further expand on this aspect in a future blog post or article.

This is how you can incorporate LINQ to SQL into a service-oriented application architecture. Now you need to make your application production-ready. Thankfully, LINQ to SQL has excellent support in this area, including support for concurrency management, stored procedures, data validation and business logic, and transactions. All of these are well documented, but the examples are based on a 2-tier application architecture. There are additional considerations when using these features with a service-oriented application architecture, and this is what I take you through in the hands-on labs. So check it out, and feel free to post comments on this blog, or to email me directly at tonys@develop.com. Happy LINQ-ing!

 

Posted in Technical | 1 Comment

Visual Studio 2008 Samples

In case you haven’t yet discovered them, there are some very good code samples that come with Visual Studio 2008. To find them, simply select the Help menu and choose Samples.

You’ll then see a start page for the samples. Simply click on the “Local Samples Folder” link to navigate to the samples folder installed with Visual Studio. There you’ll find samples for C#3.0 and LINQ. Included are the Expression Tree Debugger Visualizer and the Paste as LinqToXml Add-In, which allows you to select an XML fragment, copy it to the clipboard, then paste it into your code as a Linq to Xml expression! More code samples can be found online, including samples for WPF, Windows Forms, ASP.NET, and Silverlight.

http://msdn2.microsoft.com/en-us/vcsharp/bb330936.aspx

Enjoy.

Posted in Technical | Leave a comment

We Have a Home!

We spent about one month searching for a house to purchase in McKinney, Texas. The first half of that search entailed driving through a few dozen neighborhoods, trying to get more familiar with the city and the kinds of homes that are here. We started by searching realtor.com and getting a list of homes at with at least 4 bedrooms that cost less than $300 K. Then we drove to each house (finding the location with the help of our Verizon GPS service). When we got there, we cruised the neighborhood picking up fliers from other houses for sale. After a couple weeks doing this, we had a much better idea about what we were looking for.

We concluded that we wanted a house in a neighborhood that was somewhat well established, where there was a variety of architectures (no cookie-cutter houses), where lot sizes were larger – with more space between houses and with larger front and back yards. We discovered that over the last several years home builders started skimping on land as it became more expensive, so we wanted a neighborhood where the houses had been built more than 5 years ago.

But at the same time, we also wanted a house that was relatively new, with a floor plan that included a downstairs master bedroom and study and with a kitchen that had granite or Corian countertops and quality custom cabinets. After a friend of mine recommended his realtor, John Powell, to us, we started looking at the insides of houses. One week – and 20 houses – later, we narrowed our search down to a few different houses and neighborhoods.

Our favorite neighborhood included a park, called Falcon Creek, with a playground and jungle gyms, and a lake with a walking path that follows a wooded creek. It also has a highly rated elementary school within walking distance. There were two houses that interested us: one four-bedroom house that had just come on the market, and a five bedroom house had been on the market for quite a while but had come down in price. On Easter Sunday we placed an offer on the newly listed house but found out someone had just beat us to the punch and the house was no longer available. The other house, while a little more expensive, was larger and had an extra bedroom downstairs, which could serve as a nursery for our second child, which we’re expecting to arrive in the Fall.

The second house was also in a slightly more affluent part of the neighborhood, but it was vacant and had fewer bells and whistles, and so was selling for less than the surrounding homes. In addition to five bedrooms (2 downstairs, 3 upstairs), a downstairs study and upstairs game room, there are 4 full bathrooms, and a 2 ½ car attached garage. After a few rounds of negotiations, we settled on a price that’s pretty close to what we wanted to pay for a house. Since then we’ve lined up financing (a 15-year fixed mortgage) and had the house inspected. The sellers also replaced the roof, which had been damaged by a recent hail storm. Here is a link to an online “virtual tour” of the house:

http://www.visualtour.com/shownp.asp?sk=13&t=1369972

Although house prices in north Dallas are about one quarter of those in Southern California – our home would cost over $1 million in Thousand Oaks – there are a couple of down sides to purchasing a home in Texas: 1) property taxes, 2) utilities. Property taxes here are now about 2.3 – 2.5% of the appraised value, versus 1.5% in California. That said, the prices are much lower here and there is no personal income tax in Texas (it’s 9.3% in California). Utilities, however, are dramatically higher here. We’ll probably end up paying somewhere around $400-$500 per month for electricity, gas, sewer, water and trash. That said, we’re planning on improving the energy-efficiency of the house and, on balance, we’ll get a much bigger bang for our buck than areas of the country where the real-estate bubble pushed house prices above the affordability level for most folks.

Posted in Personal | Leave a comment

I’m Speaking at Tech Ed!

In case any of you are planning on attending the TechEd Microsoft developer conference, taking place June 3-6 in Orlando, I’ll be presenting a session there on “Real-World LINQ to SQL”. Here’s the description of the session, which is part of the “Developer Tools and Languages Track”:

“Take a deep dive into real-world LINQ to SQL applications that seek to exploit the full capabilities of the object-relational mapping technology released with Microsoft .NET Framework 3.5 and Microsoft Visual Studio 2008. This talk focuses on best practices for incorporating LINQ to SQL into your data-driven Windows Forms or Windows Presentation Foundation application, including the use of eager loading, pass-through SQL, batch updating with stored procedures, concurrency control, and disconnected scenarios. We also address object caching and identity issues, as well as support for distributed transactions.”

If you register before April 18th, you get $200 of the registration fee. Hope to see you there!

Posted in Technical | Leave a comment

House Hunting in McKinney

What a hectic past few weeks this has been! At the beginning of March we started looking for a place to live somewhere in the north Dallas area, commonly referred to as the Metroplex. It’s a vast area covering 9,289 square miles with 6.1 million people. To help narrow down the search and get a better feel for the area, we employed the services of a well-established realtor named John Powell, who’s been practicing real estate in the Dallas area for the past 37 years and knows the area as well as anyone. He was recommended to me by a DevelopMentor colleague who lives in the area, and has done an incredible job helping us find a place to call home.

While most of the rest of the country experienced what is now called the housing bubble, home prices in the Dallas area remained somewhat stable over the past several years. The abundance of land here enabled home builders to keep building lots of houses, which helped maintain enough supply to meet demand. And in the past year the collapse of real estate prices in other parts of the country has resulted in lower house prices here as well.

We quickly zoned in on McKinney as the best place for us to look for a home, which just so happens to be where we are now living. It’s one of the few areas left in north Dallas which still has a lot of growing to do before they run out of land. That makes home prices about 10% lower in McKinney than in other parts of the Metroplex. It’s also the site of a master-planned community called Stonebridge Ranch, which has a swimming pool and lake with a beach club for small children.

In spite of my busy traveling schedule, we’ve quickly established ourselves in the area, which has many of the same stores and businesses we’re used to seeing in Southern California. Plugging into a parenting program here also helped us connect with people.

Posted in Personal | Leave a comment

I Love My Home Server

I have recently become the proud owner of an HP MediaSmart Server, featuring Microsoft’s Windows Home Server product. The idea behind it is to offer consumers a somewhat convenient way to automatically backup all your home computers with a relatively easy admin panel for configuring backups, doing remote administration and accessing shared data. I use the modifiers “somewhat” and “relatively” because you do need to be technically savvy to successfully setup and configure the server, especially tweaking the network settings. But once you overcome those hurdles, actually using the Home Server is quite easy.

The most difficult part for me was configuring my wireless router to play nice with Home Server. If you do take the plunge and buy a Home Server, you should spend a little extra money to get a half-way decent router. I made the mistake of starting out with a cheapo Belkin router ($50), which caused me a few days of heartache. After switching to NetGear, it was pretty smooth sailing. Where the technological sophistication comes in is in setting up the router to reserve a specific IP address for the Home Server and then setting up port forwarding to enable remote administration over the Internet. This lets you see your Home Server from anywhere in the world, as well as remotely administer any machine on your home network (via Remote Desktop) – there are also some extra steps required to configure machines on the network to accept remote connections.

Setting up the server provided me the necessary excuse to better organize our digital media assets, such as photos, music and home videos. After having done so, I realized that we have almost 10 years worth of pictures residing on hard drives. So the peace of mind in having those backed up redundantly is well worth the price of the server (about $600) and the time needed to configure it. If you plan to buy one, you might also want to check out some of the add-ins available. It’s running Windows Server 2003 (64 bits) under the hood, so it could conceivably run things like SharePoint and Exchange. Now all I need is a little more spare time. J

Posted in Technical | Leave a comment

Everyone Should Own a 2-Year Old

I can’t believe how much fun it is to have a two-year-old – and the experience of the father-son relationship is especially rewarding. Little Kerrigan wants to do everything I do. I have to elevate my leg because it was injured while moving to Texas, so he puts his leg up too. The picture is worth a thousand words. J

Posted in Personal | Leave a comment

Kicking Off 2008

Boy, what a start to the new year! After having spent the last three weeks on the road, I’ve just arrived back at our new home in Dallas, Texas. On Jan 2nd I flew to New Orleans to take part in a company retreat for instructors at DevelopMentor. It was a lot of fun, and I got to meet others who teach for the same company I do. Then I flew to Los Angeles to load a truck with all our stuff from storage and haul it out to Texas, towing one of our cars while a friend drove the other car. In the course of loading the truck, one of the people helping me move managed to run into my left calf with a large hand dolly. Ever since then, I’ve been hobbling around on crutches and trying to treat my leg with ice, ace bandages, and elevation — which has made the rest of my trip especially challenging.

Moving from Los Angeles to Texas was a real adventure. My leg was severely injured and I was in a lot of pain. I couldn’t carry anything, and getting from one place to another was a chore. I could barely manage to climb into the cab of the truck, and spending 12 hours a day driving for three days put a real strain on it. By the time I got to Texas, my foot was swollen like a balloon and I had to go to the emergency room to have it looked at. My friend Peter Ruffner took his 86 year old father along for the 3 day drive from California to Texas, so it was quite a sight seeing his father and I using walkers to get to the rest room whenever we stopped.

After arriving with the truck and our two cars in Texas, we picked up my wife Zuzana and our son Kerrigan at the airport. They flew up to Dallas from College Station, where they had been staying with a friend. No sooner had we moved into the apartment than I hopped on a plane to fly back to Los Angeles for a teaching engagement. My leg was in bad shape, so I had to teach the class sitting in a chair with my leg packed in ice and propped up on the desk. Each day I had to get a ride to the office from a co-worker, even though the hotel was in walking distance. After that week, I flew back to Texas for the weekend, before having to take off again for another teaching assignment, this time in New York City!

My leg has finally started to feel a little better, but my foot is still swelling up from time to time. I’m hopeful it will heal so that I can get off the crutches and start walking on my own. Today we all went to Wal-Mart to buy household essentials. Thankfully, Wal-Mart has electric carts available for handicapped shoppers. I spent a couple hours tooling around the store, while Kerrigan rode in a special cart for children, which was equipped with a built-in TV monitor with running cartoon shows!

My next teaching assignment isn’t for another three weeks, so I’ve got some time to fully recuperate. I’ll spend most of that time authoring the “What’s New in .Net 3.0+3.5” course for DevelopMentor. Though the travel can be demanding, the nice thing about this job is the time I have in between gigs. I’ll take advantage of the break, because I’ll need to be rested up for the next assignment, which will take place in London. Overall, though, it is good to have work doing what I love, which is teaching developers about emerging technologies. All in all, 2008 is off to a good start. J

Posted in Personal | Leave a comment

Windows Workflow Designer Glitch

I’ve had the opportunity to teach a course called What’s New in .Net 3.0, which includes a day spent on Windows Workflow Foundation. Overall, I think the tool story for WF is one of the best among all the “pillars” of .Net 3.0 (WPF, WCF, WF, CS). However, I have noticed a glitch in the designer support for WF: the VS 2008 workflow designer does not support activity binding for bool and enum dependency properties. Normally, when binding the property of one workflow activity to another, or to the workflow itself, you see a little ellipses button when you select the property in the Properties window.

 

Continue reading

Posted in Technical | Leave a comment

Look Out Texas – Here We Come!

In my last blog entry I explained some of my reasons for taking a sabbatical year in Slovakia (roughly from June 2006 through November 2007), the primary reason being an opportunity to move into a new career as an instructor for the developer training company DevelopMentor. Having successfully negotiated the transition, I was left facing the question of where to permanently settle my family. We could have easily remained in Slovakia (I even got a Slovak “green card” through my wife!), but that country is probably decades away from recovering from communism, and better economic and educational opportunities exist in America for our son Kerrigan. Besides, I am American after all, and I’m used to the way things work here, from ordering a book at amazon.com to buying a house with a mortgage. And there’s no language barrier, as there is for me in Slovakia. Lastly, the weakening dollar eliminated the economic incentive for living in Slovakia, where the cost of living has probably doubled since when I lived there in the late nineties.

Having decided to return to America, the question emerged as to where we should live. With the price of housing in Southern California having tripled in the last 5 years, buying a decent medium-size house there would run at least $500K and probably require a dual-income household, depriving our son of the benefits of a stay-at-home mom. Adding in the commute, I would probably be away from home 12 hours a day, getting home just in time to tuck Kerrigan into bed. Not wanting to have to adopt that lifestyle, we started to look at other parts of the country offering lower real estate prices but in proximity to a major metropolitan area with plentiful programming jobs (as a fallback and to supplement by income as a developer instructor). After contemplating areas on the East Coast, such as Atlanta and cities in North and South Carolina, our gaze fell upon Texas and the city of Dallas.

Continue reading

Posted in Personal | Leave a comment