Wednesday, May 4, 2011

Beatifull Code Part 1 – Implement the repository pattern asynchronously with RIA Services

 

I’ve bought the book “Beautiful Code” published by O’Reilly and edited by Andy Oram and Greg Wilson and it has inspired my work in the last days. It doesn’t actually teach writing beautiful code or it would just be another GoF or Fowler book, it teaches you how the best think and it puts you thinking like the best. Hopefully thinking like the best will make you one of the best :).

Ten years ago when I left school if one would ask me where the best programmers spend their time I guess that I would answer writting very complex very fast. Yet today I spent hours thinking on an interface and how would people use it. I did that because I realized (through the book) that the best delete code instead of writing it. Code is bad! Code is ugly! Code is money spent! The less the better! What I really want is to reuse the same code over and over to solve equivalent problems by hiding the details.

What I was trying to do is to bridge the gap between the way you change collections of objects and the way you use RIA services to change tables. I looked at IEnumerable<T>, at ICollection<T>, at IList<T>, at EntitySet<T>, all the change tracking interfaces and the paged collection interfaces and at the end the only phrase on my brain was what a mess!

It is amazing how a mess can be created from a very simple mistake, the idea that operations that act on sets are synchronous. Have you ever asked yourself why would Add return void? Why would it return “immediately”? Imagine you are adding one element to a collection that as 10^9 elements and must always be sorted, it can take quite some time until add returns control to the caller. Until that happens the caller is blocked, wasting resources doing nothing. But if you say Add cannot be synchronous what would it look like? Well if I was on the Desktop market then I would say Task<T> but since I am on the Silverlight I must come up with a different name to the same idea because I don’t want to clash with that name in the future. So I came up with IResult:

 

/// <summary>
/// Represents the result of a method that cannot be completed synchronously.
/// </summary>
/// <remarks>
/// For void methods we consider that if no Exception was thrown the method executed successfully.
/// </remarks>
public interface IResult
{
    /// <summary>
    /// Occurs when all the activities initiated by the method that return this instance are completed.
    /// </summary>
    event EventHandler<EventArgs> Completed;

    /// <summary>
    /// Gets the error that ocurred during the execution of the activities triggered by the method that 
    /// returned this instance or null if no error occurred.
    /// </summary>
    Exception Error
    {
        get;
    }

    /// <summary>
    /// Gets a value indicating whether the method that returned this instance terminated in error.
    /// </summary>
    bool HasError
    {
        get;
    }

    /// <summary>
    /// Gets a value indicating whether the method that returned this instance finished its execution.
    /// </summary>
    bool IsComplete
    {
        get;
    }

    /// <summary>
    /// Gets a tag that identifies the method that returned this instance.
    /// </summary>
    string Action
    {
        get;
    }

    /// <summary>
    /// Gets a value representing the input of the method that returned this instance.
    /// </summary>
    IEnumerable Request
    {
        get;
    }

    /// <summary>
    /// Blocks the current thread until the underlaying activities complete.
    /// </summary>
    void Wait();

    /// <summary>
    /// Blocks the current thread until the underlaying activities complete but setting a timeout.
    /// </summary>
    /// <param name="miliseconds">The amount of time in miliseconds that the current thread will wait for a result.</param>
    void Wait(int miliseconds);
}

IResult is basically a pull based mechanism for someone to pull asynchronous method call state. We will get to a push base mechanism on a future article. IResult is inspired in OperationBase from RIA but it attempts to hide the semantics linked with web requests.

Ok, now that we have IResult how would a Repository contract look like?

/// <summary>
/// A set of elements that cannot be changed synchronously and that interfaces with a persistent storage
/// using a collection like interface.
/// </summary>
/// <typeparam name="T">The Type of elements in the repository.</typeparam>
public interface IRepository<in T>
{
    /// <summary>
    /// Gets a value indicating whether the repository can be modified.
    /// </summary>
    bool IsReadOnly
    {
        get;
    }

    /// <summary>
    /// Gets a value indicating whether the repository was modified.
    /// </summary>
    bool IsChanged
    {
        get;
    }

    /// <summary>
    /// Gets a value indicating whether the repository allows adding elements.
    /// </summary>
    bool CanAdd
    {
        get;
    }

    /// <summary>
    /// Gets a value indicating whether the repository allows removing elements.
    /// </summary>
    bool CanRemove
    {
        get;
    }

