示例#1
0
        public void SpeedTestInterface()
        {
            dynamic New     = new ClayFactory();
            IRobot  tRobot  = New.Robot().Name("Bender");
            IRobot  tRobotI = Impromptu.ActLike <IRobot>(New.Robot().Name("Bender"));

            var tInteration = 50000;
            var tWatchC     = TimeIt.Go(() =>
            {
                var tOut =
                    Impromptu.ActLike <IRobot>(New.Robot().Name("Bender"));
            }, tInteration);
            var tWatchC2 = TimeIt.Go(() =>
            {
                IRobot tOut = New.Robot().Name("Bender");
            }, tInteration);

            TestContext.WriteLine("*CreateInterface*");
            TestContext.WriteLine("Impromptu: " + tWatchC.Elapsed);
            TestContext.WriteLine("Clay: " + tWatchC2.Elapsed);
            TestContext.WriteLine("Impromptu VS Clay: {0:0.0} x faster", (double)tWatchC2.ElapsedTicks / tWatchC.ElapsedTicks);
            Assert.Less(tWatchC.Elapsed, tWatchC2.Elapsed);

            var tWatch = TimeIt.Go(() => { var tOut = tRobotI.Name; }, tInteration);

            var tWatch2 = TimeIt.Go(() => { var tOut = tRobot.Name; }, tInteration);

            TestContext.WriteLine("*Get from Interface*");
            TestContext.WriteLine("Impromptu: " + tWatch.Elapsed);
            TestContext.WriteLine("Clay: " + tWatch2.Elapsed);

            TestContext.WriteLine("Impromptu VS Clay: {0:0.0} x faster", (double)tWatch2.ElapsedTicks / tWatch.ElapsedTicks);

            Assert.Less(tWatch.Elapsed, tWatch2.Elapsed);
        }
示例#2
0
        static void Main(string[] args)
        {
            IAlgorithm algorithmInstance;

            try
            {
                PythonEngine.Initialize();

                using (Py.GIL())
                {
                    dynamic scope = Py.Import("BasicTemplateAlgorithm");

                    dynamic item = scope.BasicTemplateAlgorithm();

                    algorithmInstance = Impromptu.ActLike <IAlgorithm>(item);
                }

                algorithmInstance.Initialize();
                algorithmInstance.SetCash(1000000);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.Write("Done.");
            Console.ReadKey();
        }
示例#3
0
        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            var valid = binder.Type == typeof(TInterface);

            result = Impromptu.ActLike <TInterface>(this);
            return(valid);
        }
示例#4
0
        private static TInterface CreateInterfaceInstance <TInterface>(
            IDictionary <string, object> propertiesValues = null)
            where TInterface : class
        {
            dynamic expandoObject = new ExpandoObject();
            Type    expandoType   = typeof(TInterface);

            var expandoProperties = expandoObject as IDictionary <string, object>;

            foreach (var member in expandoType.GetMembers())
            {
                // Get value from dictionary if it exists
                if (propertiesValues != null && propertiesValues.ContainsKey(member.Name))
                {
                    var parameterValue = propertiesValues[member.Name];
                    var convertedValue = CastValueToPropertyType(member, parameterValue);
                    expandoProperties[member.Name] = convertedValue;
                }

                // If not, get the default value
                else
                {
                    var propertyType = member.GetUnderlyingType();

                    if (propertyType != typeof(void))
                    {
                        object defaultValue = propertyType.IsValueType ? Activator.CreateInstance(propertyType) : null;
                        expandoProperties[member.Name] = defaultValue;
                    }
                }
            }

            return(Impromptu.ActLike(expandoObject));
        }
