示例#1
0
        public static T ToStatic <T>(dynamic source)
        {
            var entity = Activator.CreateInstance <T>();

            var properties = Impromptu.GetMemberNames(source);

            if (properties == null)
            {
                return(entity);
            }

            foreach (var entry in properties)
            {
                var value = Impromptu.InvokeGet(source, entry);
                Impromptu.InvokeSet(entity, entry, value);
            }

            return(entity);
        }
        private static dynamic GetContextFromProperty(Type type)
        {
            try
            {
                const string     propertyName = "get_Context";
                InvokeMemberName invokeArgs   = propertyName;
                if (type.IsGenericTypeDefinition)
                {
                    var typeArgs = Enumerable.Repeat(typeof(object), type.GetGenericArguments().Length);
                    type = type.MakeGenericType(typeArgs.ToArray());
                }

                return(Impromptu.InvokeGet(type.WithStaticContext(), "Context"));
            }
            catch (RuntimeBinderException)
            {
                return(null);
            }
        }
示例#3
0
        public Document CreateDiablo3Hero(Document profile, dynamic heroprofile, User author)
        {
            string   heroId = Convert.ToString(heroprofile.id);
            Document hero   = CreateAndPublishDocument(heroId, Hero.documentTypeAlias, author, profile.Id);

            SetDocumentPropertyOrDefault(hero, Hero.heroClass, Impromptu.InvokeGet(heroprofile, "class"));
            SetDocumentPropertyOrDefault(hero, Hero.heroHardcore, heroprofile.hardcore);
            SetDocumentPropertyOrDefault(hero, Hero.heroId, heroId);
            SetDocumentPropertyOrDefault(hero, Hero.heroLevel, heroprofile.level);
            SetDocumentPropertyOrDefault(hero, Hero.heroName, heroprofile.name);
            SetDocumentPropertyOrDefault(hero, Hero.isCreatedFirstTime, true);
            SetDocumentPropertyOrDefault(hero, Hero.dead, heroprofile.dead);
            SetDocumentPropertyOrDefault(hero, Hero.lastUpdated, Convert.ToString(Impromptu.InvokeGet(heroprofile, "last-updated")));
            SetDocumentPropertyOrDefault(hero, Hero.paragonLevel, heroprofile.paragonLevel);
            SetDocumentPropertyOrDefault(hero, Hero.heroGender, heroprofile.gender);
            SetDocumentPropertyOrDefault(hero, Hero.heroKillsElites, heroprofile.kills.elites);
            UmbracoUtilities.SaveAndPublish(hero);
            return(hero);
        }
示例#4
0
        // Renders the partial view with a copy of the given view data plus the given model
        /// <summary>
        /// 部分视图
        /// </summary>
        /// <param name="partialViewName">部分视图名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="model"> model</param>
        /// <param name="ViewBag">ViewBag</param>
        /// <returns></returns>
        public IEncodedString RenderPartial(string partialViewName, string controllerName, object model, DynamicViewBag ViewBag)
        {
            RefRequestEntity paras = SetParamValue(model);

            var    t          = HuberHttpModule.CurDomainAssembly.GetType(HuberHttpModule.CurDomainAssemblyName + ".Controllers." + controllerName + "Controller");
            var    ActionFunc = t.GetMethod(partialViewName);
            object dObj       = Activator.CreateInstance(t);

            var AddViewBageFunc = t.GetMethod("AddViewBageValues");

            foreach (string key in ViewBag.GetDynamicMemberNames())
            {
                AddViewBageFunc.Invoke(dObj, new object[] { key, Impromptu.InvokeGet(ViewBag, key) });
            }

            object result = ActionFunc.Invoke(dObj, new object[] { paras });

            return(new RawString((result as RefRespondEntity).ResultContext.ToString()));
        }
示例#5
0
        public void TestPropPocoGetValueTimed()
        {
            var tSetValue = "1";
            var tAnon     = new { Test = tSetValue };



            var tWatch = TimeIt.Go(() => { var tOut = Impromptu.InvokeGet(tAnon, "Test"); }, 500000);

            var tPropertyInfo = tAnon.GetType().GetProperty("Test");
            var tWatch2       = TimeIt.Go(() =>
            {
                var tOut = tPropertyInfo.GetValue(tAnon, null);
            }, 500000);

            TestContext.WriteLine("Impromptu: " + tWatch.Elapsed);
            TestContext.WriteLine("Refelection: " + tWatch2.Elapsed);
            TestContext.WriteLine("Impromptu VS Reflection: {0:0.0} x faster", (double)tWatch2.Elapsed.Ticks / tWatch.Elapsed.Ticks);
            Assert.Less(tWatch.Elapsed, tWatch2.Elapsed);
        }
