Calling in LightSwitch the SaveChanges method in an async way with an ExecuteCompleted event.

Introduction

I recently blogged about a way to execute a query in an async way. (See: http://blog.pragmaswitch.com/?p=375)

I was wondering if the same could be done for the save pipeline. With the help of Justin Anderson, I can present here a solution.

How?

In order to emulate a long running save operation (typically a save with side-effect processing), it’s best to put a Thread.Sleep(10000) server side in the SaveChanges_Executing method.

Client side we have a simple ListDetail screen and we place an additional button on the screen named “SaveAsync”. As the name suggests, clicking this button will trigger the asynchronous save operation.

public partial class CustomersListDetail
    {
        partial void SaveAsync_Execute()
        {

            ApplicationData dataService = this.Application.CreateDataWorkspace().ApplicationData;
            Customer c = dataService.Customers.AddNew();
            c.LastName = "new customer";
            ISubmitOperationInvocation saveChangesInvocation = dataService.Details.Methods.SaveChanges.CreateInvocation(new object[] { });
            saveChangesInvocation.ExecuteCompleted += new EventHandler<ExecuteCompletedEventArgs>((s1, e1) =>
            {
                this.Details.Dispatcher.BeginInvoke(() =>
                    {
                        this.ShowMessageBox("save completed");
                    });
            });
            saveChangesInvocation.ExecuteAsync();
            this.ShowMessageBox("the save has been started and is processing...");
        }
    }

Conclusion

The above is very close to how “native” WCF Ria Services would handle submit operations.  Admitted, it looks like going a step behind, because LightSwitch is precisely hiding this type of ceremony. Nonetheless, good to know you can do it this way also. It confirms once again that LightSwitch is simple on the outside but rich on the inside.