static AuthorizationBehavior CreateAuthorizationBehavior(DispatchRuntime dispatch)
        {
            AuthorizationBehavior behavior = new AuthorizationBehavior();

            behavior.externalAuthorizationPolicies = dispatch.ExternalAuthorizationPolicies;
            behavior.serviceAuthorizationManager   = dispatch.ServiceAuthorizationManager;
            behavior.auditLogLocation               = dispatch.SecurityAuditLogLocation;
            behavior.suppressAuditFailure           = dispatch.SuppressAuditFailure;
            behavior.serviceAuthorizationAuditLevel = dispatch.ServiceAuthorizationAuditLevel;
            return(behavior);
        }
Exemple #2
0
        void Authorize()
        {
            Fx.Assert(OperationContext.Current != null, "Not in service dispatch thread");

            if (this.serviceAuthorizationManager != null)
            {
                if (!this.serviceAuthorizationManager.CheckAccess(OperationContext.Current))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
                }
            }
        }
        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            object returnVal;

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }

            outputs = EmptyArray.Allocate(this.OutputParameterCount);
            bool callFailed  = true;
            bool callFaulted = false;
            ServiceModelActivity activity = null;

            try
            {
                Activity boundOperation = null;
                GetActivityInfo(ref activity, ref boundOperation);
                using (boundOperation)
                {
                    returnVal  = this.InvokeEndDelegate(instance, outputs, result);
                    callFailed = false;
                }
            }
            catch (SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (FaultException)
            {
                callFaulted = true;
                callFailed  = false;
                throw;
            }
            finally
            {
                ServiceModelActivity.Stop(activity);
                StopOperationInvokeTrace(callFailed, callFaulted, this.endMethod.Name);
                StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.endMethod.Name.Substring(ServiceReflector.EndMethodNamePrefix.Length));
            }

            return(returnVal);
        }
        internal ImmutableDispatchRuntime(DispatchRuntime dispatch)
        {
            this.authenticationBehavior = AuthenticationBehavior.TryCreate(dispatch);
            this.authorizationBehavior = AuthorizationBehavior.TryCreate(dispatch);
            this.concurrency = new ConcurrencyBehavior(dispatch);
            this.error = new ErrorBehavior(dispatch.ChannelDispatcher);
            this.enableFaults = dispatch.EnableFaults;
            this.inputSessionShutdownHandlers = EmptyArray<IInputSessionShutdown>.ToArray(dispatch.InputSessionShutdownHandlers);
            this.instance = new InstanceBehavior(dispatch, this);
            this.isOnServer = dispatch.IsOnServer;
            this.manualAddressing = dispatch.ManualAddressing;
            this.messageInspectors = EmptyArray<IDispatchMessageInspector>.ToArray(dispatch.MessageInspectors);
            this.requestReplyCorrelator = new RequestReplyCorrelator();
            this.securityImpersonation = SecurityImpersonationBehavior.CreateIfNecessary(dispatch);
            this.requireClaimsPrincipalOnOperationContext = dispatch.RequireClaimsPrincipalOnOperationContext;
            this.impersonateOnSerializingReply = dispatch.ImpersonateOnSerializingReply;
            this.terminate = TerminatingOperationBehavior.CreateIfNecessary(dispatch);
            this.thread = new ThreadBehavior(dispatch);
            this.validateMustUnderstand = dispatch.ValidateMustUnderstand;
            this.ignoreTransactionFlow = dispatch.IgnoreTransactionMessageProperty;
            this.transaction = TransactionBehavior.CreateIfNeeded(dispatch);
            this.receiveContextEnabledChannel = dispatch.ChannelDispatcher.ReceiveContextEnabled;
            this.sendAsynchronously = dispatch.ChannelDispatcher.SendAsynchronously;
            this.parameterInspectorCorrelationOffset = (dispatch.MessageInspectors.Count +
                dispatch.MaxCallContextInitializers);
            this.correlationCount = this.parameterInspectorCorrelationOffset + dispatch.MaxParameterInspectors;

            DispatchOperationRuntime unhandled = new DispatchOperationRuntime(dispatch.UnhandledDispatchOperation, this);

            if (dispatch.OperationSelector == null)
            {
                ActionDemuxer demuxer = new ActionDemuxer();
                for (int i = 0; i < dispatch.Operations.Count; i++)
                {
                    DispatchOperation operation = dispatch.Operations[i];
                    DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
                    demuxer.Add(operation.Action, operationRuntime);
                }

                demuxer.SetUnhandled(unhandled);
                this.demuxer = demuxer;
            }
            else
            {
                CustomDemuxer demuxer = new CustomDemuxer(dispatch.OperationSelector);
                for (int i = 0; i < dispatch.Operations.Count; i++)
                {
                    DispatchOperation operation = dispatch.Operations[i];
                    DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
                    demuxer.Add(operation.Name, operationRuntime);
                }

                demuxer.SetUnhandled(unhandled);
                this.demuxer = demuxer;
            }

            this.processMessage1 = new MessageRpcProcessor(this.ProcessMessage1);
            this.processMessage11 = new MessageRpcProcessor(this.ProcessMessage11);
            this.processMessage2 = new MessageRpcProcessor(this.ProcessMessage2);
            this.processMessage3 = new MessageRpcProcessor(this.ProcessMessage3);
            this.processMessage31 = new MessageRpcProcessor(this.ProcessMessage31);
            this.processMessage4 = new MessageRpcProcessor(this.ProcessMessage4);
            this.processMessage41 = new MessageRpcProcessor(this.ProcessMessage41);
            this.processMessage5 = new MessageRpcProcessor(this.ProcessMessage5);
            this.processMessage6 = new MessageRpcProcessor(this.ProcessMessage6);
            this.processMessage7 = new MessageRpcProcessor(this.ProcessMessage7);
            this.processMessage8 = new MessageRpcProcessor(this.ProcessMessage8);
            this.processMessage9 = new MessageRpcProcessor(this.ProcessMessage9);
            this.processMessageCleanup = new MessageRpcProcessor(this.ProcessMessageCleanup);
            this.processMessageCleanupError = new MessageRpcProcessor(this.ProcessMessageCleanupError);
        }
