Beispiel #1
0
        /// <summary>
        /// Execute an asynchronous redis operation.
        /// </summary>
        /// <typeparam name="T">The result type</typeparam>
        /// <param name="obj">The this object</param>
        /// <param name="message">The message</param>
        /// <param name="processor">The result processor</param>
        /// <param name="server">The server</param>
        /// <returns>An asynchronous task.</returns>
        public static object ExecuteAsync <T>(object obj, object message, object processor, object server)
        {
            var resultType    = typeof(Task <T>);
            var asm           = obj.GetType().Assembly;
            var batchType     = asm.GetType("StackExchange.Redis.RedisBatch");
            var messageType   = asm.GetType("StackExchange.Redis.Message");
            var processorType = asm.GetType("StackExchange.Redis.ResultProcessor`1").MakeGenericType(typeof(T));
            var serverType    = asm.GetType("StackExchange.Redis.ServerEndPoint");

            var originalMethod = DynamicMethodBuilder <Func <object, object, object, object, Task <T> > > .CreateMethodCallDelegate(
                obj.GetType(),
                "ExecuteAsync",
                new Type[] { messageType, processorType, serverType },
                new Type[] { resultType });

            // we only trace RedisBatch methods here
            if (obj.GetType() == batchType)
            {
                using (var scope = CreateScope(obj, message, server))
                {
                    return(scope.Span.Trace(() => originalMethod(obj, message, processor, server)));
                }
            }
            else
            {
                return(originalMethod(obj, message, processor, server));
            }
        }
Beispiel #2
0
        /// <summary>
        /// ExecuteAsync calls the underlying ExecuteAsync and traces the request.
        /// </summary>
        /// <param name="this">The Api Controller</param>
        /// <param name="controllerContext">The controller context for the call</param>
        /// <param name="cancellationTokenSource">The cancellation token source</param>
        /// <returns>A task with the result</returns>
        public static object ExecuteAsync(object @this, object controllerContext, object cancellationTokenSource)
        {
            Type controllerType = @this.GetType();

            // in some cases, ExecuteAsync() is an explicit interface implementation,
            // which is not public and has a different name, so try both
            var executeAsyncFunc =
                DynamicMethodBuilder <Func <object, object, CancellationToken, object> >
                .GetOrCreateMethodCallDelegate(controllerType, "ExecuteAsync") ??
                DynamicMethodBuilder <Func <object, object, CancellationToken, object> >
                .GetOrCreateMethodCallDelegate(controllerType, "System.Web.Http.Controllers.IHttpController.ExecuteAsync");

            using (Scope scope = CreateScope(controllerContext))
            {
                return(scope.Span.Trace(
                           () =>
                {
                    CancellationToken cancellationToken = ((CancellationTokenSource)cancellationTokenSource).Token;
                    return executeAsyncFunc(@this, controllerContext, cancellationToken);
                },
                           onComplete: e =>
                {
                    if (e != null)
                    {
                        scope.Span.SetException(e);
                    }

                    // some fields aren't set till after execution, so repopulate anything missing
                    UpdateSpan(controllerContext, scope.Span);
                    scope.Span.Finish();
                }));
            }
        }
