Beispiel #1
0
        public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
        {
            FieldAccessor fieldAccessor = this.FieldAccessor;
            BinderBundle  binderBundle  = binder.ToBinderBundle(invokeAttr, culture);

            fieldAccessor.SetField(obj, value, binderBundle);
        }
Beispiel #2
0
        public void test_field_accessor_can_access_getter_over_class_parents()
        {
            var cls = new Child();

            var accessor = new FieldAccessor(cls, "childField", FieldAccessType.PUBLIC_METHOD);

            accessor.Exists().Should().BeTrue();
            var obj = accessor.Get <object>();

            (obj is String).Should().BeTrue();
            ((string)obj).Should().BeEquivalentTo("Hello child!");

            accessor = new FieldAccessor(cls, "parentField", FieldAccessType.PUBLIC_METHOD);

            accessor.Exists().Should().BeTrue();
            var obj2 = accessor.Get <object>();

            (obj2 is String).Should().BeTrue();
            ((string)obj2).Should().BeEquivalentTo("Hello parent!");

            accessor = new FieldAccessor(cls, "grandparentField", FieldAccessType.PUBLIC_METHOD);

            accessor.Exists().Should().BeTrue();
            var obj3 = accessor.Get <object>();

            (obj3 is String).Should().BeTrue();
            ((string)obj3).Should().BeEquivalentTo("Hello grandparent!");
        }
Beispiel #3
0
        private void MaybeSerializeValue(SerializationInfo info, FieldAccessor field, dynamic fieldValue,
                                         dynamic fieldType)
        {
            if (fieldValue is null)
            {
                info.AddValue(field.name, null);
                return;
            }

            var  acc   = GetAccessor(field);
            bool found = GetRoot()._objsCache.TryGetValue(fieldValue, out RuntimeClassSerializer rcs);

            if (found)
            {
                rcs._nodeAccs.Add(acc);
                info.AddValue(field.name, null);
            }
            else
            {
                var newRcs = new RuntimeClassSerializer
                                 (fieldType, fieldValue, this, field);
                GetRoot()._objs.Add(newRcs);
                GetRoot()._objsCache.Add(fieldValue, newRcs);
                info.AddValue(field.name, newRcs);
            }
        }