Exemple #5
0
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            EnsureIsInitialized();

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }
            if (inputs == null)
            {
                if (this.inputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.inputParameterCount)));
                }
            }
            else if (inputs.Length != this.inputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.inputParameterCount, inputs.Length)));
            }

            outputs = EmptyArray.Allocate(this.outputParameterCount);

            long startCounter   = 0;
            long stopCounter    = 0;
            long beginOperation = 0;
            bool callSucceeded  = false;
            bool callFaulted    = false;

            if (PerformanceCounters.PerformanceCountersEnabled)
            {
                PerformanceCounters.MethodCalled(this.MethodName);
                try
                {
                    if (System.ServiceModel.Channels.UnsafeNativeMethods.QueryPerformanceCounter(out startCounter) == 0)
                    {
                        startCounter = -1;
                    }
                }
                catch (SecurityException securityException)
                {
                    DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new SecurityException(SR.GetString(
                                                        SR.PartialTrustPerformanceCountersNotEnabled), securityException));
                }
            }

            EventTraceActivity eventTraceActivity = null;

            if (TD.OperationCompletedIsEnabled() ||
                TD.OperationFaultedIsEnabled() ||
                TD.OperationFailedIsEnabled())
            {
                beginOperation = DateTime.UtcNow.Ticks;
                OperationContext context = OperationContext.Current;
                if (context != null && context.IncomingMessage != null)
                {
                    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(context.IncomingMessage);
                }
            }

            object returnValue;

            try
            {
                ServiceModelActivity activity      = null;
                IDisposable          boundActivity = null;
                if (DiagnosticUtility.ShouldUseActivity)
                {
                    activity      = ServiceModelActivity.CreateBoundedActivity(true);
                    boundActivity = activity;
                }
                else if (TraceUtility.MessageFlowTracingOnly)
                {
                    Guid activityId = TraceUtility.GetReceivedActivityId(OperationContext.Current);
                    if (activityId != Guid.Empty)
                    {
                        DiagnosticTraceBase.ActivityId = activityId;
                    }
                }
                else if (TraceUtility.ShouldPropagateActivity)
                {
                    //Message flow tracing only scenarios use a light-weight ActivityID management logic
                    Guid activityId = ActivityIdHeader.ExtractActivityId(OperationContext.Current.IncomingMessage);
                    if (activityId != Guid.Empty)
                    {
                        boundActivity = Activity.CreateActivity(activityId);
                    }
                }

                using (boundActivity)
                {
                    if (DiagnosticUtility.ShouldUseActivity)
                    {
                        ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityExecuteMethod, this.method.DeclaringType.FullName, this.method.Name), ActivityType.ExecuteUserCode);
                    }
                    if (TD.OperationInvokedIsEnabled())
                    {
                        TD.OperationInvoked(eventTraceActivity, this.MethodName, TraceUtility.GetCallerInfo(OperationContext.Current));
                    }
                    returnValue   = this.invokeDelegate(instance, inputs, outputs);
                    callSucceeded = true;
                }
            }
            catch (System.ServiceModel.FaultException)
            {
                callFaulted = true;
                throw;
            }
            catch (System.Security.SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            finally
            {
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    long elapsedTime = 0;
                    if (startCounter >= 0 && System.ServiceModel.Channels.UnsafeNativeMethods.QueryPerformanceCounter(out stopCounter) != 0)
                    {
                        elapsedTime = stopCounter - startCounter;
                    }

                    if (callSucceeded) // call succeeded
                    {
                        PerformanceCounters.MethodReturnedSuccess(this.MethodName, elapsedTime);
                    }
                    else if (callFaulted) // call faulted
                    {
                        PerformanceCounters.MethodReturnedFault(this.MethodName, elapsedTime);
                    }
                    else // call failed
                    {
                        PerformanceCounters.MethodReturnedError(this.MethodName, elapsedTime);
                    }
                }

                if (beginOperation != 0)
                {
                    if (callSucceeded)
                    {
                        if (TD.OperationCompletedIsEnabled())
                        {
                            TD.OperationCompleted(eventTraceActivity, this.methodName,
                                                  TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
                        }
                    }
                    else if (callFaulted)
                    {
                        if (TD.OperationFaultedIsEnabled())
                        {
                            TD.OperationFaulted(eventTraceActivity, this.methodName,
                                                TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
                        }
                    }
                    else
                    {
                        if (TD.OperationFailedIsEnabled())
                        {
                            TD.OperationFailed(eventTraceActivity, this.methodName,
                                               TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
                        }
                    }
                }
            }

            return(returnValue);
        }
        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }
            if (inputs == null)
            {
                if (this.InputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.InputParameterCount)));
                }
            }
            else if (inputs.Length != this.InputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.InputParameterCount, inputs.Length)));
            }

            StartOperationInvokePerformanceCounters(this.beginMethod.Name.Substring(ServiceReflector.BeginMethodNamePrefix.Length));

            IAsyncResult         returnValue;
            bool                 callFailed  = true;
            bool                 callFaulted = false;
            ServiceModelActivity activity    = null;

            try
            {
                Activity boundActivity = null;
                CreateActivityInfo(ref activity, ref boundActivity);

                StartOperationInvokeTrace(this.beginMethod.Name);

                using (boundActivity)
                {
                    if (DiagnosticUtility.ShouldUseActivity)
                    {
                        string activityName = null;

                        if (this.endMethod == null)
                        {
                            activityName = SR.GetString(SR.ActivityExecuteMethod,
                                                        this.beginMethod.DeclaringType.FullName, this.beginMethod.Name);
                        }
                        else
                        {
                            activityName = SR.GetString(SR.ActivityExecuteAsyncMethod,
                                                        this.beginMethod.DeclaringType.FullName, this.beginMethod.Name,
                                                        this.endMethod.DeclaringType.FullName, this.endMethod.Name);
                        }

                        ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
                    }

                    returnValue = this.InvokeBeginDelegate(instance, inputs, callback, state);
                    callFailed  = false;
                }
            }
            catch (System.Security.SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (Exception e)
            {
                TraceUtility.TraceUserCodeException(e, this.beginMethod);
                if (e is FaultException)
                {
                    callFaulted = true;
                    callFailed  = false;
                }

                throw;
            }
            finally
            {
                ServiceModelActivity.Stop(activity);

                // An exception during the InvokeBegin will not call InvokeEnd,
                // so we complete the trace and performance counters here.
                if (callFailed || callFaulted)
                {
                    StopOperationInvokeTrace(callFailed, callFaulted, this.EndMethod.Name);
                    StopOperationInvokePerformanceCounters(callFailed, callFaulted, endMethod.Name.Substring(ServiceReflector.EndMethodNamePrefix.Length));
                }
            }
            return(returnValue);
        }
