WCF DataServices in Windows Phone 7
Cristian Merighi ()

Sample code about how to manage a DataContext the asynchronous way.
This article is obsolete. Some functionalities might not work anymore. Comments are disabled.
How to manage a WCF DataService in Windows Phone 7 (I may write Silverlight)?
Quite simple task, neither a particularly original subject. I just write this article to
fix on "paper" the key code needed to accomplish it so that I can retrieve it with relative ease in the future.
(Syntax in the WPF world is almost identical).
Reading data (C#):
- // DataContext proxy instance:
- var proxy = new ToolSpare.ToolSpareContext(new Uri("http://myserver/mydataservice.svc/"));
- // Build up a query to be executed (cast it as a
System.Data.Services.Client.DataServiceQuery) then...
- var query = proxy.MovementSet.Where(m => !m.IsIncome).OrderByDescending(m => m.Amount).Take(20) as DataServiceQuery<ToolSpare.Movement>;
- // ...execute it asynchronously
- query.BeginExecute((asyncResult) =>
- {
- // use state token to get the results:
- var state = asyncResult.AsyncState as
- DataServiceQuery<ToolSpare.Movement>;
- var list = state.EndExecute(asyncResult).ToList();
- list.ForEach(outcome => Dispatcher.BeginInvoke(() =>
- {
- // populate some collection in the ViewModel (execute this code in the UI Thread)
- var item = new ItemViewModel { LineOne = outcome.Amount.ToString("c2"), LineTwo = outcome.Caption, LineThree = string.Format("{0:D} {0:t}", outcome.Date) };
- this.Items.Add(item);
- }));
- }, /* state -> */query);
Reading data, alternative way (C#):
- // using System.Data.Services.Client.DataServiceCollection
- DataServiceCollection<ToolSpare.Movement> outcomes = new DataServiceCollection<ToolSpare.Movement>(proxy);
- outcomes.LoadCompleted += (s, e) => // inline delegate, do not try this at home! Always detach handlers :)
- {
- // ensure execution in the UI-Thread;
- foreach (var outcome in outcomes)
- {
- var item = new ItemViewModel { LineOne = outcome.Amount.ToString("c2"), LineTwo = outcome.Caption, LineThree = string.Format("{0:D} {0:t}", outcome.Date) };
- this.Items.Add(item);
- }
- };
- outcomes.LoadAsync(/* query from above -> */query);
Saving data (C#):
- // changes have been made to the model, DataContext.UpdateObject(...)
- proxy.BeginSaveChanges((asyncResult)
- => this.Dispatcher.BeginInvoke(()=>
- {
- // execute code in the UI Thread...
- var ctx = asyncResult.AsyncState as ToolSpare.ToolSpareContext;
- ctx.EndSaveChanges(asyncResult);
- // do something else...
- }, null), /* state -> */proxy);
Hope that could be of any help.
Take care. Bye.