    /// <summary>
    /// Gets the number of elements in the set asynchronously.
    /// </summary>
    IResult<int> Count
    {
        get;
    }

    /// <summary>
    /// Adds the given element to the set asynchronously.
    /// </summary>
    /// <param name="item">The element to add to the set.</param>
    /// <returns></returns>
    IResult Add(T item);

    /// <summary>
    /// Determines asynchronously whether the given element is in the set or not.
    /// </summary>
    /// <param name="item">The element to check whether it is on the set or not.</param>
    /// <returns>A representation of the current state of the activities initiated by the method call.</returns>
    IResult<bool> Contains(T item);

    /// <summary>
    /// Removes asynchronously the element from the set.
    /// </summary>
    /// <param name="item">The element to add to the set.</param>
    /// <returns>A representation of the current state of the activities initiated by the method call.</returns>
    IResult Remove(T item);

    /// <summary>
    /// Accepts the changes made to the set making them permanent.
    /// </summary>
    /// <returns>A representation of the current state of the activities initiated by the method call.</returns>
    IResult AcceptChanges();

    /// <summary>
    /// Discards the changes made to the set reverting to the values that where previously on the persistent media.
    /// </summary>
    /// <returns>A representation of the current state of the activities initiated by the method call.</returns>
    IResult RejectChanges();
}

I would recommend you to spend a couple of minutes thinking on Count. In a standard collection Count would return the number of elements that are in the data structure holding the data, but when we are counting records on a table through a service call that can take quite some time. It makes sense to return an IResult. When the Count operation is completed then the Completed event will be raised and the program can use that value. Until that happens it can do other stuff. In the next article we will see how we can tweak this interface to take advantage of pull base mechanisms and reactive extensions. I’m building a framework based on these ideas and I will release the source code if someone is interested in it.

Thursday, January 13, 2011

MEF TIP – How to initialize CompositionHost with all the assemblies contained in the application main XAP?

It’s a very a simple operation although not obvious (at least to me):

- Create an instance of the DeploymentCatalog class using the empty constructor. This gets the list of parts included in the manifest of the main XAP.

- Call CompositionHost.Initialize(deploymentCatalog, …)

If you are loading XAPs outside of MEF you must keep track of the assemblies you load and save that information, then create one AssemblyCatalog for each of then and merge them in a AggregateCatalog.

Have fun,

Pedro

Tuesday, June 1, 2010

Lambdas as EventHandlers

At the moment I’m writing a guide to do design review for .NET 4.0 applications writen in C#. One of the small questions I had was what to do with event handlers that use lambda expressions and closures.

The problem of closures is that by using members that are on the scope of the object defining the lambda they create references to those members and can cause unexpected leaks.

One of the things I wanted to try is to see if using the same lambda (Test1) to unsubscribe would remove it from the invocation list of the event. The answer is NO it does not. I have seen code that uses this but as this test shows it does nothing. The only way to remove it from the invocation list is to hold the reference to the lamdba in a variable and use that to subscribe and unsubscribe (Test2). The code loses the beauty of using the lamdba to shorten it and I am considering to allow only the use of lamdbas that do not use members of the object.

 

class Program
{
   static void Main(string[] args)
   {
       Console.WriteLine("Test 1 : Do not hold the lambda in a variable:");
       Console.WriteLine();
       Test1();

       Console.WriteLine("Test 2 : Hold the lambda in a variable.");
       Console.WriteLine();
       Test2();
   }

   private static void Test1()
   {
       EventPublisher ep = new EventPublisher();
       ep.TestEvent += (o, e) => { };
       Console.WriteLine("Number of subscribers = {0}", ep.NumberOfSubscribers);
       ep.TestEvent -= (o, e) => { };
       Console.WriteLine("Number of subscribers = {0}", ep.NumberOfSubscribers);
       Console.ReadLine();
   }

   private static void Test2()
   {
       EventPublisher ep = new EventPublisher();

       EventHandler<EventArgs> t = (o, e) => { };

       ep.TestEvent += t;
       Console.WriteLine("Number of subscribers = {0}", ep.NumberOfSubscribers);
       ep.TestEvent -= t;
       Console.WriteLine("Number of subscribers = {0}", ep.NumberOfSubscribers);
       Console.ReadLine();
   }
}