Exemple #7
0
        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }

            if (inputs == null)
            {
                if (this.InputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.InputParameterCount)));
                }
            }
            else if (inputs.Length != this.InputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.InputParameterCount, inputs.Length)));
            }

            this.outputs = EmptyArray.Allocate(this.OutputParameterCount);

            AsyncMethodInvoker.StartOperationInvokePerformanceCounters(this.taskMethod.Name);

            IAsyncResult         returnValue;
            bool                 callFailed  = true;
            bool                 callFaulted = false;
            ServiceModelActivity activity    = null;

            try
            {
                Activity boundActivity = null;
                AsyncMethodInvoker.CreateActivityInfo(ref activity, ref boundActivity);

                AsyncMethodInvoker.StartOperationInvokeTrace(this.taskMethod.Name);

                using (boundActivity)
                {
                    if (DiagnosticUtility.ShouldUseActivity)
                    {
                        string activityName = SR.GetString(SR.ActivityExecuteMethod, this.taskMethod.DeclaringType.FullName, this.taskMethod.Name);
                        ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
                    }

                    object taskReturnValue = this.InvokeDelegate(instance, inputs, this.outputs);

                    if (taskReturnValue == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("task");
                    }
                    else if (this.isGenericTask)
                    {
                        returnValue = (IAsyncResult)this.toAsyncMethodInfo.Invoke(null, new object[] { taskReturnValue, callback, state });
                    }
                    else
                    {
                        returnValue = ((Task)taskReturnValue).AsAsyncResult(callback, state);
                    }

                    callFailed = false;
                }
            }
            catch (System.Security.SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (Exception e)
            {
                TraceUtility.TraceUserCodeException(e, this.taskMethod);
                if (e is FaultException)
                {
                    callFaulted = true;
                    callFailed  = false;
                }

                throw;
            }
            finally
            {
                ServiceModelActivity.Stop(activity);

                // Any exception above means InvokeEnd will not be called, so complete it here.
                if (callFailed || callFaulted)
                {
                    AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, this.TaskMethod.Name);
                    AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.TaskMethod.Name);
                }
            }

            return(returnValue);
        }