示例#5
0
        static dynamic GetDynamicAwaitableObject(bool completeSynchronously)
        {
            // ExpandoObject类型可在运行时动态添加和删除其成员的对象
            dynamic result  = new ExpandoObject(); // 类型t
            dynamic awaiter = new ExpandoObject(); // 类型A

            awaiter.Message     = "Completed synchronously";
            awaiter.IsCompleted = completeSynchronously;
            awaiter.GetResult   = (Func <string>)(() => awaiter.Message);

            awaiter.OnCompleted = (Action <Action>)(callback => ThreadPool.QueueUserWorkItem(state =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(3));
                awaiter.Message = GetInfo();
                callback?.Invoke();
            }));

            // 使用Impromptu.ActLike方法动态的创建代理对象,该对象将实现任何需要的接口
            IAwaiter <string> proxy = Impromptu.ActLike(awaiter);

            // t有一个名为GetAwaiter的可访问的实例或扩展方法
            result.GetAwaiter = (Func <dynamic>)(() => proxy);

            return(result);
        }
示例#6
0
        private static TInterface CreateInterfaceInstance <TInterface>(Dictionary <string, object> propertiesValues = null) where TInterface : class
        {
            dynamic expandoObject = new ExpandoObject();

            var expandoType       = typeof(TInterface);
            var expandoProperties = expandoObject as IDictionary <String, object>;

            foreach (var property in GetPublicProperties(expandoType))
            {
                // Get value from dictionary if it exists
                if (propertiesValues != null && propertiesValues.ContainsKey(property.Name))
                {
                    var parameterValue = propertiesValues[property.Name];
                    var convertedValue = CastValueToPropertyType(property, parameterValue);
                    expandoProperties[property.Name] = convertedValue;
                }
                // If not, get the default value
                else
                {
                    var    propertyType = property.PropertyType;
                    object defaultValue = propertyType.IsValueType ? Activator.CreateInstance(propertyType) : null;
                    expandoProperties[property.Name] = defaultValue;
                }
            }

            return(Impromptu.ActLike <TInterface>(expandoObject));
        }
        static dynamic GetDynamicAwaitableObject(bool completeSynchronously)
        {
            dynamic result  = new ExpandoObject();
            dynamic awaiter = new ExpandoObject();

            awaiter.Message     = "Completed synchronously";
            awaiter.IsCompleted = completeSynchronously;
            awaiter.GetResult   = (Func <string>)(() => awaiter.Message);

            awaiter.OnCompleted = (Action <Action>)(callback =>
                                                    ThreadPool.QueueUserWorkItem(state => {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                awaiter.Message = GetInfo();
                if (callback != null)
                {
                    callback();
                }
            })
                                                    );

            IAwaiter <string> proxy = Impromptu.ActLike(awaiter);

            result.GetAwaiter = (Func <dynamic>)(() => proxy);

            return(result);
        }
示例#8
0
        public void MoreGenericsLinq()
        {
            var         expected = Enumerable.Range(1, 10).Select(i => Tuple.Create(1, i)).Aggregate(0, (accum, each) => each.Item2);
            ILinq <int> linq     = Impromptu.ActLike(Dynamic.Linq(Enumerable.Range(1, 10)));
            var         actual   = linq.Select(i => Tuple.Create(1, i)).Aggregate(0, (accum, each) => each.Item2);

            Assert.AreEqual(expected, actual);
        }
        public void DynamiteyDictionaryNullMethodsTest()
        {
            dynamic tNew = new Dictionary();

            ISimpleStringMethod tActsLike = Impromptu.ActLike <ISimpleStringMethod>(tNew);

            Assert.AreEqual(false, tActsLike.StartsWith("Te"));
        }
示例#10
0
        public void SimpleLinq()
        {
            var         expected = Enumerable.Range(1, 10).Where(i => i > 5).Skip(1).Take(2).Max();
            ILinq <int> linq     = Impromptu.ActLike(Dynamic.Linq(Enumerable.Range(1, 10)));
            var         actual   = linq.Where(i => i > 5).Skip(1).Take(2).Max();

            Assert.AreEqual(expected, actual);
        }