Beispiel #3
0
        private static async Task <object> ExecuteAsyncInternal(object wireProtocol, object connection, CancellationToken cancellationToken)
        {
            if (wireProtocol == null)
            {
                throw new ArgumentNullException(nameof(wireProtocol));
            }

            var executeAsync = DynamicMethodBuilder <Func <object, object, CancellationToken, Task <object> > >
                               .GetOrCreateMethodCallDelegate(
                wireProtocol.GetType(),
                "ExecuteAsync");

            using (var scope = CreateScope(wireProtocol, connection))
            {
                try
                {
                    return(await executeAsync(wireProtocol, connection, cancellationToken).ConfigureAwait(false));
                }
                catch (Exception ex) when(scope?.Span.SetExceptionForFilter(ex) ?? false)
                {
                    // unreachable code
                    throw;
                }
            }
        }
        /// <summary>
        /// ExecuteReader traces any SQL call.
        /// </summary>
        /// <param name="this">The "this" pointer for the method call.</param>
        /// <param name="behavior">The behavior.</param>
        /// <param name="method">The method.</param>
        /// <returns>The original methods return.</returns>
        public static object ExecuteReaderWithMethod(dynamic @this, int behavior, string method)
        {
            var command = (DbCommand)@this;

            if (_executeReaderWithMethod == null)
            {
                _executeReaderWithMethod = DynamicMethodBuilder.CreateMethodCallDelegate <Func <object, CommandBehavior, string, object> >(
                    command.GetType(),
                    "ExecuteReader",
                    isStatic: false);
            }

            using (var scope = CreateScope(command))
            {
                try
                {
                    return(_executeReaderWithMethod(command, (CommandBehavior)behavior, method));
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
        public static T ExecuteSyncImpl <T>(object multiplexer, object message, object processor, object server)
        {
            var resultType      = typeof(T);
            var multiplexerType = multiplexer.GetType();
            var asm             = multiplexerType.Assembly;
            var messageType     = asm.GetType("StackExchange.Redis.Message");
            var processorType   = asm.GetType("StackExchange.Redis.ResultProcessor`1").MakeGenericType(resultType);
            var serverType      = asm.GetType("StackExchange.Redis.ServerEndPoint");

            var originalMethod = DynamicMethodBuilder <Func <object, object, object, object, T> >
                                 .CreateMethodCallDelegate(
                multiplexerType,
                "ExecuteSyncImpl",
                new[] { messageType, processorType, serverType },
                new[] { resultType });

            using (var scope = CreateScope(multiplexer, message))
            {
                try
                {
                    return(originalMethod(multiplexer, message, processor, server));
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// ExecuteReader traces any SQL call.
        /// </summary>
        /// <param name="this">The "this" pointer for the method call.</param>
        /// <param name="behavior">The behavior.</param>
        /// <returns>The original methods return.</returns>
        public static object ExecuteReader(dynamic @this, int behavior)
        {
            var command = (DbCommand)@this;

            if (_executeReader == null)
            {
                _executeReader = DynamicMethodBuilder <Func <object, CommandBehavior, object> > .CreateMethodCallDelegate(
                    command.GetType(),
                    "ExecuteReader",
                    new Type[] { typeof(CommandBehavior) });
            }

            using (var scope = CreateScope(command))
            {
                try
                {
                    return(_executeReader(command, (CommandBehavior)behavior));
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Calls the underlying ExecuteAsync and traces the request.
        /// </summary>
        /// <param name="apiController">The Api Controller</param>
        /// <param name="controllerContext">The controller context for the call</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A task with the result</returns>
        private static async Task <HttpResponseMessage> ExecuteAsyncInternal(object apiController, object controllerContext, CancellationToken cancellationToken)
        {
            Type controllerType = apiController.GetType();

            // in some cases, ExecuteAsync() is an explicit interface implementation,
            // which is not public and has a different name, so try both
            var executeAsyncFunc =
                DynamicMethodBuilder <Func <object, object, CancellationToken, Task <HttpResponseMessage> > >
                .GetOrCreateMethodCallDelegate(controllerType, "ExecuteAsync") ??
                DynamicMethodBuilder <Func <object, object, CancellationToken, Task <HttpResponseMessage> > >
                .GetOrCreateMethodCallDelegate(controllerType, "System.Web.Http.Controllers.IHttpController.ExecuteAsync");

            using (Scope scope = CreateScope(controllerContext))
            {
                try
                {
                    var responseMessage = await executeAsyncFunc(apiController, controllerContext, cancellationToken).ConfigureAwait(false);

                    // some fields aren't set till after execution, so populate anything missing
                    UpdateSpan(controllerContext, scope.Span);

                    return(responseMessage);
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
        /// <summary>
        /// Execute an asynchronous redis operation.
        /// </summary>
        /// <typeparam name="T">The result type</typeparam>
        /// <param name="multiplexer">The connection multiplexer running the command.</param>
        /// <param name="message">The message to send to redis.</param>
        /// <param name="processor">The processor to handle the result.</param>
        /// <param name="state">The state to use for the task.</param>
        /// <param name="server">The server to call.</param>
        /// <returns>An asynchronous task.</returns>
        private static async Task <T> ExecuteAsyncImplInternal <T>(object multiplexer, object message, object processor, object state, object server)
        {
            var genericType     = typeof(T);
            var multiplexerType = multiplexer.GetType();
            var asm             = multiplexerType.Assembly;
            var messageType     = asm.GetType("StackExchange.Redis.Message");
            var processorType   = asm.GetType("StackExchange.Redis.ResultProcessor`1").MakeGenericType(genericType);
            var stateType       = typeof(object);
            var serverType      = asm.GetType("StackExchange.Redis.ServerEndPoint");

            var originalMethod = DynamicMethodBuilder <Func <object, object, object, object, object, Task <T> > >
                                 .CreateMethodCallDelegate(
                multiplexerType,
                "ExecuteAsyncImpl",
                new[] { messageType, processorType, stateType, serverType },
                new[] { genericType });

            using (var scope = CreateScope(multiplexer, message))
            {
                try
                {
                    return(await originalMethod(multiplexer, message, processor, state, server).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
Beispiel #9
0
        public static object Execute(object wireProtocol, object connection, object cancellationTokenSource)
        {
            // TResult MongoDB.Driver.Core.WireProtocol.IWireProtocol<TResult>.Execute(IConnection connection, CancellationToken cancellationToken)
            if (wireProtocol == null)
            {
                throw new ArgumentNullException(nameof(wireProtocol));
            }

            var execute = DynamicMethodBuilder <Func <object, object, CancellationToken, object> >
                          .GetOrCreateMethodCallDelegate(
                wireProtocol.GetType(),
                "Execute");

            using (var scope = CreateScope(wireProtocol, connection))
            {
                try
                {
                    var tokenSource       = cancellationTokenSource as CancellationTokenSource;
                    var cancellationToken = tokenSource?.Token ?? CancellationToken.None;
                    return(execute(wireProtocol, connection, cancellationToken));
                }
                catch (Exception ex) when(scope?.Span.SetExceptionForFilter(ex) ?? false)
                {
                    // unreachable code
                    throw;
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Traces an asynchronous call to Elasticsearch.
        /// </summary>
        /// <typeparam name="TResponse">Type type of the response</typeparam>
        /// <param name="pipeline">The pipeline for the original method</param>
        /// <param name="requestData">The request data</param>
        /// <param name="cancellationToken">A cancellation token</param>
        /// <returns>The original result</returns>
        private static async Task <TResponse> CallElasticsearchAsyncInternal <TResponse>(object pipeline, object requestData, CancellationToken cancellationToken)
        {
            if (_requestDataType == null)
            {
                _requestDataType = requestData.GetType();
            }

            var originalMethod = DynamicMethodBuilder <Func <object, object, CancellationToken, Task <TResponse> > >
                                 .GetOrCreateMethodCallDelegate(
                pipeline.GetType(),
                "CallElasticsearchAsync",
                new[] { _requestDataType, CancellationTokenType },
                new[] { typeof(TResponse) });

            using (var scope = CreateScope(pipeline, requestData))
            {
                try
                {
                    return(await originalMethod(pipeline, requestData, cancellationToken).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    scope.Span.SetException(ex);
                    throw;
                }
            }
        }
Beispiel #11
0
 /// <summary>
 /// 调用初始化拦截器的方法。
 /// </summary>
 /// <param name="emitter"></param>
 /// <param name="initMethod"></param>
 /// <returns></returns>
 private static EmitHelper CallInitialize(this EmitHelper emitter, DynamicMethodBuilder initMethod)
 {
     return(emitter
            .ldarg_0
            .ldloc(STACK_INTERCEPTOR_LIST_INDEX)
            .ldloc(STACK_CALLINFO_INDEX)
            .call(initMethod.MethodBuilder));
 }
Beispiel #12
0
 public static void GetDiv()
 {
     var func = new DynamicMethodBuilder <Func <int, int, int> >("GetDiv")
                .IL(il => il
                    .Divide(il.LoadArgument(0, 1))     // пусть принимает Builder?
                    .Return())
                .Build();
 }
Beispiel #13
0
 public static void GetRem()
 {
     var func = new DynamicMethodBuilder <Func <int, int, int> >("GetRem")
                .IL(il => il
                    .Remainder(il.LoadArgument(0, 1))
                    .Return())
                .Build();
 }
Beispiel #14
0
 /// <summary>
 /// 调用拦截器。
 /// </summary>
 /// <param name="emitter"></param>
 /// <param name="interceptMethod"></param>
 /// <param name="interceptType"></param>
 /// <returns></returns>
 private static EmitHelper CallInterceptors(this EmitHelper emitter, DynamicMethodBuilder interceptMethod, InterceptType interceptType)
 {
     return(emitter
            .ldarg_0
            .ldloc(STACK_INTERCEPTOR_LIST_INDEX)
            .ldloc(STACK_CALLINFO_INDEX)
            .ldc_i4((int)interceptType)
            .call(interceptMethod.MethodBuilder));
 }
Beispiel #15
0
        public static Func <T> GetEmptyObject2 <T>()
        {
            var func = new DynamicMethodBuilder <Func <T> >("GetEmptyObject")
                       .Locals <Types <T> >()
                       .IL(il => il
                           .Return(il.LoadLocal(0)))
                       .Build();

            return(func);
        }
 protected override IMethodBuilder GetMethodBuilder()
 {
     var dynamicMethodBuilder = new DynamicMethodBuilder();
     var field = typeof(DynamicMethodBuilder).GetField(
         "methodSkeletonFactory", BindingFlags.Instance | BindingFlags.NonPublic);
     var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DynamicMethodAssembly.dll");
     Func<IDynamicMethodSkeleton> methodSkeletonFactory = () => new InterceptionMethodBuilderMethodSkeleton(path);
     field.SetValue(dynamicMethodBuilder, methodSkeletonFactory);
     return dynamicMethodBuilder;
 }
Beispiel #17
0
        /// <summary>
        /// Traces SendReceive.
        /// </summary>
        /// <typeparam name="T">The return type</typeparam>
        /// <param name="redisNativeClient">The redis native client</param>
        /// <param name="cmdWithBinaryArgs">The command with args</param>
        /// <param name="fn">The function</param>
        /// <param name="completePipelineFn">An optional function to call to complete a pipeline</param>
        /// <param name="sendWithoutRead">Whether or to send without waiting for the result</param>
        /// <returns>The original result</returns>
        public static T SendReceive <T>(object redisNativeClient, byte[][] cmdWithBinaryArgs, object fn, object completePipelineFn, bool sendWithoutRead)
        {
            var originalMethod = DynamicMethodBuilder <Func <object, byte[][], object, object, bool, T> > .GetOrCreateMethodCallDelegate(
                redisNativeClient.GetType(), "SendReceive", methodGenericArguments : new Type[] { typeof(T) });

            using (var scope = Integrations.Redis.CreateScope(GetHost(redisNativeClient), GetPort(redisNativeClient), GetRawCommand(cmdWithBinaryArgs)))
            {
                return((T)scope.Span.Trace(() => originalMethod(redisNativeClient, cmdWithBinaryArgs, fn, completePipelineFn, sendWithoutRead)));
            }
        }
Beispiel #18
0
        public static Func <T> GetEmptyObject <T>()
        {
            var func = new DynamicMethodBuilder <Func <T> >("GetEmptyObject")
                       .IL(il => il
                           .NewObject <T>()
                           .Return())
                       .Build();

            return(func);
        }
Beispiel #19
0
 public static void GetDivRemAdd()
 {
     var func = new DynamicMethodBuilder <Func <int, int, int> >("GetDivRemAdd")
                .IL(il => il
                    .Divide(il.LoadArgument(0), il.LoadArgument(1))
                    .Remainder(il.LoadArgument(0), il.LoadArgument(1))
                    .Add()
                    .Return())
                .Build();
 }
Beispiel #20
0
        internal static DynamicMethod CreateInvokeExact(MethodType type)
        {
            FinishTypes(type);
            DynamicMethodBuilder dm = new DynamicMethodBuilder("InvokeExact", type, typeof(MethodHandle), null, null, null, false);
            Type targetDelegateType = GetMemberWrapperDelegateType(type.insertParameterTypes(0, CoreClasses.java.lang.invoke.MethodHandle.Wrapper.ClassObject));

            dm.ilgen.Emit(OpCodes.Ldarg_0);
            dm.ilgen.Emit(OpCodes.Ldfld, typeof(MethodHandle).GetField("form", BindingFlags.Instance | BindingFlags.NonPublic));
            dm.ilgen.Emit(OpCodes.Ldfld, typeof(LambdaForm).GetField("vmentry", BindingFlags.Instance | BindingFlags.NonPublic));
            if (type.returnType() == java.lang.Void.TYPE)
            {
                dm.ilgen.Emit(OpCodes.Call, typeof(MethodHandleUtil).GetMethod("GetVoidAdapter", BindingFlags.Static | BindingFlags.NonPublic));
            }
            else
            {
                dm.ilgen.Emit(OpCodes.Ldfld, typeof(MemberName).GetField("vmtarget", BindingFlags.Instance | BindingFlags.NonPublic));
            }
            dm.ilgen.Emit(OpCodes.Castclass, targetDelegateType);
            dm.ilgen.Emit(OpCodes.Ldarg_0);
            for (int i = 0; i < type.parameterCount(); i++)
            {
                dm.Ldarg(i);
                TypeWrapper tw = TypeWrapper.FromClass(type.parameterType(i));
                if (tw.IsNonPrimitiveValueType)
                {
                    tw.EmitBox(dm.ilgen);
                }
                else if (tw.IsGhost)
                {
                    tw.EmitConvSignatureTypeToStackType(dm.ilgen);
                }
                else if (tw == PrimitiveTypeWrapper.BYTE)
                {
                    dm.ilgen.Emit(OpCodes.Conv_I1);
                }
            }
            dm.CallDelegate(targetDelegateType);
            TypeWrapper retType = TypeWrapper.FromClass(type.returnType());

            if (retType.IsNonPrimitiveValueType)
            {
                retType.EmitUnbox(dm.ilgen);
            }
            else if (retType.IsGhost)
            {
                retType.EmitConvStackTypeToSignatureType(dm.ilgen, null);
            }
            else if (!retType.IsPrimitive && retType != CoreClasses.java.lang.Object.Wrapper)
            {
                dm.EmitCheckcast(retType);
            }
            dm.Ret();
            dm.ilgen.DoEmit();
            return(dm.dm);
        }
Beispiel #21
0
        protected override IMethodBuilder GetMethodBuilder()
        {
            var dynamicMethodBuilder = new DynamicMethodBuilder();
            var field = typeof(DynamicMethodBuilder).GetField(
                "methodSkeletonFactory", BindingFlags.Instance | BindingFlags.NonPublic);
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DynamicMethodAssembly.dll");
            Func <IDynamicMethodSkeleton> methodSkeletonFactory = () => new InterceptionMethodBuilderMethodSkeleton(path);

            field.SetValue(dynamicMethodBuilder, methodSkeletonFactory);
            return(dynamicMethodBuilder);
        }
        public static void AfterAction(
            object diagnosticSource,
            object actionDescriptor,
            object httpContext,
            object routeData)
        {
            AspNetCoreMvc2Integration integration = null;

            try
            {
                if (httpContext.TryGetPropertyValue("Items", out IDictionary <object, object> contextItems))
                {
                    integration = contextItems?[HttpContextKey] as AspNetCoreMvc2Integration;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorExceptionForFilter($"Error accessing {nameof(AspNetCoreMvc2Integration)}.", ex);
            }

            try
            {
                if (_afterAction == null)
                {
                    var type = actionDescriptor.GetType().Assembly.GetType("Microsoft.AspNetCore.Mvc.Internal.MvcCoreDiagnosticSourceExtensions");

                    _afterAction = DynamicMethodBuilder <Action <object, object, object, object> > .CreateMethodCallDelegate(
                        type,
                        "AfterAction");
                }
            }
            catch
            {
                // TODO: log this as an instrumentation error, we cannot call instrumented method,
                // profiled app will continue working without DiagnosticSource
            }

            try
            {
                // call the original method, catching and rethrowing any unhandled exceptions
                _afterAction?.Invoke(diagnosticSource, actionDescriptor, httpContext, routeData);
            }
            catch (Exception ex)
            {
                integration?.SetException(ex);

                throw;
            }
            finally
            {
                integration?.Dispose();
            }
        }
Beispiel #23
0
        /// <summary>
        /// CallElasticsearch traces a call to Elasticsearch
        /// </summary>
        /// <typeparam name="TResponse">The type of the response</typeparam>
        /// <param name="pipeline">The pipeline for the original method</param>
        /// <param name="requestData">The request data</param>
        /// <returns>The original result</returns>
        public static object CallElasticsearch <TResponse>(object pipeline, object requestData)
        {
            var originalMethod = DynamicMethodBuilder <Func <object, object, TResponse> > .GetOrCreateMethodCallDelegate(
                pipeline.GetType(),
                "CallElasticsearch",
                methodGenericArguments : new Type[] { typeof(TResponse) });

            return(CreateScope(pipeline, requestData).Span.Trace(() =>
            {
                return originalMethod(pipeline, requestData);
            }));
        }
        protected override IMethodBuilder GetMethodBuilder()
        {
            var dynamicMethodBuilder = new DynamicMethodBuilder();
            var field = typeof(DynamicMethodBuilder).GetField(
                "methodSkeletonFactory", BindingFlags.Instance | BindingFlags.NonPublic);

            var path = Path.Combine(Path.GetDirectoryName(new Uri(typeof(DynamicMethodBuilderVerificationTests).Assembly.CodeBase).LocalPath), "DynamicMethodAssembly.dll");

            Func <IDynamicMethodSkeleton> methodSkeletonFactory = () => new InterceptionMethodBuilderMethodSkeleton(path);

            field.SetValue(dynamicMethodBuilder, methodSkeletonFactory);
            return(dynamicMethodBuilder);
        }
Beispiel #25
0
        internal IdentityField(IdentitySpecification <TEntity> identitySpecification)
        {
            this.identitySpecification = identitySpecification;

            this.nextIdentity = this.identitySpecification.Seed;

            MemberExpression member       = ExpressionHelper.FindMemberExpression(identitySpecification.IdentityColumn.Body);
            PropertyInfo     identityInfo = member.Member as PropertyInfo;

            this.identityType   = identityInfo.PropertyType;
            this.identitySetter = DynamicMethodBuilder.CreatePropertySetter <TEntity>(identityInfo);
            this.identityGetter = this.identitySpecification.IdentityColumn.Compile();
        }
        /// <summary>
        /// Wrapper method used to instrument Microsoft.AspNetCore.Mvc.Internal.MvcCoreDiagnosticSourceExtensions.AfterAction()
        /// </summary>
        /// <param name="diagnosticSource">The DiagnosticSource that this extension method was called on.</param>
        /// <param name="actionDescriptor">An ActionDescriptor with information about the current action.</param>
        /// <param name="httpContext">The HttpContext for the current request.</param>
        /// <param name="routeData">A RouteData with information about the current route.</param>
        public static void AfterAction(
            object diagnosticSource,
            object actionDescriptor,
            dynamic httpContext,
            object routeData)
        {
            AspNetCoreMvc2Integration integration = null;

            try
            {
                IDictionary <object, object> contextItems = httpContext?.Items;
                integration = contextItems?[HttpContextKey] as AspNetCoreMvc2Integration;
            }
            catch
            {
                // TODO: log this as an instrumentation error, but continue calling instrumented method
            }

            try
            {
                if (_afterAction == null)
                {
                    Type type = actionDescriptor.GetType().Assembly.GetType("Microsoft.AspNetCore.Mvc.Internal.MvcCoreDiagnosticSourceExtensions");

                    _afterAction = DynamicMethodBuilder.CreateMethodCallDelegate <Action <object, object, object, object> >(
                        type,
                        "AfterAction",
                        isStatic: true);
                }
            }
            catch
            {
                // TODO: log this as an instrumentation error, we cannot call instrumented method,
                // profiled app will continue working without DiagnosticSource
            }

            try
            {
                // call the original method, catching and rethrowing any unhandled exceptions
                _afterAction?.Invoke(diagnosticSource, actionDescriptor, httpContext, routeData);
            }
            catch (Exception ex)
            {
                integration?.SetException(ex);
                throw;
            }
            finally
            {
                integration?.Dispose();
            }
        }
        public static void BeforeAction(
            object diagnosticSource,
            object actionDescriptor,
            object httpContext,
            object routeData)
        {
            AspNetCoreMvc2Integration integration = null;

            try
            {
                integration = new AspNetCoreMvc2Integration(actionDescriptor, httpContext);

                if (httpContext.TryGetPropertyValue("Items", out IDictionary <object, object> contextItems))
                {
                    contextItems[HttpContextKey] = integration;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorExceptionForFilter($"Error creating {nameof(AspNetCoreMvc2Integration)}.", ex);
            }

            try
            {
                if (_beforeAction == null)
                {
                    var assembly = actionDescriptor.GetType().GetTypeInfo().Assembly;
                    var type     = assembly.GetType("Microsoft.AspNetCore.Mvc.Internal.MvcCoreDiagnosticSourceExtensions");

                    _beforeAction = DynamicMethodBuilder <Action <object, object, object, object> > .CreateMethodCallDelegate(
                        type,
                        "BeforeAction");
                }
            }
            catch (Exception ex)
            {
                // profiled app will continue working without DiagnosticSource
                Log.ErrorException("Error calling Microsoft.AspNetCore.Mvc.Internal.MvcCoreDiagnosticSourceExtensions.BeforeAction()", ex);
            }

            try
            {
                // call the original method, catching and rethrowing any unhandled exceptions
                _beforeAction?.Invoke(diagnosticSource, actionDescriptor, httpContext, routeData);
            }
            catch (Exception ex) when(integration?.SetException(ex) ?? false)
            {
                // unreachable code
                throw;
            }
        }
Beispiel #28
0
    // called from InvokeExact DynamicMethod and ByteCodeHelper.GetDelegateForInvokeBasic()
    internal static object GetVoidAdapter(MemberName mn)
    {
        MethodType type = mn.getMethodType();

        if (type.voidAdapter == null)
        {
            if (type.returnType() == java.lang.Void.TYPE)
            {
                return(mn.vmtarget);
            }
            type.voidAdapter = DynamicMethodBuilder.CreateVoidAdapter(type);
        }
        return(type.voidAdapter);
    }
Beispiel #29
0
        public static void BeforeAction(
            object diagnosticSource,
            object actionDescriptor,
            dynamic httpContext,
            object routeData)
        {
            AspNetCoreMvc2Integration integration = null;

            try
            {
                integration = new AspNetCoreMvc2Integration(actionDescriptor, httpContext);
                IDictionary <object, object> contextItems = httpContext.Items;
                contextItems[HttpContextKey] = integration;
            }
            catch
            {
                // TODO: log this as an instrumentation error, but continue calling instrumented method
            }

            try
            {
                if (_beforeAction == null)
                {
                    Assembly assembly = actionDescriptor.GetType().GetTypeInfo().Assembly;
                    Type     type     = assembly.GetType("Microsoft.AspNetCore.Mvc.Internal.MvcCoreDiagnosticSourceExtensions");

                    _beforeAction = DynamicMethodBuilder <Action <object, object, object, object> > .CreateMethodCallDelegate(
                        type,
                        "BeforeAction");
                }
            }
            catch
            {
                // TODO: log this as an instrumentation error, we cannot call instrumented method,
                // profiled app will continue working without DiagnosticSource
            }

            try
            {
                // call the original method, catching and rethrowing any unhandled exceptions
                _beforeAction?.Invoke(diagnosticSource, actionDescriptor, httpContext, routeData);
            }
            catch (Exception ex)
            {
                integration?.SetException(ex);
                throw;
            }
        }
Beispiel #30
0
        public static object GetIlComparer()
        {
            var t       = typeof(object);
            var compGen = typeof(ILEqualityComparer <>).MakeGenericType(t);
            var def     = compGen.GetProperty("Default") !.GetMethod !;
            var eq      = compGen.GetMethod(nameof(Equals), new[] { t, t }) !;

            var func = new DynamicMethodBuilder <Func <object> >("GetDiv")
                       .IL(il => il
                           .Call(def).CastClass(typeof(object)).Return())
                       .Build();

            var a = func();

            return(a);
        }
        /// <summary>
        /// Get the configuration for the multiplexer.
        /// </summary>
        /// <param name="multiplexer">The multiplexer</param>
        /// <returns>The configuration</returns>
        public static string GetConfiguration(object multiplexer)
        {
            try
            {
                if (_getConfigurationMethod == null)
                {
                    _getConfigurationMethod = DynamicMethodBuilder <Func <object, string> > .CreateMethodCallDelegate(multiplexer.GetType(), "get_Configuration");
                }

                return(_getConfigurationMethod(multiplexer));
            }
            catch
            {
                return(null);
            }
        }