Exemple #8
0
        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            object returnVal;
            bool   callFailed             = true;
            bool   callFaulted            = false;
            ServiceModelActivity activity = null;

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }

            try
            {
                Activity boundOperation = null;
                AsyncMethodInvoker.GetActivityInfo(ref activity, ref boundOperation);

                using (boundOperation)
                {
                    Task task = result as Task;

                    Fx.Assert(task != null, "InvokeEnd needs to be called with the result returned from InvokeBegin.");
                    if (task.IsFaulted)
                    {
                        Fx.Assert(task.Exception != null, "Task.IsFaulted guarantees non-null exception.");

                        // If FaultException is thrown, we will get 'callFaulted' behavior below.
                        // Any other exception will retain 'callFailed' behavior.
                        throw FxTrace.Exception.AsError <FaultException>(task.Exception);
                    }

                    // Task cancellation without an exception indicates failure but we have no
                    // additional information to provide.  Accessing Task.Result will throw a
                    // TaskCanceledException.   For consistency between void Tasks and Task<T>,
                    // we detect and throw here.
                    if (task.IsCanceled)
                    {
                        throw FxTrace.Exception.AsError(new TaskCanceledException(task));
                    }

                    outputs = this.outputs;
                    if (this.isGenericTask)
                    {
                        returnVal = this.taskTResultGetMethod.Invoke(result, Type.EmptyTypes);
                    }
                    else
                    {
                        returnVal = null;
                    }

                    callFailed = false;
                }
            }
            catch (SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (FaultException)
            {
                callFaulted = true;
                callFailed  = false;
                throw;
            }
            finally
            {
                ServiceModelActivity.Stop(activity);
                AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, this.TaskMethod.Name);
                AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.TaskMethod.Name);
            }

            return(returnVal);
        }
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            object obj2;

            this.EnsureIsInitialized();
            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxNoServiceObject")));
            }
            if (inputs == null)
            {
                if (this.inputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxInputParametersToServiceNull", new object[] { this.inputParameterCount })));
                }
            }
            else if (inputs.Length != this.inputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxInputParametersToServiceInvalid", new object[] { this.inputParameterCount, inputs.Length })));
            }
            outputs = EmptyArray.Allocate(this.outputParameterCount);
            long time       = 0L;
            long num2       = 0L;
            long startTicks = 0L;
            bool flag       = false;
            bool flag2      = false;

            if (PerformanceCounters.PerformanceCountersEnabled)
            {
                PerformanceCounters.MethodCalled(this.MethodName);
                try
                {
                    if (UnsafeNativeMethods.QueryPerformanceCounter(out time) == 0)
                    {
                        time = -1L;
                    }
                }
                catch (SecurityException exception)
                {
                    if (DiagnosticUtility.ShouldTraceWarning)
                    {
                        DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                    }
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityException(System.ServiceModel.SR.GetString("PartialTrustPerformanceCountersNotEnabled"), exception));
                }
            }
            if ((TD.OperationCompletedIsEnabled() || TD.OperationFaultedIsEnabled()) || TD.OperationFailedIsEnabled())
            {
                startTicks = DateTime.UtcNow.Ticks;
            }
            try
            {
                ServiceModelActivity activity   = null;
                IDisposable          disposable = null;
                if (DiagnosticUtility.ShouldUseActivity)
                {
                    activity   = ServiceModelActivity.CreateBoundedActivity(true);
                    disposable = activity;
                }
                else if (TraceUtility.MessageFlowTracingOnly)
                {
                    Guid receivedActivityId = TraceUtility.GetReceivedActivityId(OperationContext.Current);
                    if (receivedActivityId != Guid.Empty)
                    {
                        DiagnosticTrace.ActivityId = receivedActivityId;
                    }
                }
                else if (TraceUtility.ShouldPropagateActivity)
                {
                    Guid activityId = ActivityIdHeader.ExtractActivityId(OperationContext.Current.IncomingMessage);
                    if (activityId != Guid.Empty)
                    {
                        disposable = Activity.CreateActivity(activityId);
                    }
                }
                using (disposable)
                {
                    if (DiagnosticUtility.ShouldUseActivity)
                    {
                        ServiceModelActivity.Start(activity, System.ServiceModel.SR.GetString("ActivityExecuteMethod", new object[] { this.method.DeclaringType.FullName, this.method.Name }), ActivityType.ExecuteUserCode);
                    }
                    if (TD.OperationInvokedIsEnabled())
                    {
                        TD.OperationInvoked(this.MethodName, TraceUtility.GetCallerInfo(OperationContext.Current));
                    }
                    obj2 = this.invokeDelegate(instance, inputs, outputs);
                    flag = true;
                }
                return(obj2);
            }
            catch (FaultException)
            {
                flag2 = true;
                throw;
            }
            catch (SecurityException exception2)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            finally
            {
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    long num4 = 0L;
                    if ((time >= 0L) && (UnsafeNativeMethods.QueryPerformanceCounter(out num2) != 0))
                    {
                        num4 = num2 - time;
                    }
                    if (flag)
                    {
                        PerformanceCounters.MethodReturnedSuccess(this.MethodName, num4);
                    }
                    else if (flag2)
                    {
                        PerformanceCounters.MethodReturnedFault(this.MethodName, num4);
                    }
                    else
                    {
                        PerformanceCounters.MethodReturnedError(this.MethodName, num4);
                    }
                }
                if (startTicks != 0L)
                {
                    if (flag)
                    {
                        if (TD.OperationCompletedIsEnabled())
                        {
                            TD.OperationCompleted(this.methodName, TraceUtility.GetUtcBasedDurationForTrace(startTicks));
                        }
                    }
                    else if (flag2)
                    {
                        if (TD.OperationFaultedIsEnabled())
                        {
                            TD.OperationFaulted(this.methodName, TraceUtility.GetUtcBasedDurationForTrace(startTicks));
                        }
                    }
                    else if (TD.OperationFailedIsEnabled())
                    {
                        TD.OperationFailed(this.methodName, TraceUtility.GetUtcBasedDurationForTrace(startTicks));
                    }
                }
            }
            return(obj2);
        }
