This is a mirror of official site: http://jasper-net.blogspot.com/

Getting rid of the magic strings in a WCF Data Service Client

| Thursday, October 28, 2010
One of the common problems that you might find when using the generated DataServiceContext for consuming an existing WCF data service is that you have magic strings everywhere for handling links (expanding, adding, deleting, etc). The problem with all those magic strings is that they make your code to compile correctly, but you might run into some error at runtime because you used a link that does not exist or it was just renamed.

To give an example, this is how you expand the items associated to an order using the traditional way with magic strings.

context.Orders.Expand(“Items”)

If that property is later renamed to “OrderItems” on the service side, and the proxy is updated, that code will still compile but you will receive an error at runtime.

Fortunately, you can get rid of those “magic” strings and making the compiler your friend by leveraging Expression trees. The expression trees will make your code easier to maintain, and what’s more important, the compiler will verify the expressions correctness at compilation time.

Continuing what Stuart Leeks did for link expansions with expressions, I added a few more methods for managing links.

namespace System.Data.Services.Client
{
   public static class DataServiceExtensions
   {
       public static void SetLink<TSource, TPropType>(this DataServiceContext context, TSource source,
           Expression<Func<TSource, TPropType>> propertySelector, object target)
       {
           string expandString = BuildString(propertySelector);
           context.SetLink(source, expandString, target);
       }

       public static void AddLink<TSource, TPropType>(this DataServiceContext context,
           TSource source, Expression<Func<TSource, TPropType>> propertySelector, object target)
       {
           string expandString = BuildString(propertySelector);
           context.AddLink(source, expandString, target);
       }

       public static void DeleteLink<TSource, TPropType>(this DataServiceContext context,
           TSource source, Expression<Func<TSource, TPropType>> propertySelector, object target)
       {
           string expandString = BuildString(propertySelector);
           context.DeleteLink(source, expandString, target);
       }

Read more: Pablo M. Cibraro (aka Cibrax)

Posted via email from .NET Info

0 comments: