Posts tagged with: Silverlight 4

Rewriting ¿better? WCF RIA Services callbacks while reusing code

There’s a legacy project I’ve been working on that has recently had it’s environment migrated to a different architecture, meaning, problems have arisen, but manageable problems. Until now.

The affected part is a Silverlight app that connects to a WCF RIA Service on a server, and then this server connects to a CRM 4 service and does some CRUD operations on CRM entities. The Silverlight scenario is fairly common, but rather exhausting: ExpedientViewModel is the VM to a child window of InterviewViewModel, which inherits from BaseInterviewViewModel, which inherits from BaseTaskViewModel that, finally, inherits from BaseViewModel. ExpedientViewModel is in charge of creating/editing a set of entities, that is then handed over to InterViewViewModel (remember, parent-child window) through MvvmLight messaging.

Leaving aside the discussion about the architecture, the problem was one of the entities was failing on an insert and we couldn’t debug why, because every call to Context.SubmitChanges() was done with the parameterless overload, meaning you had to do something like this:

var operation = Context.SubmitChanges();
operation.Completed += SubmitChangesCompleted;
private void SubmitChangesCompleted(object sender, EventArgs args)
    ///do something else once the data is "inserted". There's no way to get that operation variable that actually holds information about the operation in here. And I'm doing a global variable for that.

The problem was sound: the Complete operation does not say anything about it being completed with or without errors, nor there’s any way to actually get the OperationBase.SubmitOperation object on the callback to determine if anything has gone wrong. The solution goes without mention: use the SubmitChanges overload that takes 2 parameters, an Action callback and an object userState. But then again, I didn’t wanted to rewrite the whole application again, including the callbacks within lambdas.

Having in mind I’m no architecture whatsoever, the solution I came up with was having a GeneralSubmitChangesCompleted function in the BaseViewModel taking a SubmitOperation and an Action to be passed as a callback to every SubmitChanges and, inside this function, call whatever function is next. Like so:

protected void GeneralSubmitChangesCompleted(SubmitOperation operation, Action<object, EventArgs> next)
        next(new object(), new EventArgs());
        var frame = new StackFrame(1);
        InsertLog(this.GetType().Name, frame.GetMethod().Name, new Exception(operationCompleted.Error.Message, operationCompleted.Error.InnerException));

So far it works and I’m a bit more certain that the operation actually completes successfully and at least I’m able to discard that part as the cause of the problem. But I don’t know if it’s actually a good practice to follow.

¿Any expert?