示例#6
0
        private static IList <string> ValidateValuesOfRow(TableRow tableRow, dynamic instance, bool doTypeConversion = true)
        {
            var valueDiffs = new List <string>();

            foreach (var header in tableRow.Keys)
            {
                var propertyName      = CreatePropertyName(header);
                var valueFromInstance = Impromptu.InvokeGet(instance, propertyName);
                var typeFromInstance  = valueFromInstance.GetType().Name;
                var valueFromTable    = CreateTypedValue(tableRow[header], doTypeConversion);
                var typeFromTable     = valueFromTable.GetType().Name;

                if (!valueFromInstance.Equals(valueFromTable))
                {
                    var mess = string.Format(ERRORMESS_VALUE_DIFFERS, propertyName, valueFromInstance, typeFromInstance, valueFromTable, typeFromTable);
                    valueDiffs.Add(mess);
                }
            }
            return(valueDiffs);
        }
        private static List <string> GetSetValueDifferences(Table table, IList <object> set, Options options)
        {
            var memberNames     = Impromptu.GetMemberNames(set[0]);
            var valueDifference = new List <string>();

            for (var i = 0; i < set.Count; i++)
            {
                foreach (var memberName in memberNames)
                {
                    var currentHeader = string.Empty;
                    var rowValue      = GetRowValue(i, table, memberName, out currentHeader, options);

                    if ((rowValue.GetType() == typeof(string)) && ((string)rowValue == "NULL"))
                    {
                        rowValue = null;
                    }

                    var instanceValue = Impromptu.InvokeGet(set[i], memberName);

                    if (((instanceValue != null) || (rowValue != null)) &&
                        !instanceValue.Equals((dynamic)rowValue))
                    {
                        var rowType      = rowValue.GetType().Name;
                        var instanceType = instanceValue.GetType().Name;

                        var difference = string.Format(ERRORMESS_SET_VALUES_DIFFERS,
                                                       i + 1,
                                                       currentHeader,
                                                       memberName,
                                                       instanceValue,
                                                       instanceType,
                                                       rowValue,
                                                       rowType);

                        valueDifference.Add(difference);
                    }
                }
            }
            return(valueDifference);
        }
示例#8
0
        public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
        {
            if (!base.TryInvokeMember(binder, args, out result))
            {
                Type[] types = null;
                try
                {
                    IList <Type> typeList = Impromptu.InvokeGet(binder,
                                                                "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder.TypeArguments");
                    if (typeList != null)
                    {
                        types = typeList.ToArray();
                    }
                }catch (RuntimeBinderException)
                {
                    types = null;
                }

                var name = InvokeMemberName.Create;
                result = InvokeStaticMethod(name(binder.Name, types), args);
            }
            return(true);
        }
示例#9
0
        /// <summary>
        /// Provides the implementation for operations that invoke a member. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as calling a method.
        /// </summary>
        /// <param name="binder">Provides information about the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleMethod". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
        /// <param name="args">The arguments that are passed to the object member during the invoke operation. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="args"/> is equal to 100.</param>
        /// <param name="result">The result of the member invocation.</param>
        /// <returns>
        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
        /// </returns>
        public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
        {
            if (!base.TryInvokeMember(binder, args, out result))
            {
                result = Impromptu.InvokeGet(CallTarget, binder.Name);
                if (result == null)
                {
                    return(false);
                }
                var tDel = result as Delegate;
                if (!binder.CallInfo.ArgumentNames.Any() && tDel != null)
                {
                    try
                    {
                        result = this.InvokeMethodDelegate(tDel, args);
                    }
                    catch (RuntimeBinderException)
                    //If it has out parmaters etc it can't be invoked dynamically like this.
                    //if we return false it will be handle by the GetProperty and then handled by the original dynamic invocation
                    {
                        return(false);
                    }
                }
                try
                {
                    result = Impromptu.Invoke(result, Util.NameArgsIfNecessary(binder.CallInfo, args));
                }
                catch (RuntimeBinderException)//If it has out parmaters etc it can't be invoked dynamically like this.
                //if we return false it will be handle by the GetProperty and then handled by the original dynamic invocation
                {
                    return(false);
                }
            }

            return(this.MassageResultBasedOnInterface(binder.Name, true, ref result));
        }