Exemple #10
0
        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            object obj2;

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxNoServiceObject")));
            }
            outputs = EmptyArray.Allocate(this.OutputParameterCount);
            bool flag  = true;
            bool flag2 = false;

            try
            {
                ServiceModelActivity activity       = null;
                Activity             boundOperation = null;
                this.GetActivityInfo(ref activity, ref boundOperation);
                using (boundOperation)
                {
                    obj2 = this.InvokeEndDelegate(instance, outputs, result);
                    flag = false;
                }
                ServiceModelActivity.Stop(activity);
            }
            catch (SecurityException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (FaultException)
            {
                flag2 = true;
                flag  = false;
                throw;
            }
            finally
            {
                if (flag)
                {
                    if (TD.OperationFailedIsEnabled())
                    {
                        TD.OperationFailed(this.EndMethod.Name, TraceUtility.GetUtcBasedDurationForTrace(TraceUtility.ExtractAsyncOperationStartTime()));
                    }
                }
                else if (flag2)
                {
                    if (TD.OperationFaultedIsEnabled())
                    {
                        TD.OperationFaulted(this.EndMethod.Name, TraceUtility.GetUtcBasedDurationForTrace(TraceUtility.ExtractAsyncOperationStartTime()));
                    }
                }
                else if (TD.OperationCompletedIsEnabled())
                {
                    TD.OperationCompleted(this.EndMethod.Name, TraceUtility.GetUtcBasedDurationForTrace(TraceUtility.ExtractAsyncOperationStartTime()));
                }
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    if (flag)
                    {
                        PerformanceCounters.MethodReturnedError(this.endMethod.Name.Substring("End".Length));
                    }
                    else if (flag2)
                    {
                        PerformanceCounters.MethodReturnedFault(this.endMethod.Name.Substring("End".Length));
                    }
                    else
                    {
                        PerformanceCounters.MethodReturnedSuccess(this.endMethod.Name.Substring("End".Length));
                    }
                }
            }
            return(obj2);
        }