class EventPublisher
{
   public event EventHandler<EventArgs> TestEvent;

   public int NumberOfSubscribers
   {
       get
       {
           if (this.TestEvent != null)
           {
               return this.TestEvent.GetInvocationList().Length;
           }

           return 0;
       }
   }

   public void Publish()
   {
       this.OnTestEvent(new EventArgs());
   }

   protected virtual void OnTestEvent(EventArgs e)
   {
       if (this.TestEvent != null)
       {
           this.TestEvent(this, e);
       }
   }
}

The output of this small program is the following:

Test 1 : Do not hold the lambda in a variable:

Number of subscribers = 1
Number of subscribers = 1

Test 2 : Hold the lambda in a variable.

Number of subscribers = 1
Number of subscribers = 0

As you can see beware of lambdas in Event Handlers.

Have fun,

Thursday, April 22, 2010

Techdays 2010 – Just bought some new toys

Techdays is almost over, as always there are way too many products on the table and it is time to choose what to buy and take home. This year I would like to highlight a couple of stars. One was here before but has grown from a promising idea to a great tool, PEX:

Pex and Mole

The other nominee I would describe it with the idea of chaos theory where the butterfly’s wings might be the igniter for a tornado! The tools is Rx Extensions. The idea is basically if you have iterators that you can use to pull data out of collections why can’t you have iterators that throw data at you! Instead of having to continuously checking for data availability you get notified. What this bring is a shift from programs that way of users to interact with them to programs that react to changes and do things. Programs will always be interactive in some way but this can be a starting point to create new compelling experiences.

Rx Extensions

And the next one is The toy for architects. If you want to amaze with the latest craziest stunt then you should go event driven and start processing tens of millions of events using StreamInsight. Get your backbones fibered and your cores lubed :)

Stream Insight 

And last but not least a toy to use when you are tired after eight hours of coding really scientific applications that do something as challenging as inserting data into a database and  you want to do stupid coding such as autonomous robots this is what you need. .NET Micro Framework.

.NET Micro Framework

Just heard about this really nice (cheap) platform: TinyClr

Have fun,

Wednesday, April 21, 2010

Monday, April 19, 2010

I will be on Techdays 2010 presenting the product I’ve been working on

My session is about software industrialization. I’ve working on a Domain Driven Development framework on Primavera and this is the first public presentation we are doing about it. The last months have been hard but are starting to payoff. You can find better details here:

The age of software industrialization – Combining Domain Driven Design with Code Generation

The description is only available in Portuguese but most of the contents are in United States English.

Our platform will support the product lines of the next generation of Primavera ERPs. We have achieved a high level of automation by using Microsoft DSL tools and T4 templates to generate a very large portion of the software. Our objective is to reach 100% of generated code! This is very very hard but we are highly motivated to pursuit it.

Tuesday, April 13, 2010

Silverlight Serialization – Avoiding having public setters in Properties

In Silverlight you cannot use Reflection to call a non-public setter on a class unless you are in the scope of the class. This has a side-effect in serialization because it requires having public setters for all properties that must be serialized. Well that is not really the case. You can make them internal and use the InternalsVisibleTo attribute to expose those internals to the Microsoft serialization assemblies like this:

   1: [assembly: InternalsVisibleTo("System.Runtime.Serialization, PublicKey="
   2:     + "00240000048000009400000006020000002400005253413100040000010001008D56C76F9E86493"
   3:     + "83049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E"
   4:     + "9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4"
   5:     + "BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B"
   6:     + "37AB", AllInternalsVisible = true)]
   7:  
   8: [assembly: InternalsVisibleTo("System.ServiceModel.Web, PublicKey="
   9:     + "00240000048000009400000006020000002400005253413100040000010001008D56C76F9E86493"
  10:     + "83049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E"
  11:     + "9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4"
  12:     + "BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B"
  13:     + "37AB", AllInternalsVisible = true)]
  14:  
  15: [assembly: InternalsVisibleTo("System.Runtime.Serialization.Json, PublicKey="
  16:     + "00240000048000009400000006020000002400005253413100040000010001008D56C76F9E86493"
  17:     + "83049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E"
  18:     + "9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4"
  19:     + "BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B"
  20:     + "37AB", AllInternalsVisible = true)]

Once this is done you can make your setters internal and prevent outside code from calling them.

Have fun,