Exemple #1
0
        public static IList <KnownAttributes <TInfo> > LookupAttributes <TInfo>(
            object target,
            Dictionary <Type, IList <KnownAttributes <TInfo> > > known,
            InvocationHelper helper) where TInfo : MemberInfo
        {
            Contract.Requires(target != null);
            Contract.Requires(known != null);
            Contract.Requires(helper != null);

            IList <KnownAttributes <TInfo> > result;
            var type = target.GetType();

            lock (known)
            {
                if (!known.TryGetValue(type, out result))
                {
                    var infos = helper();
                    Contract.Assume(infos != null); // ensures infos is not null
                    result = new List <KnownAttributes <TInfo> >();
                    foreach (TInfo info in infos)   // possibly unboxing a null reference
                    {
                        if (info != null)
                        {
                            var temp = new KnownAttributes <TInfo>(info); // Flagged as related
                        }
                    }
                    known[type] = result;
                }
            }
            return(result);
        }
Exemple #2
0
        public FieldWrapper(Type ownerType, FieldInfo info, NanoLocation location, NanoState state, int constructorArg, string name) :
            base(ownerType, info, info.FieldType, location, state, constructorArg, name)
        {
            Info = info;

            readFunc  = InvocationHelper.CreateGetFieldDelegate(ownerType, info);
            writeFunc = InvocationHelper.CreateSetFieldDelegate(ownerType, info);
        }
        private Func <object[], object> UpdateConstructors(int maxArgIndex, out int argsCount, out string[] globalArgNames)
        {
            MemberWrapper[] args = null;
            if (maxArgIndex > -1)
            {
                args = new MemberWrapper[maxArgIndex + 1];
                foreach (PropertyWrapper wrapper in Properties)
                {
                    if (wrapper.ConstructorArg != -1)
                    {
                        args[wrapper.ConstructorArg] = wrapper;
                    }
                }
                foreach (FieldWrapper wrapper in Fields)
                {
                    if (wrapper.ConstructorArg != -1)
                    {
                        args[wrapper.ConstructorArg] = wrapper;
                    }
                }
            }

            globalArgNames = null;
            ConstructorInfo bestCtor      = null;
            float           bestCtorScore = -1;

            ParameterInfo[] bestCtorParameterInfos = null;

            foreach (ConstructorInfo info in Type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                ParameterInfo[] parameterInfos = null;
                string[]        names          = null;

                float score = TestConstructor(info, args, ref names, ref parameterInfos);
                if (score > bestCtorScore)
                {
                    bestCtorScore          = score;
                    bestCtor               = info;
                    bestCtorParameterInfos = parameterInfos;
                    globalArgNames         = names;
                }
            }

            if (bestCtor == null)
            {
                if (Type.IsValueType)
                {
                    argsCount = 0;
                    return(InvocationHelper.CreateConstructorDelegate(Type, null, null));
                }
                throw new SerializationException($"Unable to get best constructor for {Type.FullName}");
            }

            argsCount = bestCtorParameterInfos.Length;
            return(InvocationHelper.CreateConstructorDelegate(Type, bestCtor, bestCtorParameterInfos));
        }
Exemple #4
0
        public static T GetCustomAttributes <T>(Type type, MethodInfo methodInfo) where T : Attribute
        {
            var method = InvocationHelper.GetMethodOnType(type, methodInfo);

            if (method != null)
            {
                return(method.GetAttribute <T>());
            }

            return(null);
        }
Exemple #5
0
        public static object CreateParameterless(Type type)
        {
            Func <object> func;

            if (!typeConstructors.TryGetValue(type, out func))
            {
                func = InvocationHelper.CreateConstructorDelegate(type);
                typeConstructors.Add(type, func);
            }

            return(func());
        }
        public PropertyWrapper(Type ownerType, PropertyInfo info, NanoLocation location, NanoState state, int constructorArg, string name)
            : base(ownerType, info, info.PropertyType, location, state, constructorArg, name)
        {
            Info = info;

            if (info.CanWrite)
            {
                writeAction = InvocationHelper.CreateSetDelegate(ownerType, info.PropertyType, info.SetMethod);
            }
            readFunc = InvocationHelper.CreateGetDelegate(ownerType, info.PropertyType, info.GetMethod);

            CanWrite = info.CanWrite;
            CanRead  = info.CanRead;

            IsPrivate = (!info.CanRead || info.GetMethod.IsPrivate) &&
                        (!info.CanWrite || info.SetMethod.IsPrivate);
        }