示例#11
0
        private void GenericHelperConstraints <T>(T param, string expected) where T : class
        {
            dynamic tNew = new ExpandoObject();

            tNew.Funct = new Func <T, string>(it => it.ToString());
            var tActsLike = Impromptu.ActLike <IGenericTypeConstraints <T> >(tNew);

            Assert.AreEqual(expected, tActsLike.Funct(param));
        }
示例#12
0
        private void GenericMethHelper2 <T>(T param)
        {
            dynamic tNew = new ExpandoObject();

            tNew.Action2 = new Func <T, T>(it => it);
            IGenericMeth tActsLike = Impromptu.ActLike <IGenericMeth>(tNew);

            Assert.AreEqual(param, tActsLike.Action2(param));
        }
示例#13
0
        public void GenericMethodTest()
        {
            dynamic      ot   = new OtherThing();
            IGenericTest test = Impromptu.ActLike(ot);

            var tResult = test.GetThings <Thing>(Guid.Empty);

            Assert.AreEqual(true, tResult is List <Thing>);
        }
示例#14
0
        public static T1 Wrap <T1>(T obj) where T1 : class
        {
            if (!typeof(T1).IsInterface)
            {
                throw new ArgumentException("T1 must be an Interface");
            }

            return(Impromptu.ActLike <T1>(new NHibernateTransactionProxy <T>(obj)));
        }
示例#15
0
        private void GenericMethHelper <T>(T param, string expected)
        {
            dynamic tNew = new ExpandoObject();

            tNew.Action = new Func <T, string>(it => it.ToString());
            IGenericMeth tActsLike = Impromptu.ActLike <IGenericMeth>(tNew);

            Assert.AreEqual(expected, tActsLike.Action(param));
        }
示例#16
0
        private void GenericMethConstraintsHelper2 <T>(T param, string expected) where T : IComparable

        {
            dynamic tNew = new ExpandoObject();

            tNew.Action2 = new Func <T, string>(it => it.ToString());
            var tActsLike = Impromptu.ActLike <IGenericMethWithConstraints>(tNew);

            Assert.AreEqual(expected, tActsLike.Action2(param));
        }
示例#17
0
        public T Face <T>(bool makeSafe = false) where T : class, IAgent
        {
            var face = Impromptu.ActLike <T>(this);

            if (makeSafe)
            {
                Init(typeof(T), makeSafe);
            }
            return(face);
        }
示例#18
0
        public void ActLikeTest()
        {
            var expando = CreateExpando();

            IMyCoso micoso = Impromptu.ActLike <IMyCoso>(expando);

            Assert.AreEqual("Hola", micoso.El);
            Assert.AreEqual("Mostru", micoso.Cosito);
            Assert.AreEqual("HolaMostru", micoso.Toma());
        }
示例#19
0
        public void ArrayIndexTest()
        {
            var tNew = new[] { "Test1", "Test2" };

            var tActsLike = Impromptu.ActLike <IStringIntIndexer>(tNew);



            Assert.AreEqual(tNew[1], tActsLike[1]);
        }
示例#20
0
        public void DynamicArgMethodTest2()
        {
            dynamic tPoco     = new PocoNonDynamicArg();
            dynamic tActsLike = Impromptu.ActLike <IDynamicArg>(tPoco);



            Assert.AreEqual(DynamicArgsHelper(tPoco, new[] { 1, 2, 3 }), tActsLike.Params(1, 2, 3));
            Assert.AreEqual(tPoco.Params("test"), tActsLike.Params("test"));
        }
        public void DictionaryNullPropertyTest()
        {
            dynamic tNew = new Dictionary();


            ISimpeleClassProps tActsLike = Impromptu.ActLike <ISimpeleClassProps>(tNew);

            Assert.AreEqual(default(string), tActsLike.Prop1);
            Assert.AreEqual(default(long), tActsLike.Prop2);
            Assert.AreEqual(default(Guid), tActsLike.Prop3);
        }