Beispiel #4
0
        private IFieldAccessor BuildFieldAccessor(object ob, string fieldName)
        {
            var klass = ob.GetType();

            var accessType = _configurationManager.GetAccessType();

            if (_provider.HasAccessType(klass))
            {
                accessType = _provider.GetAccessType(klass);
            }
            if (_provider.HasPropertyAccessType(klass, fieldName))
            {
                accessType = _provider.GetPropertyAccessType(klass, fieldName);
            }

            var customGetter = _provider.GetPropertyCustomGetterName(klass, fieldName);

            var fieldAccessor = new FieldAccessor(ob, fieldName, accessType);

            fieldAccessor.SetCustomGetterName(customGetter);

            if (_logger != null)
            {
                fieldAccessor.SetLogger(_logger);
            }

            if (_provider.IsVirtualProperty(klass, fieldName))
            {
                fieldAccessor.SetEnsureFieldExists(false);
            }

            return(fieldAccessor);
        }
        static CustomMoreSongsFlowCoordinator()
        {
            try
            {
                SongDetailViewController = FieldAccessor <MoreSongsFlowCoordinator, SongDetailViewController> .GetAccessor("_songDetailView");

                MoreSongsNavigationController = FieldAccessor <MoreSongsFlowCoordinator, NavigationController> .GetAccessor("_moreSongsNavigationcontroller");

                MoreSongsView = FieldAccessor <MoreSongsFlowCoordinator, MoreSongsListViewController> .GetAccessor("_moreSongsView");

                DownloadQueueView = FieldAccessor <MoreSongsFlowCoordinator, DownloadQueueViewController> .GetAccessor("_downloadQueueView");

                string abortDownloadsMethodName = "AbortAllDownloads";
                AbortAllDownloadsMethod = typeof(DownloadQueueViewController).GetMethod(abortDownloadsMethodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                if (AbortAllDownloadsMethod == null)
                {
                    throw new MissingMethodException($"Method {abortDownloadsMethodName} does not exist.", abortDownloadsMethodName);
                }
                CanCreate = true;
            }
            catch (Exception ex)
            {
                CanCreate = false;
                Plugin.log.Error($"Error creating accessors for MoreSongsFlowCoordinator, Downloader will be unavailable in Multiplayer: {ex.Message}");
                Plugin.log.Debug(ex);
            }
        }
Beispiel #6
0
        public override string GetSafeName(object obj, bool hasChildren)
        {
            String name = base.GetSafeName(obj, hasChildren);

            if (hasChildren)
            {
                if (obj is IHasEvents)
                {
                    List <StoryEvent> events = (obj as IHasEvents).GetEvents();
                    name += AddNameChildren(events);
                }
                else if (obj is ObjectEditor.Json.DataObject)
                {
                    var accessors = FieldAccessor.GetForObject(obj);
                    foreach (Accessor accessor in accessors)
                    {
                        Type type = accessor.GetAccessorType();
                        if (DataObjectEditor.IsGenericList(type))
                        {
                            IList list = (IList)accessor.Get();
                            if (list == null)
                            {
                                continue;
                            }
                            Type listOf = DataObjectEditor.GetFirstGenericType(list);
                            if (typeof(Outcome).IsAssignableFrom(listOf))
                            {
                                name += AddNameChildren(list);
                            }
                        }
                    }
                }
            }
            return(name);
        }
Beispiel #7
0
        private void InitializeSO(string id, int index)
        {
            LightSwitchEventEffect lightSwitchEventEffect = _lightSwitchEventEffect;

            FieldAccessor <LightSwitchEventEffect, ColorSO> .Accessor colorSOAcessor = FieldAccessor <LightSwitchEventEffect, ColorSO> .GetAccessor(id);

            MultipliedColorSO lightMultSO = (MultipliedColorSO)colorSOAcessor(ref lightSwitchEventEffect);

            Color         multiplierColor = _multiplierColorAccessor(ref lightMultSO);
            SimpleColorSO lightSO         = _baseColorAccessor(ref lightMultSO);

            _originalColors[index] = lightSO.color;

            MultipliedColorSO mColorSO = ScriptableObject.CreateInstance <MultipliedColorSO>();

            _multiplierColorAccessor(ref mColorSO) = multiplierColor;

            SimpleColorSO sColorSO;

            if (_simpleColorSOs[index] == null)
            {
                sColorSO = ScriptableObject.CreateInstance <SimpleColorSO>();
                sColorSO.SetColor(lightSO.color);
                _simpleColorSOs[index] = sColorSO;
            }
            else
            {
                sColorSO = _simpleColorSOs[index];
            }

            _baseColorAccessor(ref mColorSO) = sColorSO;

            colorSOAcessor(ref lightSwitchEventEffect) = mColorSO;
        }
        private static IEnumerable <GuidDataObject> ListChildObjects(GuidDataObject obj, Type type)
        {
            if (obj == null)
            {
                yield break;
            }
            if (Match(obj, type))
            {
                yield return(obj);
            }
            if (!(obj is ISearchable))
            {
                yield break;
            }

            foreach (Accessor field in FieldAccessor.GetForObject(obj).ToList())
            {
                Type fieldType = field.GetAccessorType();
                if (IsGenericList(fieldType))
                {
                    IList list = field.Get() as IList;
                    foreach (object item in list)
                    {
                        foreach (GuidDataObject match in ListChildObjects(item as GuidDataObject, type))
                        {
                            yield return(match);
                        }
                    }
                }
            }
        }
 // Main initialization method
 public static void Init()
 {
     s_Accessor4_PersonID_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Guid>("<PersonID>k__BackingField");
     s_Accessor4_FirstName_k__BackingField      = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<FirstName>k__BackingField");
     s_Accessor4_LastName_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<LastName>k__BackingField");
     s_Accessor4_BirthDate_k__BackingField      = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.DateTime>("<BirthDate>k__BackingField");
     s_Accessor4_KnownAddresses_k__BackingField = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, PerfTests.Classes.AzureEntityFramework.Address[]>("<KnownAddresses>k__BackingField");
     s_Accessor4_ExternalId1_k__BackingField    = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Guid>("<ExternalId1>k__BackingField");
     s_Accessor4_ExternalId2_k__BackingField    = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Guid>("<ExternalId2>k__BackingField");
     s_Accessor4_ExternalId3_k__BackingField    = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Guid>("<ExternalId3>k__BackingField");
     s_Accessor4_ExternalId4_k__BackingField    = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Guid>("<ExternalId4>k__BackingField");
     s_Accessor4_ExternalId5_k__BackingField    = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Guid>("<ExternalId5>k__BackingField");
     s_Accessor4_Sallary1_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Decimal>("<Sallary1>k__BackingField");
     s_Accessor4_Sallary2_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Decimal>("<Sallary2>k__BackingField");
     s_Accessor4_Sallary3_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Decimal>("<Sallary3>k__BackingField");
     s_Accessor4_Sallary4_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Decimal>("<Sallary4>k__BackingField");
     s_Accessor4_Sallary5_k__BackingField       = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Decimal>("<Sallary5>k__BackingField");
     s_Accessor4_Result1_k__BackingField        = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Double>("<Result1>k__BackingField");
     s_Accessor4_Result2_k__BackingField        = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Double>("<Result2>k__BackingField");
     s_Accessor4_Result3_k__BackingField        = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Double>("<Result3>k__BackingField");
     s_Accessor4_Result4_k__BackingField        = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Double>("<Result4>k__BackingField");
     s_Accessor4_Result5_k__BackingField        = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.Double>("<Result5>k__BackingField");
     s_Accessor4_Skill1_k__BackingField         = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<Skill1>k__BackingField");
     s_Accessor4_Skill2_k__BackingField         = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<Skill2>k__BackingField");
     s_Accessor4_Skill3_k__BackingField         = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<Skill3>k__BackingField");
     s_Accessor4_Skill4_k__BackingField         = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<Skill4>k__BackingField");
     s_Accessor4_Skill5_k__BackingField         = new FieldAccessor <PerfTests.Classes.AzureEntityFramework.Person, System.String>("<Skill5>k__BackingField");
 }
Beispiel #10
0
        private void InitializeSearchBox()
        {
            if (_searchBox != null)
            {
                return;
            }

            _searchBox             = new TextBox();
            _searchBox.Location    = new Point(0, 0);
            _searchBox.Size        = new Size(70, _searchBox.Height);
            _searchBox.BorderStyle = BorderStyle.Fixed3D;
            _searchBox.Font        = new Font("Tahoma", 8.25f);

            _searchBoxBackColor = _searchBox.BackColor;

            _searchBox.TextChanged += (s, _) => ApplyFilter();

            // Hack: let's remove the read-only flag on the toolstrip controls collection
            var rofield = new FieldAccessor(ToolStrip.Controls, "_isReadOnly");

            rofield.Set(false);
            ToolStrip.Controls.Add(_searchBox);
            rofield.Set(true);

            ToolStrip.SizeChanged += (s, _) => FixSearchBoxLocation();

            FixSearchBoxLocation();

            // And now initialize accessors
            InitializeAccessors();

            PropertyTabChanged     += (s, _) => _searchBox.Text = string.Empty;
            PropertySortChanged    += (s, _) => _searchBox.Text = string.Empty;
            SelectedObjectsChanged += (s, _) => _searchBox.Text = string.Empty;
        }
Beispiel #11
0
        internal static void ReadObject(IScriptable scriptable, string body)
        {
            if (scriptable == null)
            {
                return;
            }
            if (scriptable is IReadOnlyScriptable)
            {
                return;
            }

            if (scriptable is ICustomScriptable)
            {
                ICustomScriptable s = scriptable as ICustomScriptable;
                s.Read(body);
                return;
            }

            foreach (Accessor accessor in FieldAccessor.GetForObject(scriptable))
            {
                foreach (FieldTag tag in accessor.GetTags())
                {
                    if (tag.flag == FieldTags.Title)
                    {
                        accessor.Set(body);
                        return;
                    }
                }
            }
        }
        private void AddRows(Json.DataObject obj, TableLayoutPanel tableLayout, string listPrefix = "")
        {
            tableLayout.RowCount = 0;
            List <Accessor> accessors = FieldAccessor.GetForObject(obj).ToList();

            accessors.AddRange(PropertyAccessor.GetForObject(obj));
            foreach (Accessor accessor in accessors)
            {
                IList list = accessor.Get() as IList;
                if (list != null)
                {
                    Type listOf = GetFirstGenericType(list);
                    if (!typeof(ObjectEditor.Json.DataObject).IsAssignableFrom(listOf))
                    {
                        continue;
                    }

                    comboBoxList.Items.Add(listPrefix + GetHumanReadableField(accessor.GetName()));
                    lists.Add(list);
                }
            }
            foreach (Accessor accessor in accessors)
            {
                if (!IsGenericList(accessor.GetAccessorType()))
                {
                    AddRow(accessor, tableLayout);
                }
            }
        }
Beispiel #13
0
        internal static string WriteObject(IScriptable scriptable, Indent indent = null)
        {
            if (scriptable == null)
            {
                return(null);
            }
            IIgnorable ignorable = scriptable as IIgnorable;

            if (ignorable != null && ignorable.Ignored)
            {
                return(null);
            }
            if (scriptable is ICustomScriptable)
            {
                ICustomScriptable s = scriptable as ICustomScriptable;
                string            r = s.Write();
                if (indent != null)
                {
                    r = indent.GetIndent(s.Indent()) + r;
                    if (s.Indent() == "#")
                    {
                        r += " `[" + scriptable.GetType().Name + "]`";
                    }
                }
                return(r);
            }

            if (scriptable is IReadOnlyScriptable)
            {
                string r = scriptable.ToString();
                if (indent != null)
                {
                    indent.Push(null);
                    r = "`" + r + "`";
                }
                return(r);
            }

            foreach (Accessor accessor in FieldAccessor.GetForObject(scriptable))
            {
                foreach (FieldTag tag in accessor.GetTags())
                {
                    if (tag.flag == FieldTags.Title)
                    {
                        string r = "" + accessor.Get();
                        if (indent != null)
                        {
                            r = indent.GetIndent(tag.arg) + r;
                            if (tag.arg == "#")
                            {
                                r += " `[" + scriptable.GetType().Name + "]`";
                            }
                        }
                        return(r);
                    }
                }
            }
            return(null);
        }
Beispiel #14
0
 private RuntimeClassSerializer(Type bclass, object bobject, RuntimeClassSerializer parent,
                                FieldAccessor fieldAccessor)
 {
     this._type      = bclass;
     this.obj        = bobject;
     this._parent    = parent;
     this._fromField = fieldAccessor;
 }
Beispiel #15
0
        private static string Write(IScriptable scriptable, Indent indent, int depth)
        {
            if (scriptable == null)
            {
                return("");
            }

            StringBuilder sb = new StringBuilder();

            string text = WriteObject(scriptable, indent);

            if (text != null)
            {
                if (!(scriptable is IReadOnlyScriptable))
                {
                    sb.Append("<!-- [" + depth + "](" + scriptable.GetGuid() + ") ");
                    //if (indent.Peek() == null) sb.Append("\n-->");
                    //else sb.AppendLine("-->");
                    sb.AppendLine("-->");
                }
                sb.AppendLine(text);
            }

            foreach (Accessor accessor in FieldAccessor.GetForObject(scriptable))
            {
                IList list = accessor.Get() as IList;
                if (list == null)
                {
                    continue;
                }

                for (int i = 0; i < list.Count; i++)
                {
                    IScriptable child = list[i] as IScriptable;
                    if (child == null)
                    {
                        continue;
                    }
                    IIgnorable ignorable = child as IIgnorable;
                    if (ignorable != null && ignorable.Ignored)
                    {
                        continue;
                    }
                    sb.AppendLine();
                    sb.Append(Write(child, indent, depth + 1));
                }
            }

            if (text != null)
            {
                indent.Pop();
            }

            return(sb.ToString());
        }
Beispiel #16
0
 private void Parse(Transform parentTransform)
 {
     if (!parsed)
     {
         BSMLParser.instance.Parse(BeatSaberMarkupLanguage.Utilities.GetResourceContent(Assembly.GetExecutingAssembly(), "PauseChamp.UI.Views.SettingsModal.bsml"), parentTransform.gameObject, this);
         modalPosition = modalTransform.position;
         parsed        = true;
     }
     modalTransform.position = modalPosition;
     FieldAccessor <ModalView, bool> .Set(ref modalView, "_animateParentCanvas", true);
 }
Beispiel #17
0
        public sealed override void SetValue(Object obj, Object value)
        {
            if (ReflectionTrace.Enabled)
            {
                ReflectionTrace.FieldInfo_SetValue(this, obj, value);
            }

            FieldAccessor fieldAccessor = this.FieldAccessor;

            fieldAccessor.SetField(obj, value);
        }
Beispiel #18
0
        public sealed override Object GetValue(Object obj)
        {
            if (ReflectionTrace.Enabled)
            {
                ReflectionTrace.FieldInfo_GetValue(this, obj);
            }

            FieldAccessor fieldAccessor = this.FieldAccessor;

            return(fieldAccessor.GetField(obj));
        }
Beispiel #19
0
        private LiquidExpressionResult SortByProperty(ITemplateContext ctx, LiquidCollection val, string sortfield)
        {
            if (ctx.Options.ErrorWhenValueMissing &&
                val.Any(x => FieldAccessor.TryField(ctx, x.Value, sortfield).IsError))
            {
                return(LiquidExpressionResult.Error("an array element is missing the field '" + sortfield + "'"));
            }
            var ordered = val.OrderBy(x => AsString(ctx, x, sortfield));

            return(LiquidExpressionResult.Success(new LiquidCollection(ordered.ToList())));
        }
Beispiel #20
0
        public void test_field_accessor_access_property_with_NULL_value_correctly()
        {
            var cls = new ClassWithGetters(null);

            var accessor = new FieldAccessor(cls, "id", FieldAccessType.PROPERTY);

            accessor.Exists().Should().BeTrue();
            var obj = accessor.Get <object>();

            obj.Should().BeNull();
        }
Beispiel #21
0
        public void test_field_accessor_access_getter_with_value_correctly_ensuring_that_field_exists()
        {
            var cls = new ClassWithGetters();

            var accessor = new FieldAccessor(cls, "getterWithoutProperty", FieldAccessType.PUBLIC_METHOD);

            accessor.Exists().Should().BeFalse();
            var obj = accessor.Get <object>();

            ((string)obj).Should().BeEquivalentTo(null);
        }
Beispiel #22
0
        /// <summary>
        ///Ein Test für "GetValue"
        ///</summary>
        public void GetValueTestHelper <TValueType>()
        {
            var obj       = new TweeningTestObject();
            var fieldInfo = obj.GetType().GetField("GenericValue");
            var target    = new FieldAccessor <TValueType>(obj, fieldInfo);

            var expected = default(TValueType);
            var actual   = target.GetValue();

            Assert.AreEqual(expected, actual);
        }
Beispiel #23
0
        public override LiquidExpressionResult ApplyTo(ITemplateContext ctx, LiquidCollection liquidArrayExpression)
        {
            var list = liquidArrayExpression.Select(x => x.HasValue
                ? FieldAccessor.TryField(ctx, x.Value, _selector.StringVal)
                : LiquidExpressionResult.ErrorOrNone(ctx, _selector.StringVal)).ToList();

            //new None<ILiquidValue>()).ToList();
            return(list.Any(x => x.IsError) ?
                   list.First(x => x.IsError) :
                   LiquidExpressionResult.Success(new LiquidCollection(list.Select(x => x.SuccessResult).ToList())));
        }
        public unsafe override float HasTriggered(Particle parentParticle)
        {
            if (!FieldAccessor.IsValid())
            {
                return(0f);
            }

            var remainingLifetime = (*((float *)parentParticle[FieldAccessor]));

            return((remainingLifetime <= MathUtil.ZeroTolerance) ? 1f : 0f);
        }
Beispiel #25
0
        public sealed override void SetValueDirect(TypedReference obj, object value)
        {
            if (obj.IsNull)
            {
                throw new ArgumentException(SR.Arg_TypedReference_Null);
            }

            FieldAccessor fieldAccessor = this.FieldAccessor;

            fieldAccessor.SetFieldDirect(obj, value);
        }
Beispiel #26
0
        public sealed override object GetValueDirect(TypedReference obj)
        {
            if (obj.IsNull)
            {
                throw new ArgumentException(SR.Arg_TypedReference_Null);
            }

            FieldAccessor fieldAccessor = this.FieldAccessor;

            return(fieldAccessor.GetFieldDirect(obj));
        }
Beispiel #27
0
        public unsafe override float HasTriggered(Particle parentParticle)
        {
            if (!FieldAccessor.IsValid())
            {
                return(0f);
            }

            var collisionAttribute = (*((ParticleCollisionAttribute *)parentParticle[FieldAccessor]));

            return((collisionAttribute.HasColided) ? 1f : 0f);
        }
        public unsafe override float HasTriggered(Particle parentParticle)
        {
            if (!FieldAccessor.IsValid() || !SecondFieldAccessor.IsValid())
            {
                return(0f);
            }

            var deltaPosition = ((*((Vector3 *)parentParticle[FieldAccessor])) - (*((Vector3 *)parentParticle[SecondFieldAccessor]))).Length();

            return(deltaPosition);
        }
Beispiel #29
0
 static GetUserInfo()
 {
     try
     {
         AccessPlatformUserModel = FieldAccessor <PlatformLeaderboardsModel, IPlatformUserModel> .GetAccessor("_platformUserModel");
     }
     catch (Exception ex)
     {
         Logger.log.Error($"Error getting PlatformUserModel, GetUserInfo is unavailable: {ex.Message}");
         Logger.log.Debug(ex);
     }
 }
Beispiel #30
0
        public sealed override Object GetValue(Object obj)
        {
#if ENABLE_REFLECTION_TRACE
            if (ReflectionTrace.Enabled)
            {
                ReflectionTrace.FieldInfo_GetValue(this, obj);
            }
#endif

            FieldAccessor fieldAccessor = this.FieldAccessor;
            return(fieldAccessor.GetField(obj));
        }
 private static void ReplaceCollection(HttpContext context, FieldAccessor<NameValueCollection> fieldAccessor, Func<NameValueCollection> propertyAccessor, Action<NameValueCollection> storeInUnvalidatedCollection, RequestValidationSource validationSource, ValidationSourceFlag validationSourceFlag)
 {
     NameValueCollection originalBackingCollection;
     ValidateStringCallback validateString;
     SimpleValidateStringCallback simpleValidateString;
     Func<NameValueCollection> getActualCollection;
     Action<NameValueCollection> makeCollectionLazy;
     HttpRequest request = context.Request;
     Func<bool> getValidationFlag = () => _reflectionUtil.GetRequestValidationFlag(request, validationSourceFlag);
     Func<bool> func = () => !getValidationFlag();
     Action<bool> setValidationFlag = delegate (bool value) {
         _reflectionUtil.SetRequestValidationFlag(request, validationSourceFlag, value);
     };
     if ((fieldAccessor.Value != null) && func())
     {
         storeInUnvalidatedCollection(fieldAccessor.Value);
     }
     else
     {
         originalBackingCollection = fieldAccessor.Value;
         validateString = _reflectionUtil.MakeValidateStringCallback(context.Request);
         simpleValidateString = delegate (string value, string key) {
             if (((key == null) || !key.StartsWith("__", StringComparison.Ordinal)) && !string.IsNullOrEmpty(value))
             {
                 validateString(value, key, validationSource);
             }
         };
         getActualCollection = delegate {
             fieldAccessor.Value = originalBackingCollection;
             bool flag = getValidationFlag();
             setValidationFlag(false);
             NameValueCollection col = propertyAccessor();
             setValidationFlag(flag);
             storeInUnvalidatedCollection(new NameValueCollection(col));
             return col;
         };
         makeCollectionLazy = delegate (NameValueCollection col) {
             simpleValidateString(col[null], null);
             LazilyValidatingArrayList array = new LazilyValidatingArrayList(_reflectionUtil.GetNameObjectCollectionEntriesArray(col), simpleValidateString);
             _reflectionUtil.SetNameObjectCollectionEntriesArray(col, array);
             LazilyValidatingHashtable table = new LazilyValidatingHashtable(_reflectionUtil.GetNameObjectCollectionEntriesTable(col), simpleValidateString);
             _reflectionUtil.SetNameObjectCollectionEntriesTable(col, table);
         };
         Func<bool> hasValidationFired = func;
         Action disableValidation = delegate {
             setValidationFlag(false);
         };
         Func<int> fillInActualFormContents = delegate {
             NameValueCollection values = getActualCollection();
             makeCollectionLazy(values);
             return values.Count;
         };
         DeferredCountArrayList list = new DeferredCountArrayList(hasValidationFired, disableValidation, fillInActualFormContents);
         NameValueCollection target = _reflectionUtil.NewHttpValueCollection();
         _reflectionUtil.SetNameObjectCollectionEntriesArray(target, list);
         fieldAccessor.Value = target;
     }
 }
Beispiel #32
0
        public void FieldAccessorConstructorTest()
        { 
            FieldInfo[] myFieldInfo;
            Type myType = typeof(MyClass);
            // Get the type and fields of FieldInfoClass.
            myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
                | BindingFlags.Public);

            FieldInfo fieldInfo = myFieldInfo[0];
            FieldAccessor target = new FieldAccessor(fieldInfo);
            Assert.IsNotNull(target);
        }
 public static void MakeCollectionsLazy(HttpContext context)
 {
     HttpRequest request;
     ValidationUtility.UnvalidatedCollections unvalidatedCollections;
     if (((context != null) && (context.Items[_unvalidatedCollectionsKey] == null)) && (_reflectionUtil != null))
     {
         request = context.Request;
         request.ValidateInput();
         unvalidatedCollections = new ValidationUtility.UnvalidatedCollections(request);
         context.Items[_unvalidatedCollectionsKey] = unvalidatedCollections;
         HttpContext context2 = context;
         Func<NameValueCollection> getter = () => _reflectionUtil.GetHttpRequestFormField(request);
         Action<NameValueCollection> setter = delegate (NameValueCollection val) {
             _reflectionUtil.SetHttpRequestFormField(request, val);
         };
         FieldAccessor<NameValueCollection> fieldAccessor = new FieldAccessor<NameValueCollection>(getter, setter);
         Func<NameValueCollection> propertyAccessor = () => request.Form;
         Action<NameValueCollection> storeInUnvalidatedCollection = delegate (NameValueCollection col) {
             unvalidatedCollections.Form = col;
         };
         RequestValidationSource form = RequestValidationSource.Form;
         ValidationSourceFlag needToValidateForm = ValidationSourceFlag.needToValidateForm;
         ReplaceCollection(context2, fieldAccessor, propertyAccessor, storeInUnvalidatedCollection, form, needToValidateForm);
         HttpContext context3 = context;
         Func<NameValueCollection> func3 = () => _reflectionUtil.GetHttpRequestQueryStringField(request);
         Action<NameValueCollection> action3 = delegate (NameValueCollection val) {
             _reflectionUtil.SetHttpRequestQueryStringField(request, val);
         };
         FieldAccessor<NameValueCollection> accessor2 = new FieldAccessor<NameValueCollection>(func3, action3);
         Func<NameValueCollection> func4 = () => request.QueryString;
         Action<NameValueCollection> action4 = delegate (NameValueCollection col) {
             unvalidatedCollections.QueryString = col;
         };
         RequestValidationSource queryString = RequestValidationSource.QueryString;
         ValidationSourceFlag needToValidateQueryString = ValidationSourceFlag.needToValidateQueryString;
         ReplaceCollection(context3, accessor2, func4, action4, queryString, needToValidateQueryString);
     }
 }
Beispiel #34
0
        private static FieldAccessor[] GetTypeCopyableFieldList(Type type)
        {

            if (type == null)
                throw new ArgumentNullException("type");

            FieldAccessor[] obj = (FieldAccessor[])typeFieldCache[type];
            if (obj != null) 
                return obj;

            lock (typeFieldCache)
            {
                obj = (FieldAccessor[])typeFieldCache[type];
                if (obj != null)
                    return obj;

                var lst = new List<FieldAccessor>();

                var current = type;
                while (current != null)
                {
                    foreach (FieldInfo field in current.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                        if (!field.IsInitOnly)
                        {
                            var accessor = new FieldAccessor();
                            accessor.Getter = ILGeneration.GenerateGetter(field);
                            accessor.Setter = ILGeneration.GenerateSetter(field);
                            lst.Add(accessor);
                        }

                    current = current.BaseType;
                }

                obj = lst.ToArray();

                typeFieldCache[type] = obj;
                return obj;
            }
        }