コード例 #1
0
        private static CREATE_FUNC GetCreateFunc()
        {
            var tType  = typeof(T);
            var method = tType.GetMethods()
                         .Where((methodInfo) => methodInfo.Name.Equals("CreateFromBinary"))
                         .Where((methodInfo) => methodInfo.IsStatic &&
                                methodInfo.IsPublic)
                         .Where((methodInfo) => methodInfo.GetParameters().Length == 2)
                         .Where((methodInfo) => methodInfo.GetParameters()[0].ParameterType.Equals(typeof(MutagenFrame)))
                         .Where((methodInfo) => methodInfo.GetParameters()[1].ParameterType.Equals(typeof(RecordTypeConverter)))
                         .FirstOrDefault();

            if (method == null)
            {
                throw new ArgumentException();
            }
            if (method.ReturnType == tType)
            {
                var wrap = LoquiBinaryTranslation <T> .CREATE;
                return(async(MutagenFrame frame, RecordTypeConverter? recConv) =>
                {
                    return wrap(frame, recConv);
                });
            }
            else
            {
                return(DelegateBuilder.BuildDelegate <CREATE_FUNC>(method));
            }
        }
コード例 #2
0
        public void Build_Builds_Object_From_Delegate_Supplied()
        {
            const int expected = 11;
            var builder = new DelegateBuilder<int>(() => expected);

            Assert.AreEqual(builder.Build(), expected);
        }
コード例 #3
0
ファイル: DataGenerator.cs プロジェクト: banncan/Theraot
        private static (Type ReturnType, Type GeneratorType, Delegate Delegate) GetGenerators(MethodInfo methodInfo)
        {
            Delegate @delegate;

            if (methodInfo.IsStatic)
            {
                @delegate = DelegateBuilder.BuildDelegate(methodInfo, null);
            }
            else
            {
                var declaringType = methodInfo.DeclaringType;
                if (declaringType == null)
                {
                    throw new InvalidOperationException();
                }

                if (!_instances.TryGetValue(declaringType, out var instance))
                {
                    try
                    {
                        instance = Activator.CreateInstance(declaringType);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }

                    _instances[declaringType] = instance;
                }

                @delegate = instance == null ? null : DelegateBuilder.BuildDelegate(methodInfo, instance);
            }

            return(methodInfo.GetReturnType(), methodInfo.DeclaringType, @delegate);
        }
コード例 #4
0
        public void BuidUnkownCtorWithParams_CanBuildAnonymousConstructor_BuildsConstructorThatCanParseStringsToValueTypes()
        {
            var now  = DateTime.Now;
            var anon = new
            {
                Property1 = default(long?),
                Property2 = default(long),
                Property3 = default(DateTime?),
                Property4 = default(DateTime),
                Property5 = default(string),
                Property6 = default(SomeEnum),
                Property7 = default(SomeEnum?)
            };

            var ctor = DelegateBuilder.BuildUnknownCtorWithParams(anon.GetType().GetConstructors().First());

            var instance = ctor((long?)1, (long)2, now, now, "str", SomeEnum.Value1, SomeEnum.Value2);

            instance.PropertyValue <long?>("Property1").Should().Be.EqualTo(1);
            instance.PropertyValue <long>("Property2").Should().Be.EqualTo(2);
            instance.PropertyValue <DateTime?>("Property3").Should().Be.EqualTo(now);
            instance.PropertyValue <DateTime>("Property4").Should().Be.EqualTo(now);
            instance.PropertyValue <string>("Property5").Should().Be.EqualTo("str");
            instance.PropertyValue <SomeEnum>("Property6").Should().Be.EqualTo(SomeEnum.Value1);
            instance.PropertyValue <SomeEnum?>("Property7").Should().Be.EqualTo(SomeEnum.Value2);
        }