示例#22
0
        public void EventPropertyCollisionTest()
        {
            dynamic tNew = new ExpandoObject();

            tNew.Event = 3;

            IEventCollisions tActsLike = Impromptu.ActLike <IEventCollisions>(tNew, typeof(IEvent));


            Assert.AreEqual(tNew.Event, tActsLike.Event);
        }
示例#23
0
        public void InterfaceDirectDuplicateTest()
        {
            dynamic tNew = new ExpandoObject();

            tNew.StartsWith = new Func <string, bool>(x => true);

            ISimpleStringMethod tActsLike = Impromptu.ActLike <ISimpleStringMethod>(tNew, typeof(ISimpleStringMethod));


            Assert.AreEqual(tNew.StartsWith("test"), tActsLike.StartsWith("test"));
        }
 /// <summary>
 /// Add support for an interface to this document if it doesn't already have it
 /// </summary>
 public T AddLike <T>()
     where T : class
 {
     @int.Add(typeof(T).FullName);
     // And also act like any interfaces that interface implements (which will include ones they represent too)
     foreach (var @interface in typeof(T).GetInterfaces())
     {
         @int.Add(@interface.FullName);
     }
     return(Impromptu.ActLike <T>(this, this.GetAllInterfaces()));
 }
            object IInstance.CreateInstance()
            {
                var overrideCountable = Builder.New().Object(GetCount: new Func <int>(OverrideCount));
                var targetSelector    = new DictionaryTargetSelectorBuilder
                {
                    { typeof(ILongCountable), a, false },
                    { typeof(ICountable), Impromptu.ActLike <ICountable>(overrideCountable) },
                    { typeof(IContainsCountable), this }
                }.Create();

                return((IContainsCountable)Mixins.GenerateProxy(targetSelector));
            }
示例#26
0
        public void PythonLinq()
        {
            var         expected = Enumerable.Range(1, 10).Where(x => x < 5).OrderBy(x => 10 - x).First();
            ILinq <int> linq     = Impromptu.ActLike(Dynamic.Linq(Enumerable.Range(1, 10)));
            var         actual   = RunPythonHelper(linq, @"
import System
result = linq.Where.Overloads[System.Func[int, bool]](lambda x: x < 5).OrderBy(lambda x: 10-x).First()

");

            Assert.AreEqual(expected, actual);
        }
        /// <summary>
        /// Add support for multiple interfaces
        /// </summary>
        public T AddLike <T>(Type[] otherInterfaces)
            where T : class
        {
            var allInterfaces = otherInterfaces.Concat(new[] { typeof(T) });
            var allInterfacesAndDescendants = allInterfaces.Concat(allInterfaces.SelectMany(x => x.GetInterfaces()));

            foreach (var @interface in allInterfacesAndDescendants)
            {
                @int.Add(@interface.FullName);
            }
            return(Impromptu.ActLike <T>(this, this.GetAllInterfaces()));
        }
 /// <summary>
 /// Cast this object to an interface only if it has previously been created as one of that kind
 /// </summary>
 public T AsLike <T>()
     where T : class
 {
     if ([email protected](typeof(T).FullName))
     {
         return(null);
     }
     else
     {
         return(Impromptu.ActLike <T>(this, this.GetAllInterfaces()));
     }
 }
示例#29
0
        public Interface Bind <Interface>()
            where Interface : class
        {
            var t = typeof(Interface);

            if (!_iTypes.ContainsKey(t.Name))
            {
                _iTypes.Add(t.Name, t);
            }

            return(Impromptu.ActLike <Interface>(new InterfaceProxy <Interface>(this)));
        }
示例#30
0
        static void Main(string[] args)
        {
            var swan       = new Swan();
            var swanAsDuck = Impromptu.ActLike <IDuck>(swan);

            if (swanAsDuck != null)
            {
                swanAsDuck.Walk();
                swanAsDuck.Swim();
                swanAsDuck.Quack();
            }
            Console.ReadKey();
        }