public void StopImpersonation(IDisposable impersonationContext, IPrincipal originalPrincipal, bool isThreadPrincipalSet)
 {
     if (OperationContext.Current != null)
     {
         EndpointDispatcher endpointDispatcher = OperationContext.Current.EndpointDispatcher;
         if (endpointDispatcher != null)
         {
             DispatchRuntime          dispatchRuntime = endpointDispatcher.DispatchRuntime;
             ImmutableDispatchRuntime runtime         = dispatchRuntime.GetRuntime();
             if (runtime != null && runtime.SecurityImpersonation != null)
             {
                 runtime.SecurityImpersonation.StopImpersonation(ref this.rpc, impersonationContext, originalPrincipal, isThreadPrincipalSet);
             }
         }
     }
 }
        /// <summary>
        /// Executes a Func<typeparamref name="T"/> with the caller's context if impersonation is enabled on the service and sets the appropriate principal on the thread as per the service configuration.
        /// </summary>
        /// <param name="func">The function to execute under caller's impersonated context</param>
        /// <returns>The return value from executing the func</returns>
        public T RunImpersonated <T>(Func <T> func)
        {
            if (OperationContext.Current != null)
            {
                EndpointDispatcher endpointDispatcher = OperationContext.Current.EndpointDispatcher;
                if (endpointDispatcher != null)
                {
                    DispatchRuntime          dispatchRuntime = endpointDispatcher.DispatchRuntime;
                    ImmutableDispatchRuntime runtime         = dispatchRuntime.GetRuntime();
                    if (runtime != null && runtime.SecurityImpersonation != null)
                    {
                        return(runtime.SecurityImpersonation.RunImpersonated(_rpc, func));
                    }
                }
            }

            return(func());
        }