I use some invoke operation method in wcf ria service.like following method:
[Invoke]
public int GetCountOfAccountsByRequestId(long requestId)
{
return ObjectContext.Accounts.Count(a => a.RequestId ==requestId);
}
When i want get data from this method , i use the following code to run and get value from invoke method:
int countOfAccounts = 0;
InvokeOperation<int> invokeOperation = context.GetCountOfAccountsByRequestId(selectedRequest.RequestId);
invokeOperation.Completed += (s, args) =>
{
if (invokeOperation.HasError)
{
var messageWindow = new MessageWindow(invokeOperation.Error.Message);
messageWindow.Show();
invokeOperation.MarkErrorAsHandled();
}
else
{
countOfAccounts = invokeOperation.Value;
if (countOfAccounts == 0)
{
// do some thing
}
}
};
But this method requires a lot of coding to Run invoke method and get value from this.Also as part of this code is executed asynchronously.Similarly, some method must be implemented in tandem.And the return value of each method is related to previous methods.
How can i implement this actions?! How can i write better than this without any problem?
For WCF RIA Services I usually create a service class in my project to handle all the interactions with the service in one place. So I would use this service class to make the calls easier to understand and use.
I put your existing code in a separate class so you can see how it might be called. Note: This is just an example. :)
public class ServiceWrapper
{
...
public void GetCountOfAccountsByRequestId(int requestId, Action<int> callback)
{
context.GetCountOfAccountsByRequestId(requestId, InvokeComplete, callback);
}
private void InvokeComplete<T>(InvokeOperation<T> io)
{
var callback = (Action<T>)io.UserState;
if (io.HasError == false)
{
callback(io.Value);
}
else
{
var messageWindow = new MessageWindow(io.Error.Message);
messageWindow.Show();
io.MarkErrorAsHandled();
}
}
}
public class YourCode
{
public void SomeMethod()
{
serviceWrapper.GetCountOfAccountsByRequestId(selectedRequest.RequestId, GetCountCompleted);
}
public void GetCountCompleted(int countOfAccounts)
{
if (countOfAccounts == 0)
{
// do some thing
}
}
}