#region Author //// Yevhen Bobrov, http://blog.xtalion.com #endregion using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Sample.Silverlight.WCF.Infrastructure.Actions; namespace Sample.Silverlight.WCF.Infrastructure.Services { public abstract class ServiceCall<TService> : DispatchAction where TService: class { readonly ServiceChannelFactory<TService> factory; readonly TService instance; readonly MethodCallExpression call; object channel; protected ServiceCall(ServiceChannelFactory<TService> factory, TService instance, MethodCallExpression call) { this.factory = factory; this.instance = instance; this.call = call; } public bool Failed { get { return Exception != null; } } public Exception Exception { get; private set; } public override void Execute() { if (instance != null) { ExecuteSynchronously(); return; } ExecuteAsynchronously(); } void ExecuteSynchronously() { try { object result = DirectCall(); HandleResult(result); } catch (Exception exc) { Exception = exc; } SignalCompleted(); } object DirectCall() { object[] parameters = call.Arguments.Select(Value).ToArray(); return call.Method.Invoke(instance, parameters); } static object Value(Expression arg) { return Expression.Lambda(arg).Compile().DynamicInvoke(); } void ExecuteAsynchronously() { channel = factory.CreateChannel(); object[] parameters = BuildParameters(); MethodInfo beginMethod = GetBeginMethod(); beginMethod.Invoke(channel, parameters); } MethodInfo GetBeginMethod() { return GetMethod("Begin" + call.Method.Name); } MethodInfo GetEndMethod() { return GetMethod("End" + call.Method.Name); } MethodInfo GetMethod(string methodName) { return channel.GetType().GetMethod(methodName); } object[] BuildParameters() { var parameters = call.Arguments.Select(Value).ToList(); parameters.Add(new AsyncCallback(OnCallCompleted)); parameters.Add(null); return parameters.ToArray(); } void OnCallCompleted(IAsyncResult ar) { try { MethodInfo endMethod = GetEndMethod(); HandleResult(endMethod.Invoke(channel, new object[]{ar})); } catch (Exception exc) { Exception = exc; } SignalCompleted(); } protected abstract void HandleResult(object result); } }
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The MIT License