示例#10
0
        public void TestStaticGet2()
        {
            var tVal = Impromptu.InvokeGet(typeof(StaticType).WithStaticContext(), "Test");

            Assert.AreEqual(true, tVal);
        }
示例#11
0
        /// <summary>
        /// Invokes the invocation on specified target with specific args.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        public virtual object Invoke(object target, params object[] args)
        {
            switch (Kind)
            {
            case InvocationKind.Constructor:
                return(Impromptu.InvokeConstructor((Type)target, args));

            case InvocationKind.Convert:
                bool tExplict = false;
                if (Args.Length == 2)
                {
                    tExplict = (bool)args[1];
                }
                return(Impromptu.InvokeConvert(target, (Type)args[0], tExplict));

            case InvocationKind.Get:
                return(Impromptu.InvokeGet(target, Name.Name));

            case InvocationKind.Set:
                Impromptu.InvokeSet(target, Name.Name, args.FirstOrDefault());
                return(null);

            case InvocationKind.GetIndex:
                return(Impromptu.InvokeGetIndex(target, args));

            case InvocationKind.SetIndex:
                Impromptu.InvokeSetIndex(target, args);
                return(null);

            case InvocationKind.InvokeMember:
                return(Impromptu.InvokeMember(target, Name, args));

            case InvocationKind.InvokeMemberAction:
                Impromptu.InvokeMemberAction(target, Name, args);
                return(null);

            case InvocationKind.InvokeMemberUnknown:
            {
                try
                {
                    return(Impromptu.InvokeMember(target, Name, args));
                }
                catch (RuntimeBinderException)
                {
                    Impromptu.InvokeMemberAction(target, Name, args);
                    return(null);
                }
            }

            case InvocationKind.Invoke:
                return(Impromptu.Invoke(target, args));

            case InvocationKind.InvokeAction:
                Impromptu.InvokeAction(target, args);
                return(null);

            case InvocationKind.InvokeUnknown:
            {
                try
                {
                    return(Impromptu.Invoke(target, args));
                }
                catch (RuntimeBinderException)
                {
                    Impromptu.InvokeAction(target, args);
                    return(null);
                }
            }

            case InvocationKind.AddAssign:
                Impromptu.InvokeAddAssignMember(target, Name.Name, args.FirstOrDefault());
                return(null);

            case InvocationKind.SubtractAssign:
                Impromptu.InvokeSubtractAssignMember(target, Name.Name, args.FirstOrDefault());
                return(null);

            case InvocationKind.IsEvent:
                return(Impromptu.InvokeIsEvent(target, Name.Name));

            default:
                throw new InvalidOperationException("Unknown Invocation Kind: " + Kind);
            }
        }
示例#12
0
 public static IList <Type> GetTypeArguments(this InvokeMemberBinder binder)
 {
     return(Impromptu.InvokeGet(binder, "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder.TypeArguments") as IList <Type>);
 }
