Tuesday, May 10, 2011

Implement a Cancel button while using Bindings, and send only an object's changes to a WCF service


Take the following scenario: A user of your application opens a customer for editing. They put in a new address. Now they realize they're in the wrong customer entirely and want to cancel their changes.

What does your application do? If you're like me, then you are on a mission to keep code behind to an absolute minimum. You have two way bindings setup for everything. You're proud of all the C#/VB code that you haven't written in your application. So, your model is already updated. Do you not have a cancel button? Blame the user for the bad experience and tell them not to do that? Or did you add a reload method to your cancel button instead, forcing the application to grab data from a web service or a database?
Another possible option might have been to follow MVVM completely and to separate the Model from the ViewModel even on the most basic classes. The ViewModel could then store copies of this data and include methods to move back to the object and to reload data from the object. The downside here is that you need to add properties twice, and always remember to include them in your methods. This is a lot of code duplication. 
Here's another predicament: You use a web service for your data source. You'd like to keep the data sent across the Internet to a minimum. But your class has 100+ properties. Sure, only one might have changed, but how do you know which ones have changed? Do you serialize the entire class to send it? Do you create 100 variables called OrgAddress, OrgName, etc? 
I'd like to share a solution to both of these that has worked for me: A special base class.  

Using the code 

Let's introduce our class: 

Related links

WCF Chat Sample
Implement a Cancel button while using Bindings, and send only an object's changes to a WCF service
Send Cookies When Making WCF Service Calls
Hosting WCF in SharePoint 2010
WCF Architecture Overview
Getting Started Tutorial
WCF programming for Beginners
Returning Large Volume of Records from SOAP based WCF Service
Windows Communication Foundation
Windows Communication Foundation Architecture Overview
How to: Implement an Asynchronous Service Operation
Windows Communication Foundation Architecture Overview
A truely simple example to get started with WCF
What's New for WCF in Visual Studio 2008