Exemple #7
0
        public void Intercept(IInvocation invocation)
        {
            if (this.IsTransactional(invocation))
            {
                this.loggingHelper.LogTransactionMethodBegin(invocation);

                bool iAmTheFirst = default(bool);
                try
                {
                    iAmTheFirst = this.BeginTransactionIfNeeded();
                    invocation.Proceed();
                    this.TryCommit(iAmTheFirst, invocation);
                }
                catch (Exception ex)
                {
                    this.logger.Error(ex, "Exception in method: {0}", invocation.Method.GetFullMethodName());
                    this.RollbackTransaction(iAmTheFirst, invocation);

                    if (InvocationHelper.IsKnownCrudOperation(invocation))
                    {
                        invocation.ReturnValue = InvocationHelper.BuildReturnValueForError(invocation, ex);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    this.session.Close();
                }
            }
            else
            {
                this.loggingHelper.LogTransactionMethodIgnored(invocation);
                invocation.Proceed();
            }
        }
Exemple #8
0
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     // This first if statement is a temporary hack to work around the fact that GroupMe doesn't correctly route add/join messages through OnMembersAddedAsync.
     // Once https://github.com/microsoft/BotFramework-Services/issues/97 is resolved, welcome messages need only be handled by OnMembersAddedAsync
     foreach (var member in turnContext.Activity.NewMembers())
     {
         await WelcomeHelper.SendWelcomeMessage(member, turnContext, cancellationToken);
     }
     foreach (var member in turnContext.Activity.ReturningMembers())
     {
         await WelcomeHelper.SendWelcomeBackMessage(member, turnContext, cancellationToken);
     }
     if (turnContext.Activity.Text.StartsWith("!", StringComparison.Ordinal))
     {
         await InvocationHelper.HandleInvocationActivity(turnContext, cancellationToken);
     }
     if (turnContext.Activity.Polls().Any())
     {
         await turnContext.SendActivitiesAsync(new[] {
             MessageFactory.Text(Constants.VoteAndLikeReminder),
             MessageFactory.Text(Constants.MaskReminder)
         }, cancellationToken);
     }
 }
Exemple #9
0
 protected override void OnExit(IInvocation invocation)
 {
     InvocationHelper.SetReturnValue(invocation, RETURN_VALUE_SET_BY_ASPECT);
 }
        public static void TestPerformance()
        {
            Test         test = new Test();
            PropertyInfo info = typeof(Test).GetProperty("A");

            const string TEST = "1";

            info.SetValue(test, TEST);
            Action <object, object> action = InvocationHelper.CreateSetDelegate(typeof(Test), typeof(string), info.SetMethod);
            MethodInfo method = info.SetMethod;

            action(test, TEST);

            Action <object, object> actionUntyped       = SetUntyped;
            Action <Test, string>   actionTyped         = SetUntyped;
            Action <Test, string>   actionLambdaTyped   = (target, arg) => target.A = arg;
            Action <object, object> actionLambdaUntyped = (target, arg) => ((Test)target).A = (string)arg;

            Action <Test, string> actionDelegate     = (Action <Test, string>)Delegate.CreateDelegate(typeof(Action <Test, string>), method);
            Func <object>         actionCreateLambda = CreateConstructorDelegate(typeof(Test));
            Func <object>         actionCreateEmit   = InvocationHelper.CreateConstructorDelegate(typeof(Test));
            ConstructorInfo       ctor = typeof(Test).GetConstructor(Type.EmptyTypes);

            ConstructorInfo         ctorString             = typeof(Test).GetConstructor(new Type[] { typeof(string) });
            Func <object[], object> actionCreateEmitString = InvocationHelper.CreateConstructorDelegate(typeof(Test), ctorString, ctorString.GetParameters());

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Performance test: Property set...");
            Console.ForegroundColor = ConsoleColor.Gray;

            WriteTestStart("PropertyInfo.SetValue");
            Stopwatch stopwatch = Stopwatch.StartNew();

            for (int i = 0; i < ITERATIONS; i++)
            {
                info.SetValue(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("MethodInfo.Invoke");
            stopwatch.Restart();
            object[] cache = { TEST };
            for (int i = 0; i < ITERATIONS; i++)
            {
                method.Invoke(test, cache);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("InvocationHelper.CreateSetDelegate");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                action(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("test.A = TEST");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                test.A = TEST;
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("SetTyped(Test test, string s)");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                SetTyped(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("SetUntyped(object test, object s)");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                SetUntyped(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("Action<Test, string>");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionTyped(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("Action<object, object>");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionUntyped(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("=> target.A = arg");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionLambdaTyped(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("=> ((Test)target).A = (string)arg");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionLambdaUntyped(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("Delegate.CreateDelegate");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionDelegate(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("Delegate.DynamicInvoke");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                action.DynamicInvoke(test, TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine();
            Console.WriteLine("Performance test: Object creation...");
            Console.ForegroundColor = ConsoleColor.Gray;

            WriteTestStart("Activator.Create");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                Activator.CreateInstance(typeof(Test));
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("CreateConstructorDelegate");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionCreateEmit();
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("() => new TResult()");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionCreateLambda();
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("ConstructorInfo.Invoke");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                ctor.Invoke(null);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("new Test()");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                // ReSharper disable once ObjectCreationAsStatement
                new Test();
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("Activator.Create (string)");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                Activator.CreateInstance(typeof(Test), cache);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("CreateConstructorDelegate(string)");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                actionCreateEmitString(cache);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("ConstructorInfo.Invoke(string)");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                ctorString.Invoke(cache);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            WriteTestStart("new Test(string)");
            stopwatch.Restart();
            for (int i = 0; i < ITERATIONS; i++)
            {
                // ReSharper disable once ObjectCreationAsStatement
                new Test(TEST);
            }
            stopwatch.Stop();
            WriteTestFinish(stopwatch);

            Console.WriteLine("-- All done. Press <Enter> to continue.");
            Console.WriteLine();
        }