コード例 #5
0
ファイル: ClientSession.cs プロジェクト: lwp001/NosCore
        public ClientSession(ServerConfiguration configuration, IEnumerable <IPacketController> packetControllers,
                             IMapInstanceProvider mapInstanceProvider, IExchangeProvider exchangeProvider, ILogger logger) : base(logger)
        {
            _logger = logger;

            if (configuration is WorldConfiguration worldConfiguration)
            {
                WorldConfiguration   = worldConfiguration;
                _mapInstanceProvider = mapInstanceProvider;
                _exchangeProvider    = exchangeProvider;
                _isWorldClient       = true;
            }

            foreach (var controller in packetControllers)
            {
                controller.RegisterSession(this);
                foreach (var methodInfo in controller.GetType().GetMethods().Where(x =>
                                                                                   typeof(PacketDefinition).IsAssignableFrom(x.GetParameters().FirstOrDefault()?.ParameterType)))
                {
                    var type         = methodInfo.GetParameters().FirstOrDefault()?.ParameterType;
                    var packetheader = (PacketHeaderAttribute)Array.Find(type?.GetCustomAttributes(true),
                                                                         ca => ca.GetType() == typeof(PacketHeaderAttribute));
                    _headerMethod.Add(packetheader, new Tuple <IPacketController, Type>(controller, type));
                    _controllerMethods.Add(packetheader,
                                           DelegateBuilder.BuildDelegate <Action <object, object> >(methodInfo));
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// 创建一个委托
        /// </summary>
        /// <returns></returns>
        public virtual DelegateBuilder CreateDelegate()
        {
            var member = new DelegateBuilder();

            _namespace.Delegates.Add(member);
            return(member);
        }
コード例 #7
0
    public static void Main()
    {
        Type type   = typeof(MyType);
        var  mi     = type.GetMethod("SetValue");
        var  obj1   = new MyType(1);
        var  obj2   = new MyType(2);
        var  action = DelegateBuilder.BuildDelegate <Action <object, int> >(mi);

        action(obj1, 3);
        action(obj2, 4);
        Console.WriteLine(obj1.Value);
        Console.WriteLine(obj2.Value);
        // Sample passing a default value for the 2nd param of SetSumValue.
        var mi2     = type.GetMethod("SetSumValue");
        var action2 = DelegateBuilder.BuildDelegate <Action <object, int> >(mi2, 10);

        action2(obj1, 3);
        action2(obj2, 4);
        Console.WriteLine(obj1.Value);
        Console.WriteLine(obj2.Value);
        // Sample without passing a default value for the 2nd param of SetSumValue.
        // It will just use the default int value that is 0.
        var action3 = DelegateBuilder.BuildDelegate <Action <object, int> >(mi2);

        action3(obj1, 3);
        action3(obj2, 4);
        Console.WriteLine(obj1.Value);
        Console.WriteLine(obj2.Value);
    }
コード例 #8
0
        public void BuildSetter_StandardType_BuildsSetters()
        {
            var flags           = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
            var now             = DateTime.Now;
            var propertySetter1 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property1", flags));

            propertySetter1(this, (long?)1);
            var propertySetter2 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property2", flags));

            propertySetter2(this, (long)2);
            var propertySetter3 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property3", flags));

            propertySetter3(this, now);
            var propertySetter4 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property4", flags));

            propertySetter4(this, now);
            var propertySetter5 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property5", flags));

            propertySetter5(this, "str");
            var propertySetter6 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property6", flags));

            propertySetter6(this, SomeEnum.Value1);
            var propertySetter7 = DelegateBuilder.BuildSetter <DelegateBuilderTest>(GetType().GetProperty("Property7", flags));

            propertySetter7(this, SomeEnum.Value2);

            Property1.Should().Be.EqualTo(1);
            Property2.Should().Be.EqualTo(2);
            Property3.Should().Be.EqualTo(now);
            Property4.Should().Be.EqualTo(now);
            Property5.Should().Be.EqualTo("str");
            Property6.Should().Be.EqualTo(SomeEnum.Value1);
            Property7.Should().Be.EqualTo(SomeEnum.Value2);
        }
コード例 #9
0
        /// <summary>
        /// 统计一个委托
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public virtual TBuilder WithDelegate(Action <DelegateBuilder> builder)
        {
            DelegateBuilder member = new DelegateBuilder();

            builder.Invoke(member);
            _class.Delegates.Add(member);
            return(_TBuilder);
        }
コード例 #10
0
        /// <summary>
        /// Builds this method into a delegate that invokes the method using the argument to the first
        /// parameter of the action as the target object and returns void.
        /// </summary>
        /// <remarks><b>Must be non-static method.</b> For static methods, see <see cref="BuildDelegateStatic{TDelegate}(MethodInfo, Type[])"/>.</remarks>
        /// <typeparam name="TDelegate">The type of <see cref="Delegate"/> to build the method into.</typeparam>
        /// <param name="method">The method to build into an action.</param>
        /// <exception cref="IncompatibleInstanceException">The method is static and no instance is given.
        ///     -or-The method is non-static and an instance is given.
        ///     -or-The method is not defined for the instance given.</exception>
        /// <exception cref="ArgumentCountMismatchException">The number of arguments given does not match the
        ///     number of parameters on the given method.</exception>
        /// <exception cref="IncompatibleArgumentTypeException">An argument value given can't be cast to be compatible with the
        ///     corresponding parameter in the method signature.</exception>
        /// <exception cref="IncompatibleParameterTypeException">An argument-mapped parameter type given can't be cast to be compatible with the
        ///     corresponding parameter in the method signature.</exception>
        /// <exception cref="IncompatibleReturnTypeException">The return type of the method cannot be converted into the given return type.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="method"/> is null.</exception>
        public static TDelegate CreateDelegate <TDelegate>(this MethodInfo method, Action <DelegateBuilder> builderSetup)
            where TDelegate : Delegate
        {
            var builder = new DelegateBuilder(method);

            builderSetup(builder);

            return(builder.Build <TDelegate>());
        }
コード例 #11
0
        /// <summary>
        /// Create new call sites builder.
        /// </summary>
        /// <param name="moduleBuilder">Module to contain call sites container.</param>
        /// <param name="userFriendlyName">User friendly name used to identify the call sites container by user.</param>
        /// <param name="classContextPlace">If known and if it can be emitted in static .cctor, defines the place where the class context can be loaded. Otherwise <c>null</c> if the class context will be determined in run time.</param>
        /// <param name="classContext">Current PHP type context.</param>
        public CallSitesBuilder(ModuleBuilder /*!*/ moduleBuilder, string /*!*/ userFriendlyName, IPlace classContextPlace, PhpType classContext)
        {
            Debug.Assert(moduleBuilder != null && userFriendlyName != null);

            this.userFriendlyName = userFriendlyName;
            this.moduleBuilder    = moduleBuilder;
            this.PushClassContext(classContextPlace, classContext);
            this.delegateBuilder = new DelegateBuilder(moduleBuilder);
        }
コード例 #12
0
        /// <summary>
        /// 返回将对象从 <see cref="OriginType"/> 类型转换为 <paramref name="outputType"/> 类型的类型转换器。
        /// </summary>
        /// <param name="outputType">要将输入对象转换到的类型。</param>
        /// <returns>将对象从 <see cref="OriginType"/> 类型转换为 <paramref name="outputType"/>
        /// 类型的类型转换器,如果不存在则为 <c>null</c>。</returns>
        /// <remarks>返回的委托必须符合 <see cref="Converter{TInput,TOutput}"/>,
        /// 其输入类型是 <see cref="OriginType"/>,输出类型是 <paramref name="outputType"/>。</remarks>
        public Delegate GetConverterTo(Type outputType)
        {
            if (outputType.IsEnum)
            {
                return(DelegateBuilder.CreateDelegate(Convert.GetConverterType(typeof(string), outputType), convertToEnumMethod));
            }
            switch (Type.GetTypeCode(outputType))
            {
            case TypeCode.Boolean:
                return(new Converter <string, bool>(bool.Parse));

            case TypeCode.Char:
                return(new Converter <string, char>(char.Parse));

            case TypeCode.SByte:
                return(new Converter <string, sbyte>(sbyte.Parse));

            case TypeCode.Byte:
                return(new Converter <string, byte>(byte.Parse));

            case TypeCode.Int16:
                return(new Converter <string, short>(short.Parse));

            case TypeCode.UInt16:
                return(new Converter <string, ushort>(ushort.Parse));

            case TypeCode.Int32:
                return(new Converter <string, int>(int.Parse));

            case TypeCode.UInt32:
                return(new Converter <string, uint>(uint.Parse));

            case TypeCode.Int64:
                return(new Converter <string, long>(long.Parse));

            case TypeCode.UInt64:
                return(new Converter <string, ulong>(ulong.Parse));

            case TypeCode.Single:
                return(new Converter <string, float>(float.Parse));

            case TypeCode.Double:
                return(new Converter <string, double>(double.Parse));

            case TypeCode.Decimal:
                return(new Converter <string, decimal>(decimal.Parse));

            case TypeCode.DateTime:
                return(new Converter <string, DateTime>(DateTime.Parse));

            case TypeCode.DBNull:
                return(null);
            }
            return(null);
        }
コード例 #13
0
        public void DelegateBuilder_PropertyGetter_Speed()
        {
            Speed  inst          = new Speed();
            long   seven         = 7;
            double eight         = 8;
            float  nine          = 9;
            var    prop1Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property1"));
            var    prop2Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property2"));
            var    prop3Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property3"));
            var    prop4Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property4"));
            var    prop5Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property5"));
            var    prop6Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property6"));
            var    prop7Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property7"));
            var    prop8Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property8"));
            var    prop9Getter   = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property9"));
            var    prop10GGetter = DelegateBuilder.BuildGetter <Speed>(typeof(Speed).GetProperty("Property10"));

            inst.Property1  = "1";
            inst.Property2  = 2;
            inst.Property3  = 3m;
            inst.Property4  = new byte[0];
            inst.Property5  = "5";
            inst.Property6  = 6;
            inst.Property7  = seven;
            inst.Property8  = eight;
            inst.Property9  = nine;
            inst.Property10 = Speed.SpeedEnum.None;
            var watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                var a = prop1Getter(inst);
                var b = prop2Getter(inst);
                var c = prop3Getter(inst);
                var d = prop4Getter(inst);
                var e = prop5Getter(inst);
                var f = prop6Getter(inst);
                var g = prop7Getter(inst);
                var h = prop8Getter(inst);
                var j = prop9Getter(inst);
                var k = prop10GGetter(inst);
            }
            watch.Stop();
            inst.Property1.Should().Be.EqualTo("1");
            inst.Property2.Should().Be.EqualTo(2);
            inst.Property3.Should().Be.EqualTo(3m);
            inst.Property4.Should().Not.Be.Null();
            inst.Property5.Should().Be.EqualTo("5");
            inst.Property6.Should().Be.EqualTo(6);
            inst.Property7.Should().Be.EqualTo(7);
            inst.Property8.Should().Be.EqualTo(8);
            inst.Property9.Should().Be.EqualTo(9);
            inst.Property10.Should().Be.EqualTo(Speed.SpeedEnum.None);
            Trace.WriteLine(watch.ElapsedMilliseconds);
        }
コード例 #14
0
        public void Build_BuildAnActionFromTypeAndMethodInfo_ReturnsActionThatDoesNotThrow()
        {
            var             analyzer        = new Analyzer();
            PerformanceSet  set             = analyzer.GetPerformanceSets((typeof(Test).Assembly)).First();
            PerformanceUnit performanceUnit = set.PerformanceUnits.First();

            var builder = new DelegateBuilder();

            Action action = builder.Build(set.Type, performanceUnit.MethodInfo);

            Assert.DoesNotThrow(action.Invoke);
        }
コード例 #15
0
        unsafe static int TrySerializer <T>(StringBuilder sb, params T[] samples)
        {
            int failures = 0;

            sb.AppendLine();
            sb.AppendLine("# " + SchemaTest.HumanName(typeof(T)));
            sb.AppendLine();

            var    emit = DelegateBuilder.CreateStream <T>(Schema.Reflect(typeof(T)));
            string instructions;
            var    del = (Serializer.WriteToStream <T>)emit.CreateDelegate(typeof(Serializer.WriteToStream <T>), out instructions);

            sb.AppendLine(emit.Instructions());
            sb.AppendLine();

            var ms     = new MemoryStream();
            var buffer = new byte[64];

            for (int i = 0; i < samples.Length; i++)
            {
                ms.Position = 0;
                fixed(byte *ptr = buffer)
                {
                    del.Invoke(ref samples[i], ptr, ms, buffer);
                }

                var newt = DelegateBuilderTest.GetNewtonsoft(samples[i]);
                var mine = ms.GetBuffer().Take((int)ms.Position);

                sb.AppendLine();
                sb.AppendLine("## Newtonsoft");
                Util.Hex.Dump(sb, newt);
                sb.AppendLine();

                sb.AppendLine();
                sb.AppendLine("## Cameronism.Json");
                Util.Hex.Dump(sb, mine);
                sb.AppendLine();
                sb.AppendLine();

                bool equal = newt.SequenceEqual(mine);
                sb.AppendLine("Equal: " + equal);
                sb.AppendLine();

                if (!equal)
                {
                    failures++;
                }
            }

            return(failures);
        }
コード例 #16
0
        public void 委托_T1_类中()
        {
            DelegateBuilder builder = CodeSyntax.CreateDelegate("T1")
                                      .WithAccess(NamespaceAccess.Public)
                                      .WithReturnType("void");

            var result = builder.ToFormatCode();

#if Log
            _tempOutput.WriteLine(result);
#endif
            Assert.Equal("public delegate void T1();", result);
        }
コード例 #17
0
        public void 委托_T2_返回值()
        {
            DelegateBuilder builder = CodeSyntax.CreateDelegate("T2")
                                      .WithAccess(MemberAccess.Public)
                                      .WithReturnType("string");

            var result = builder.ToFormatCode();

#if Log
            _tempOutput.WriteLine(result);
#endif
            Assert.Equal("public delegate string T2();", result);
        }
コード例 #18
0
        public void 委托_T5_通过字符串生成()
        {
            DelegateBuilder builder = DelegateBuilder.FromCode(@"[Test(""1"", ""2"", A = ""3"", B = ""4"")]
public delegate void T5();");

            var result = builder.ToFormatCode();

#if Log
            _tempOutput.WriteLine(result);
#endif
            Assert.Equal(@"[Test(""1"", ""2"", A = ""3"", B = ""4"")]
public delegate void T5();", result);
        }
コード例 #19
0
        public void DelegateBuilderNew_Speed()
        {
            Speed inst  = null;
            var   ctor  = DelegateBuilder.BuildCtor <Speed>();
            var   watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                inst = ctor();
            }
            watch.Stop();
            Trace.WriteLine(inst.Property1);
            Trace.WriteLine(watch.ElapsedMilliseconds);
        }
コード例 #20
0
        public void 委托_T4_特性()
        {
            DelegateBuilder builder = CodeSyntax.CreateDelegate("T4")
                                      .WithAttributes(new string[] { @"[Test(""1"", ""2"", A = ""3"", B = ""4"")]" })
                                      .WithAccess(MemberAccess.Public);

            var result = builder.ToFormatCode();

#if Log
            _tempOutput.WriteLine(result);
#endif
            Assert.Equal(@"[Test(""1"", ""2"", A = ""3"", B = ""4"")]
public delegate void T4();", result);
        }
コード例 #21
0
        public void 委托_T3_参数和返回值()
        {
            DelegateBuilder builder = CodeSyntax.CreateDelegate("T3")
                                      .WithAccess(MemberAccess.Public)
                                      .WithReturnType("string")
                                      .WithParams("string a");

            var result = builder.ToFormatCode();

#if Log
            _tempOutput.WriteLine(result.WithUnixEOL());
#endif
            Assert.Equal("public delegate string T3(string a);", result.WithUnixEOL());
        }
コード例 #22
0
        public IPropertyMapping ToPropertyMapping()
        {
            var arguments = new PropertyMappingArguments <T>
            {
                PropertyName        = PropertyInfo.Name,
                PropertyType        = PropertyInfo.PropertyType,
                AttributeName       = AttributeName ?? PropertyInfo.Name.Replace('_', '-'),
                Getter              = DelegateBuilder.BuildGetter <T>(PropertyInfo),
                Setter              = DelegateBuilder.BuildSetter <T>(PropertyInfo),
                IsDistinguishedName = IsDistinguishedName,
                ReadOnly            = IsDistinguishedName ? Mapping.ReadOnly.Always : ReadOnlyConfiguration.GetValueOrDefault(Mapping.ReadOnly.Never)
            };

            return(new CustomPropertyMapping <T, TProperty>(arguments, _convertFrom, _convertTo, _convertToFilter, _isEqual));
        }
コード例 #23
0
        public IPropertyMapping ToPropertyMapping()
        {
            var arguments = new PropertyMappingArguments <T>
            {
                PropertyName        = PropertyInfo.Name,
                PropertyType        = PropertyInfo.PropertyType,
                AttributeName       = AttributeName ?? PropertyInfo.Name.Replace('_', '-'),
                Getter              = DelegateBuilder.BuildGetter <T>(PropertyInfo),
                Setter              = DelegateBuilder.BuildSetter <T>(PropertyInfo),
                IsStoreGenerated    = IsStoreGenerated,
                IsDistinguishedName = IsDistinguishedName,
                IsReadOnly          = IsReadOnly,
            };

            return(new CustomPropertyMapping <T, TProperty>(arguments, _convertFrom, _convertTo, _convertToFilter, _isEqual));
        }
コード例 #24
0
        public void 委托_T5_泛型委托代码生成()
        {
            DelegateBuilder builder = DelegateBuilder.FromCode(@"public delegate T2 Test<T1, T2, T3, T4, T5>(string a, string b)
                    where T2 : struct
                    where T3 : class
                    where T4 : notnull
                    where T5 : IEnumerable<int>, IQueryable<int>;");

            var result = builder.ToFormatCode();

#if Log
            _tempOutput.WriteLine(result);
#endif
            Assert.Equal(@"public delegate T2 Test<T1, T2, T3, T4, T5>(string a, string b)
    where T2 : struct where T3 : class where T4 : notnull where T5 : IEnumerable<int>, IQueryable<int>;", result);
        }
コード例 #25
0
        private static CreateFunc GetCreateFunc()
        {
            var regis = LoquiRegistration.GetRegister(typeof(T));

            if (regis == null)
            {
                throw new ArgumentException();
            }
            var className = $"{regis.Namespace}.Internals.{regis.Name}BinaryOverlay";

            var tType  = regis.ClassType.Assembly.GetType(className) !;
            var method = tType.GetMethods()
                         .Where((methodInfo) => methodInfo.Name.Equals($"{regis.Name}Factory"))
                         .Where((methodInfo) => methodInfo.IsStatic &&
                                methodInfo.IsPublic)
                         .Where((methodInfo) =>
            {
                var param = methodInfo.GetParameters();
                if (param.Length != 3)
                {
                    return(false);
                }
                if (!param[0].ParameterType.Equals(typeof(OverlayStream)))
                {
                    return(false);
                }
                if (!param[1].ParameterType.Equals(typeof(BinaryOverlayFactoryPackage)))
                {
                    return(false);
                }
                if (!param[2].ParameterType.Equals(typeof(RecordTypeConverter)))
                {
                    return(false);
                }
                return(true);
            })
                         .FirstOrDefault();

            if (method != null)
            {
                return(DelegateBuilder.BuildDelegate <CreateFunc>(method));
            }
            else
            {
                throw new ArgumentException();
            }
        }
コード例 #26
0
        public void DelegateBuilderNewParameters_Speed()
        {
            Speed  inst  = null;
            long   seven = 7;
            double eight = 8;
            float  nine  = 9;
            var    ctor  = DelegateBuilder.BuildUnknownCtorWithParams(typeof(Speed).GetConstructors().First(x => x.GetParameters().Length > 0));
            var    watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                inst = (Speed)ctor("1", 2, 3m, new byte[0], "5", 6, seven, eight, nine, Speed.SpeedEnum.None);
            }
            watch.Stop();
            Trace.WriteLine(inst.Property1);
            Trace.WriteLine(watch.ElapsedMilliseconds);
        }
コード例 #27
0
        public void Run_RunsAMarkedMethodOneHundredTimes_ReturnsResultWithOneHundredResults()
        {
            var analyzer = new Analyzer();
            IEnumerable<PerformanceSet> sets = analyzer.GetPerformanceSets((typeof (Test).Assembly));
            PerformanceSet set = sets.First();
            PerformanceUnit unit = set.PerformanceUnits.First();

            MethodInfo methodInfo = unit.MethodInfo;

            var builder = new DelegateBuilder();
            Action action = builder.Build(set.Type, methodInfo);

            var runner = new UnitRunner();

            Result result = runner.Run(set.Name, methodInfo.Name, action, unit.Runs);

            Assert.IsTrue(result.Success);
        }
コード例 #28
0
        public void Run_RunsAMarkedMethodOneHundredTimes_ReturnsResultWithOneHundredResults()
        {
            var analyzer = new Analyzer();
            IEnumerable <PerformanceSet> sets = analyzer.GetPerformanceSets((typeof(Test).Assembly));
            PerformanceSet  set  = sets.First();
            PerformanceUnit unit = set.PerformanceUnits.First();

            MethodInfo methodInfo = unit.MethodInfo;

            var    builder = new DelegateBuilder();
            Action action  = builder.Build(set.Type, methodInfo);

            var runner = new UnitRunner();

            Result result = runner.Run(set.Name, methodInfo.Name, action, unit.Runs);

            Assert.IsTrue(result.Success);
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: clintonmead/Theraot
            public Test(TestMethod testMethod)
            {
                var method = testMethod.Method;
                var type   = method.DeclaringType;

                if (type == null)
                {
                    throw new ArgumentException("Null declaring type", nameof(testMethod));
                }

                _instance            = method.IsStatic ? null : Activator.CreateInstance(type);
                _delegate            = DelegateBuilder.BuildDelegate(method, _instance);
                _parameterInfos      = method.GetParameters();
                _isolatedThread      = testMethod.TestAttribute.IsolatedThread;
                _preferredGenerators = testMethod.PreferredGenerators;
                Name    = method.Name;
                _repeat = testMethod.TestAttribute.Repeat;
            }
コード例 #30
0
 public ClientSession(IChannel channel, bool isWorldClient) : base(channel)
 {
     // set last received
     lastPacketReceive = DateTime.Now.Ticks;
     _random           = new Random((int)ClientId);
     _isWorldClient    = isWorldClient;
     foreach (var controller in PacketControllerFactory.GenerateControllers())
     {
         controller.RegisterSession(this);
         foreach (MethodInfo methodInfo in controller.GetType().GetMethods().Where(x => x.GetParameters().FirstOrDefault()?.ParameterType.BaseType == typeof(PacketDefinition)))
         {
             var type = methodInfo.GetParameters().FirstOrDefault()?.ParameterType;
             PacketHeaderAttribute packetheader = (PacketHeaderAttribute)Array.Find(type.GetCustomAttributes(true), ca => ca.GetType().Equals(typeof(PacketHeaderAttribute)));
             HeaderMethod.Add(packetheader, new Tuple <IPacketController, Type>(controller, type));
             ControllerMethods.Add(packetheader, DelegateBuilder.BuildDelegate <Action <object, object> >(methodInfo));
         }
     }
 }
コード例 #31
0
ファイル: ClientSession.cs プロジェクト: KILL009/NosCore
 public ClientSession(IChannel channel, bool isWorldClient) : base(channel)
 {
     _isWorldClient = isWorldClient;
     foreach (var controller in PacketControllerFactory.GenerateControllers())
     {
         controller.RegisterSession(this);
         foreach (var methodInfo in controller.GetType().GetMethods().Where(x =>
                                                                            x.GetParameters().FirstOrDefault()?.ParameterType.BaseType == typeof(PacketDefinition)))
         {
             var type         = methodInfo.GetParameters().FirstOrDefault()?.ParameterType;
             var packetheader = (PacketHeaderAttribute)Array.Find(type?.GetCustomAttributes(true),
                                                                  ca => ca.GetType() == typeof(PacketHeaderAttribute));
             _headerMethod.Add(packetheader, new Tuple <IPacketController, Type>(controller, type));
             _controllerMethods.Add(packetheader,
                                    DelegateBuilder.BuildDelegate <Action <object, object> >(methodInfo));
         }
     }
 }
コード例 #32
0
ファイル: ClientSession.cs プロジェクト: Saphierus/NosCore
 public ClientSession(GameServerConfiguration configuration, IEnumerable <IPacketController> packetControllers)
 {
     _isWorldClient = configuration is WorldConfiguration;
     foreach (var controller in packetControllers)
     {
         controller.RegisterSession(this);
         foreach (var methodInfo in controller.GetType().GetMethods().Where(x =>
                                                                            x.GetParameters().FirstOrDefault()?.ParameterType.BaseType == typeof(PacketDefinition)))
         {
             var type         = methodInfo.GetParameters().FirstOrDefault()?.ParameterType;
             var packetheader = (PacketHeaderAttribute)Array.Find(type?.GetCustomAttributes(true),
                                                                  ca => ca.GetType() == typeof(PacketHeaderAttribute));
             _headerMethod.Add(packetheader, new Tuple <IPacketController, Type>(controller, type));
             _controllerMethods.Add(packetheader,
                                    DelegateBuilder.BuildDelegate <Action <object, object> >(methodInfo));
         }
     }
 }