/// <summary>
        /// Calls an operation on an already constructed WCF service channel
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="operationName">name of method/operation to call</param>
        /// <param name="parameters">parameters for the call</param>
        /// <param name="callback">callback responsible for casting return value and epr method error handling</param>
        /// <param name="cancellationToken"><see cref="CancellationToken"/> to be used for requesting cancellation</param>
        /// <returns>A <see cref="Task{TResult}"/> which will contain the result of the operation, exception or be cancelled</returns>
        protected virtual Task <TResult> CallServiceOperation <TResult>(string operationName,
                                                                        IDictionary <string, object> parameters,
                                                                        Func <IAsyncResult, TResult> callback, CancellationToken cancellationToken)
        {
            MethodInfo beginInvokeMethod = WebDomainClient <TContract> .ResolveBeginMethod(operationName);

            MethodInfo endInvokeMethod = WebDomainClient <TContract> .ResolveEndMethod(operationName);

            var taskCompletionSource = new TaskCompletionSource <TResult>();

            if (parameters == null)
            {
                parameters = new Dictionary <string, object>(2);
            }

            // Pass async operation related parameters.
            parameters.Add("callback", new AsyncCallback(delegate(IAsyncResult asyncResponseResult)
            {
                try
                {
                    TResult result = callback(asyncResponseResult);
                    taskCompletionSource.SetResult(result);
                }
#pragma warning disable CA1031 // Do not catch general exception types, we "rethrow it via task
                catch (CommunicationException) when(cancellationToken.IsCancellationRequested)
                {
                    taskCompletionSource.TrySetCanceled(cancellationToken);
                }
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    taskCompletionSource.TrySetException(ex);
                }
            }));
            parameters.Add("asyncState", /*userState*/ endInvokeMethod);

            // Call Begin** method
            // Handle any immediate CommunicationException which can be thrown directly from begin method
            // for some tests that perform invalid calls against localhost
            try
            {
                InvokeBeginMethod(beginInvokeMethod, ChannelFactory, parameters);
            }
            catch (CommunicationException ex)
            {
                // We might have aborted the channel due to cancellation
                if (cancellationToken.IsCancellationRequested)
                {
                    taskCompletionSource.TrySetCanceled(cancellationToken);
                }
                else
                {
                    taskCompletionSource.TrySetException(ex);
                }
            }

            return(taskCompletionSource.Task);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Invokes an operation asynchronously.
        /// </summary>
        /// <param name="invokeArgs">The arguments to the Invoke operation.</param>
        /// <param name="callback">The callback to invoke when the invocation has been completed.</param>
        /// <param name="userState">Optional user state that will be passed through on the <see cref="InvokeCompletedResult"/>.</param>
        /// <returns>An asynchronous result that identifies this invocation.</returns>
        /// <exception cref="InvalidOperationException">The specified query does not exist.</exception>
        protected sealed override IAsyncResult BeginInvokeCore(InvokeArgs invokeArgs, AsyncCallback callback, object userState)
        {
            MethodInfo beginInvokeMethod = WebDomainClient <TContract> .ResolveBeginMethod(invokeArgs.OperationName);

            MethodInfo endInvokeMethod = WebDomainClient <TContract> .ResolveEndMethod(invokeArgs.OperationName);

            // Pass operation parameters.
            ParameterInfo[] parameterInfos  = beginInvokeMethod.GetParameters();
            object[]        realParameters  = new object[parameterInfos.Length];
            int             parametersCount = (invokeArgs.Parameters == null) ? 0 : invokeArgs.Parameters.Count;

            for (int i = 0; i < parametersCount; i++)
            {
                realParameters[i] = invokeArgs.Parameters[parameterInfos[i].Name];
            }

            TContract channel = this.ChannelFactory.CreateChannel();
            WebDomainClientAsyncResult <TContract> wcfAsyncResult = WebDomainClientAsyncResult <TContract> .CreateInvokeResult(this, channel, endInvokeMethod, invokeArgs, callback, userState);

            // Pass async operation related parameters.
            realParameters[parameterInfos.Length - 2] = new AsyncCallback(delegate(IAsyncResult asyncResponseResult)
            {
                wcfAsyncResult.InnerAsyncResult = asyncResponseResult;
                wcfAsyncResult.Complete();
            });
            realParameters[parameterInfos.Length - 1] = userState;

            IAsyncResult asyncResult;

            try
            {
                asyncResult = (IAsyncResult)beginInvokeMethod.Invoke(channel, realParameters);
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException != null)
                {
                    throw tie.InnerException;
                }

                throw;
            }

            if (!asyncResult.CompletedSynchronously)
            {
                wcfAsyncResult.InnerAsyncResult = asyncResult;
            }
            return(wcfAsyncResult);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Submit the specified <see cref="EntityChangeSet"/> to the DomainService, with the results of the operation
        /// being returned on the SubmitCompleted event args.
        /// </summary>
        /// <param name="changeSet">The changeset to submit. If the changeset is empty, an <see cref="InvalidOperationException"/> will
        /// be thrown.</param>
        /// <param name="callback">The callback to invoke when the submit has been executed.</param>
        /// <param name="userState">Optional state that will flow through to the SubmitCompleted event</param>
        /// <returns>An asynchronous result that identifies this submit.</returns>
        /// <exception cref="InvalidOperationException">The changeset is empty.</exception>
        /// <exception cref="InvalidOperationException">The specified query does not exist.</exception>
        protected sealed override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState)
        {
            MethodInfo beginSubmitMethod = WebDomainClient <TContract> .ResolveBeginMethod("SubmitChanges");

            MethodInfo endSubmitMethod = WebDomainClient <TContract> .ResolveEndMethod("SubmitChanges");

            IEnumerable <ChangeSetEntry> submitOperations = changeSet.GetChangeSetEntries();

            TContract channel = this.ChannelFactory.CreateChannel();
            WebDomainClientAsyncResult <TContract> wcfAsyncResult = WebDomainClientAsyncResult <TContract> .CreateSubmitResult(this, channel, endSubmitMethod, changeSet, submitOperations.ToList(), callback, userState);

            object[] parameters =
            {
                submitOperations,
                new AsyncCallback(delegate(IAsyncResult asyncResponseResult)
                {
                    wcfAsyncResult.InnerAsyncResult = asyncResponseResult;
                    wcfAsyncResult.Complete();
                }),
                userState
            };

            IAsyncResult asyncResult;

            try
            {
                asyncResult = (IAsyncResult)beginSubmitMethod.Invoke(channel, parameters);
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException != null)
                {
                    throw tie.InnerException;
                }

                throw;
            }

            if (!asyncResult.CompletedSynchronously)
            {
                wcfAsyncResult.InnerAsyncResult = asyncResult;
            }
            return(wcfAsyncResult);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Calls an operation on an already constructed WCF service channel
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="channel">WCF channel</param>
        /// <param name="operationName">name of method/operation to call</param>
        /// <param name="parameters">parameters for the call</param>
        /// <param name="callback">callback responsible for casting return value and epr method error handling</param>
        /// <param name="cancellationToken"><see cref="CancellationToken"/> to be used for requesting cancellation</param>
        /// <returns>A <see cref="Task{TResult}"/> which will contain the result of the operation, exception or be cancelled</returns>
        protected virtual Task <TResult> CallServiceOperation <TResult>(TContract channel, string operationName,
                                                                        IDictionary <string, object> parameters,
                                                                        Func <object, IAsyncResult, TResult> callback, CancellationToken cancellationToken)
        {
            MethodInfo beginInvokeMethod = WebDomainClient <TContract> .ResolveBeginMethod(operationName);

            MethodInfo endInvokeMethod = WebDomainClient <TContract> .ResolveEndMethod(operationName);

            // Pass operation parameters.
            ParameterInfo[] parameterInfos  = beginInvokeMethod.GetParameters();
            object[]        realParameters  = new object[parameterInfos.Length];
            int             parametersCount = parameters == null ? 0 : parameters.Count;

            for (int i = 0; i < parametersCount; i++)
            {
                realParameters[i] = parameters[parameterInfos[i].Name];
            }

            var taskCompletionSource = new TaskCompletionSource <TResult>();
            CancellationTokenRegistration cancellationTokenRegistration = default;

            if (cancellationToken.CanBeCanceled)
            {
                cancellationTokenRegistration = cancellationToken.Register(state => { ((IChannel)state).Abort(); }, channel);
            }
            // Pass async operation related parameters.
            realParameters[realParameters.Length - 2] = new AsyncCallback(delegate(IAsyncResult asyncResponseResult)
            {
                cancellationTokenRegistration.Dispose();

                try
                {
                    TResult result = callback(channel, asyncResponseResult);
                    taskCompletionSource.SetResult(result);
                }
                catch (CommunicationException) when(cancellationToken.IsCancellationRequested)
                {
#if SILVERLIGHT || NET45
                    taskCompletionSource.SetCanceled();
#else
                    taskCompletionSource.TrySetCanceled(cancellationToken);
#endif
                }
#pragma warning disable CA1031 // Do not catch general exception types, we "rethrow it via task
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    taskCompletionSource.SetException(ex);
                }
                finally
                {
                    if (((IChannel)channel).State == CommunicationState.Faulted)
                    {
                        ((IChannel)channel).Abort();
                    }
                    else
                    {
                        ((IChannel)channel).Close();
                    }
                }
            });
            realParameters[realParameters.Length - 1] = /*userState*/ endInvokeMethod;

            // Call Begin** method
            InvokeMethod(beginInvokeMethod, channel, realParameters);
            return(taskCompletionSource.Task);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Method called by the framework to begin an asynchronous query operation
        /// </summary>
        /// <param name="query">The query to invoke.</param>
        /// <param name="callback">The callback to invoke when the query has been executed.</param>
        /// <param name="userState">Optional state associated with this operation.</param>
        /// <returns>An asynchronous result that identifies this query.</returns>
        /// <exception cref="InvalidOperationException">The specified query does not exist.</exception>
        protected sealed override IAsyncResult BeginQueryCore(EntityQuery query, AsyncCallback callback, object userState)
        {
            MethodInfo beginQueryMethod = WebDomainClient <TContract> .ResolveBeginMethod(query.QueryName);

            MethodInfo endQueryMethod = WebDomainClient <TContract> .ResolveEndMethod(query.QueryName);

            // Pass query parameters.
            ParameterInfo[] parameterInfos  = beginQueryMethod.GetParameters();
            object[]        realParameters  = new object[parameterInfos.Length];
            int             parametersCount = (query.Parameters == null) ? 0 : query.Parameters.Count;

            for (int i = 0; i < parametersCount; i++)
            {
                realParameters[i] = query.Parameters[parameterInfos[i].Name];
            }

            TContract channel = this.ChannelFactory.CreateChannel();

            WebDomainClientAsyncResult <TContract> wcfAsyncResult = WebDomainClientAsyncResult <TContract> .CreateQueryResult(this, channel, endQueryMethod, callback, userState);

            // Pass async operation related parameters.
            realParameters[parameterInfos.Length - 2] = new AsyncCallback(delegate(IAsyncResult asyncResponseResult)
            {
                wcfAsyncResult.InnerAsyncResult = asyncResponseResult;
                wcfAsyncResult.Complete();
            });
            realParameters[parameterInfos.Length - 1] = userState;

            IAsyncResult asyncResult;

            try
            {
                // Pass the query as a message property.
                using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
                {
                    if (query.Query != null)
                    {
                        OperationContext.Current.OutgoingMessageProperties.Add(WebDomainClient <object> .QueryPropertyName, query.Query);
                    }
                    if (query.IncludeTotalCount)
                    {
                        OperationContext.Current.OutgoingMessageProperties.Add(WebDomainClient <object> .IncludeTotalCountPropertyName, true);
                    }

                    asyncResult = (IAsyncResult)beginQueryMethod.Invoke(channel, realParameters);
                }
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException != null)
                {
                    throw tie.InnerException;
                }

                throw;
            }

            if (!asyncResult.CompletedSynchronously)
            {
                wcfAsyncResult.InnerAsyncResult = asyncResult;
            }

            return(wcfAsyncResult);
        }