Exemple #11
0
        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            IAsyncResult result;

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxNoServiceObject")));
            }
            if (inputs == null)
            {
                if (this.InputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxInputParametersToServiceNull", new object[] { this.InputParameterCount })));
                }
            }
            else if (inputs.Length != this.InputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxInputParametersToServiceInvalid", new object[] { this.InputParameterCount, inputs.Length })));
            }
            if (PerformanceCounters.PerformanceCountersEnabled)
            {
                PerformanceCounters.MethodCalled(this.beginMethod.Name.Substring("Begin".Length));
            }
            try
            {
                ServiceModelActivity activity      = null;
                Activity             boundActivity = null;
                this.CreateActivityInfo(ref activity, ref boundActivity);
                if (TD.OperationInvokedIsEnabled())
                {
                    TD.OperationInvoked(this.beginMethod.Name.Substring("Begin".Length), TraceUtility.GetCallerInfo(OperationContext.Current));
                }
                if ((TD.OperationCompletedIsEnabled() || TD.OperationFaultedIsEnabled()) || TD.OperationFailedIsEnabled())
                {
                    TraceUtility.UpdateAsyncOperationContextWithStartTime(DateTime.UtcNow.Ticks);
                }
                using (boundActivity)
                {
                    if (DiagnosticUtility.ShouldUseActivity)
                    {
                        string activityName = null;
                        if (this.endMethod == null)
                        {
                            activityName = System.ServiceModel.SR.GetString("ActivityExecuteMethod", new object[] { this.beginMethod.DeclaringType.FullName, this.beginMethod.Name });
                        }
                        else
                        {
                            activityName = System.ServiceModel.SR.GetString("ActivityExecuteAsyncMethod", new object[] { this.beginMethod.DeclaringType.FullName, this.beginMethod.Name, this.endMethod.DeclaringType.FullName, this.endMethod.Name });
                        }
                        ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
                    }
                    result = this.InvokeBeginDelegate(instance, inputs, callback, state);
                }
                ServiceModelActivity.Stop(activity);
            }
            catch (SecurityException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (Exception exception2)
            {
                TraceUtility.TraceUserCodeException(exception2, this.beginMethod);
                throw;
            }
            return(result);
        }
 static AuthorizationBehavior CreateAuthorizationBehavior(DispatchRuntime dispatch)
 {
     AuthorizationBehavior behavior = new AuthorizationBehavior();
     behavior.externalAuthorizationPolicies = dispatch.ExternalAuthorizationPolicies;
     behavior.serviceAuthorizationManager = dispatch.ServiceAuthorizationManager;
     behavior.auditLogLocation = dispatch.SecurityAuditLogLocation;
     behavior.suppressAuditFailure = dispatch.SuppressAuditFailure;
     behavior.serviceAuthorizationAuditLevel = dispatch.ServiceAuthorizationAuditLevel;
     return behavior;
 }
        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }

            object returnVal                    = null;
            bool   callFailed                   = true;
            bool   callFaulted                  = false;
            ServiceModelActivity activity       = null;
            Activity             boundOperation = null;

            try
            {
                AsyncMethodInvoker.GetActivityInfo(ref activity, ref boundOperation);

                Task <Tuple <object, object[]> > invokeTask = result as Task <Tuple <object, object[]> >;

                if (invokeTask == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SFxInvalidCallbackIAsyncResult));
                }

                AggregateException       ae    = null;
                Tuple <object, object[]> tuple = null;
                Task task = null;

                if (invokeTask.IsFaulted)
                {
                    Fx.Assert(invokeTask.Exception != null, "Task.IsFaulted guarantees non-null exception.");
                    ae = invokeTask.Exception;
                }
                else
                {
                    Fx.Assert(invokeTask.IsCompleted, "Task.Result is expected to be completed");

                    tuple = invokeTask.Result;
                    task  = tuple.Item1 as Task;

                    if (task == null)
                    {
                        outputs = tuple.Item2;
                        return(null);
                    }

                    if (task.IsFaulted)
                    {
                        Fx.Assert(task.Exception != null, "Task.IsFaulted guarantees non-null exception.");
                        ae = task.Exception;
                    }
                }

                if (ae != null && ae.InnerException != null)
                {
                    if (ae.InnerException is FaultException)
                    {
                        // If invokeTask.IsFaulted we produce the 'callFaulted' behavior below.
                        // Any other exception will retain 'callFailed' behavior.
                        callFaulted = true;
                        callFailed  = false;
                    }

                    if (ae.InnerException is SecurityException)
                    {
                        DiagnosticUtility.TraceHandledException(ae.InnerException, TraceEventType.Warning);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
                    }

                    invokeTask.GetAwaiter().GetResult();
                }

                // Task cancellation without an exception indicates failure but we have no
                // additional information to provide.  Accessing Task.Result will throw a
                // TaskCanceledException.   For consistency between void Tasks and Task<T>,
                // we detect and throw here.
                if (task.IsCanceled)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TaskCanceledException(task));
                }

                outputs = tuple.Item2;

                returnVal  = this.isGenericTask ? this.taskTResultGetMethod.Invoke(task, Type.EmptyTypes) : null;
                callFailed = false;

                return(returnVal);
            }
            finally
            {
                if (boundOperation != null)
                {
                    ((IDisposable)boundOperation).Dispose();
                }

                ServiceModelActivity.Stop(activity);
                AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, this.TaskMethod.Name);
                AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.TaskMethod.Name);
            }
        }
        private async Task <Tuple <object, object[]> > InvokeAsync(object instance, object[] inputs)
        {
            EnsureIsInitialized();

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }

            if (inputs == null)
            {
                if (this.inputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.inputParameterCount)));
                }
            }
            else if (inputs.Length != this.inputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.inputParameterCount, inputs.Length)));
            }

            object[] outputs = EmptyArray.Allocate(this.outputParameterCount);

            AsyncMethodInvoker.StartOperationInvokePerformanceCounters(this.taskMethod.Name);

            object returnValue;
            ServiceModelActivity activity      = null;
            Activity             boundActivity = null;

            try
            {
                AsyncMethodInvoker.CreateActivityInfo(ref activity, ref boundActivity);
                AsyncMethodInvoker.StartOperationInvokeTrace(this.taskMethod.Name);

                if (DiagnosticUtility.ShouldUseActivity)
                {
                    string activityName = SR.GetString(SR.ActivityExecuteMethod, this.taskMethod.DeclaringType.FullName, this.taskMethod.Name);
                    ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
                }

                OperationContext.EnableAsyncFlow();

                returnValue = this.invokeDelegate(instance, inputs, outputs);

                if (returnValue == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("task");
                }

                var returnValueTask = returnValue as Task;

                if (returnValueTask != null)
                {
                    // Only return once the task has completed
                    await returnValueTask;
                }

                return(Tuple.Create(returnValue, outputs));
            }
            catch (SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            catch (Exception e)
            {
                TraceUtility.TraceUserCodeException(e, this.taskMethod);
                throw;
            }
            finally
            {
                OperationContext.DisableAsyncFlow();

                if (boundActivity != null)
                {
                    ((IDisposable)boundActivity).Dispose();
                }

                ServiceModelActivity.Stop(activity);
            }
        }