示例#13
0
        /// <summary>
        /// Provides the implementation for operations that invoke an object. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as invoking an object or a delegate.
        /// </summary>
        /// <param name="binder">Provides information about the invoke operation.</param>
        /// <param name="args">The arguments that are passed to the object during the invoke operation. For example, for the sampleObject(100) operation, where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="args"/>[0] is equal to 100.</param>
        /// <param name="result">The result of the object invocation.</param>
        /// <returns>
        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.
        /// </returns>
        public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
        {
            IEnumerable <KeyValuePair <string, object> > tDict = null;
            object target = null;

            result = null;

            //Setup Properties as dictionary
            if (binder.CallInfo.ArgumentNames.Any())
            {
                if (binder.CallInfo.ArgumentNames.Count + 1 == binder.CallInfo.ArgumentCount)
                {
                    target = args.First();
                    tDict  = binder.CallInfo.ArgumentNames
                             .Zip(args.Skip(1), (key, value) => new { key, value })
                             .ToDictionary(k => k.key, v => v.value);
                }
                else
                {
                    throw new RuntimeBinderException("InvokeSetAll requires first parameter to be target unamed, and all other parameters to be named.");
                }
            }
            else if (args.Length == 2)
            {
                target = args[0];
                if (args[1] is IEnumerable <KeyValuePair <string, object> > )
                {
                    tDict = (IEnumerable <KeyValuePair <string, object> >)args[1];
                }
                else if (args[1] is IEnumerable &&
                         args[1].GetType().IsGenericType
                         )
                {
                    var tEnumerableArg = (IEnumerable)args[1];

                    var tInterface = tEnumerableArg.GetType().GetInterface("IEnumerable`1", false);
                    if (tInterface != null)
                    {
                        var tParamTypes = tInterface.GetGenericArguments();
                        if (tParamTypes.Length == 1 &&
                            tParamTypes[0].GetGenericTypeDefinition() == typeof(Tuple <,>))
                        {
                            tDict = tEnumerableArg.Cast <dynamic>().ToDictionary(k => (string)k.Item1, v => (object)v.Item2);
                        }
                    }
                }
                else if (Util.IsAnonymousType(args[1]))
                {
                    var keyDict = new Dictionary <string, object>();
                    foreach (var tProp in args[1].GetType().GetProperties())
                    {
                        keyDict[tProp.Name] = Impromptu.InvokeGet(args[1], tProp.Name);
                    }
                    tDict = keyDict;
                }
            }
            //Invoke all properties
            if (target != null && tDict != null)
            {
                foreach (var tPair in tDict)
                {
                    Impromptu.InvokeSetChain(target, tPair.Key, tPair.Value);
                }
                result = target;
                return(true);
            }
            return(false);
        }
示例#14
0
        public Document CreateDiablo3Profile(Document profiles, dynamic careerprofile, User author)
        {
            string   battleTag = careerprofile.battleTag;
            Document profile   = CreateAndPublishDocument(battleTag, BattleTagProfile.documentTypeAlias, author, profiles.Id);

            SetDocumentPropertyOrDefault(profile, BattleTagProfile.lastUpdated, careerprofile.lastUpdated);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.lastPlayedHero, careerprofile.lastHeroPlayed);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.monsters, careerprofile.kills.monsters);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.elites, careerprofile.kills.elites);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.hardcoreMonsters, careerprofile.kills.hardcoreMonsters);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.timePlayedBarbarian, careerprofile.timePlayed.barbarian);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.timePlayedDemonHunter, Convert.ToString(Impromptu.InvokeGet(careerprofile.timePlayed, "demon-hunter")));
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.timePlayedMonk, careerprofile.timePlayed.monk);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.timePlayedWicthDoctor, Convert.ToString(Impromptu.InvokeGet(careerprofile.timePlayed, "witch-doctor")));
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.timePlayedWizard, careerprofile.timePlayed.wizard);
            SetDocumentPropertyOrDefault(profile, BattleTagProfile.numberOfHeroes, Convert.ToString(careerprofile.heroes.Count));
            UmbracoUtilities.SaveAndPublish(profile);
            return(profile);
        }
示例#15
0
        public static bool AreEqual(dynamic source, dynamic target)
        {
            IEnumerable <string> list1 = Impromptu.GetMemberNames(source);

            list1 = list1.OrderBy(m => m);
            IEnumerable <string> list2 = Impromptu.GetMemberNames(target);

            list2 = list2.OrderBy(m => m);

            if (!list1.SequenceEqual(list2))
            {
                return(false);
            }

            return(list1.All(memberName => Impromptu.InvokeGet(source, memberName).Equals(Impromptu.InvokeGet(target, memberName))));
        }
示例#16
0
        public void TestStaticGet()
        {
            var tDate = Impromptu.InvokeGet(typeof(DateTime).WithStaticContext(), "Today");

            Assert.AreEqual(DateTime.Today, tDate);
        }
        public void ThenObjectShouldHavePropertyContaingString(string propName, string expectedValue)
        {
            IEnumerable collection = Impromptu.InvokeGet(Entity, propName);

            Assert.That(collection, Contains.Item(expectedValue));
        }
        public void ThenObjectShouldHavePropertyEqualTo(string propertyName, string expectedValue)
        {
            var actualValue = Impromptu.InvokeGet(Entity, propertyName);

            Assert.That(actualValue, Is.EqualTo(expectedValue));
        }