10.09.08
Posted in Technical at 4:08 pm by Tony
There are a couple of gotchas when managing concurrency issues with LINQ to SQL. First, when you catch a ChangeConflictException and allow the other user’s changes to win by calling ResolveAll on the DataContext’s ChangeConflicts property and passing RefreshMode.OverwriteCurrentValues, other non-conflictual changes will not be persisted because LINQ to SQL will roll back the transaction it started whenever there is an exception. To avoid this behavior, you need to wrap the call to SubmitChanges inside a “using” block that creates a new TransactionScope. Then right before the ending brace, you need to call Complete on the TransactionScope, which will ensure that the changes you tried to persist when calling SubmitChanges will in fact commit, even when you catch a ChangeConflictException.
// Persist non-conflict changes even when catching an exception
using (TransactionScope txScope = new TransactionScope())
{
try
{
db.SubmitChanges
(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException)
{
Console.WriteLine("Re-submit changes? {Y/N}");
ConsoleKey key = Console.ReadKey().Key;
if (key == ConsoleKey.Y)
{
//Keep local data
//db.ChangeConflicts.ResolveAll
//(RefreshMode.KeepCurrentValues);
foreach (ObjectChangeConflict conflict
in db.ChangeConflicts)
{
conflict.Resolve
(RefreshMode.KeepCurrentValues);
}
// Overwrite other users' changes
db.SubmitChanges();
}
else
{
// Refresh local data from the database
db.ChangeConflicts.ResolveAll
(RefreshMode.OverwriteCurrentValues);
}
}
// Commit transaction
txScope.Complete();
}
As you can see from this code, there are two ways you can resolve a change conflict. You can allow the other user’s changes to overwrite your own (shown in the ‘else’ block), or you can keep your current values and attempt to re-submit your changes to the database (as shown in the ‘if’ block), overwriting the other user’s changes with your own. As indicated, there is a problem lurking here. The ResolveAll method has a bug that refreshes database values, not just for the change conflicts, but for all updates in the change set, which results in an InvalidOperationException when you try to invoke SubmitChanges. The exception states that the timestamp property (which you are using for optimistic concurrency checking) is a computed value and cannot be changed. The answer is to iterate each change conflict and call Resolve on them individually. Thus, we avoid refreshing items for which there is not a change conflict, because those changes were applied the first time we called SubmitChanges. You can download the full VS project here.
Permalink
10.05.08
Posted in Personal at 6:01 pm by Tony
Soon after we purchased our home in a suburb of Dallas, Texas, I started to investigate how to make the house more energy efficient, and in particular how to protect ourselves against excess heat from the sun during summer months. So I started looking into radiant heat barriers. Some companies spray on Aluminum based paint to the underside of the attic rafters. Others will lay out aluminum foil on the attic floor. These approaches are mostly ineffective, but companies sell them because they don’t require much labor and are therefore less expensive and easier to sell. But the best way to install foil is tacked to the underside of the attic rafters, with good ventilation at the top and bottom to direct heated air up and out of the attic.
The best companies out there offer to install the foil for about $1.50 per square foot, which on our home would amount to almost $4,000! This was way out our budget, so I decided to buy the material over the Internet at atticfoil.com. The cost was only $400, and I was able to hire an off-duty fireman to help me install it – I got his name and phone number from this same web site. The final bill was about a third the cost of the original estimate, and I had extra insulation laid down at the same time.
We installed the foil at the height of summer and saw our electric bills come down as a result. The house is cooler, and we’ve only had to run one of our air conditioning units to keep the place at 78 degrees when it’s over 90 degrees outside. Please feel free to share your experiences with attic foil here.
Permalink
Posted in Technical at 5:40 pm by Tony
I just found a great post on how to format code sections in a WordPress blog:
http://www.thomasclaudiushuber.com/blog/2008/01/07/give-your-blog-code-the-visual-studio-look
Now the code in my blog should look a lot prettier.
Permalink
Posted in Technical at 1:25 pm by Tony
I’ve been using NOD32 as my anti-virus for quite some time now, and I’ve been quite pleased with it. For the most part it runs silently in the background and does not impact system performance. However, I’ve discovered there are some issues related to running Visual Studio and its interaction with NOD32.
First of all, if you develop web applications with VS, you may run into trouble. After creating a web app based on the “File System” (using the ASP.NET development web server), I would not be able to run the app from Visual Studio. When pressing F5 or Ctrl+F5, Internet Explorer would state plainly that it could not display the web page. But on closer inspection, I noticed that the port number had been decremented by 2 from that used by the development web server.
I ran across a forum post, which referenced a blog post detailing the problem and how to solve it. It turns out NOD32 Protocol Filtering is the culprit. What you need to do is disable this feature for the ASP.NET development server. Open NOD32, press F5 to show advanced settings, then in the tree-view on the left expand Web Access Protection / HTTP / Web Browsers. Click the Add button to add WebDev.WebServer.EXE, located here:
C:\Program Files\Common Files\microsoft shared\DevServer\9.0
Click the checkbox until a Red X is displayed. This will solve the problem. As a postscript, I also had to add an exclusion for MS Word in order to publish this blog post. J
Permalink
08.28.08
Posted in Technical at 7:43 pm by Tony
If you’ve been programming WCF for a while, you’re probably used to the convenience of using the proxy class generated by svcutil.exe when you add a Service Reference to a Visual Studio project. You’re also probably used to creating the proxy within a using block, so that its Dispose method is called and cleanup can take place in a robust fashion.
However, you may not be aware that closing the proxy at the end of the using block could result in an exception (for example, a Timeout or Communication exception) and that you should catch this exception and call Abort on the client channel, as described in this MSDN topic: http://msdn.microsoft.com/en-us/library/aa355056(VS.85).aspx.
using (MyServiceClient proxy = new MyServiceClient())
{
proxy.SomeOperation();
} // Could throw an exception here
To remedy this, I wrote a code snippet that creates a partial class to extend the generated proxy class by implementing IDisposable and properly handling the cleanup. Although there are other approaches you could take, what I like about the code snippet is that it doesn’t require you to change the code that creates and uses the proxy. Here’s the code that the snippet produces:
namespace Client.MyService
{
public partial class MyServiceClient : IDisposable
{
bool disposed;
public void Dispose()
{
if (!disposed)
{
CloseChannel();
}
disposed = true;
}
void CloseChannel()
{
try
{
if (base.InnerChannel.State
!= CommunicationState.Closed)
{
this.InnerChannel.Close();
}
}
catch
{
this.InnerChannel.Abort();
}
}
}
}
The code snippet has placeholders for both the namespace name and the class name, which reflect what you specified when adding the Service Reference. You can download the code snippet here. To install it, place it in the My Code Snippets folder: …\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets. Enjoy.
Permalink
06.01.08
Posted in Technical at 9:02 am by Tony
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:
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!
Permalink
04.25.08
Posted in Technical at 11:41 am by Tony
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.
Permalink
04.14.08
Posted in Personal at 4:24 pm by Tony
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.
Permalink
04.10.08
Posted in Technical at 3:48 pm by Tony
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!
Permalink
03.30.08
Posted in Personal at 7:18 am by Tony
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.
Permalink
« Previous entries