public IList <string> GetErrorMessages(T entity, string fieldname)
        {
            List <string> list = new List <string>();

            if (UseAttributes)
            {
                var validationResults = new List <ValidationResult>();
                var isValid           = ValidateProperty(entity, fieldname, validationResults);

                if (validationResults.Count > 0)
                {
                    list.AddRange(validationResults.Select(v => v.ErrorMessage));
                }
            }

            if (_propertyRules != null && PropertyRules.ContainsKey(fieldname))
            {
                string msg = PropertyRules[fieldname].GetMessage(entity, Accessors[fieldname](entity));
                if (!string.IsNullOrEmpty(msg))
                {
                    list.Add(msg);
                }
            }

            return(list);
        }
        //property level
        bool ValidateProperty(T entity, string fieldname, List <ValidationResult> validationResults)
        {
            var vc = new ValidationContext(entity, null, null);

            //This does not work correctly for types with custom ITypeDescriptor!
            if (!_isCustomTypeDescriptor)
            {
                vc.MemberName = fieldname;
                return(Validator.TryValidateProperty(Accessors[fieldname](entity), vc, validationResults));
            }

            bool isValid = true;

            foreach (var prop in TypeDescriptor.GetProperties(entity, false).Cast <PropertyDescriptor>())
            {
                if (prop.Name != fieldname)
                {
                    continue;
                }
                foreach (var attr in prop.Attributes)
                {
                    var val = attr as ValidationAttribute;
                    if (val == null)
                    {
                        continue;
                    }
                    var v = prop.GetValue(entity);
                    if (!Validator.TryValidateValue(v, vc, validationResults, new[] { val }))
                    {
                        isValid = false;
                    }
                }
            }
            return(isValid);
        }
Exemplo n.º 3
0
        public static void OnSpriteLoaded(object sender, EventArgs e)
        {
            if (sender is IDeferredSpriteLoad deferredSpriteLoad)
            {
                if (EventTable.TryGetValue(deferredSpriteLoad, out AnnotatedBeatmapLevelCollectionTableCell tableCell))
                {
                    IAnnotatedBeatmapLevelCollection collection = Accessors.BeatmapCollectionAccessor(ref tableCell);
                    if (collection == deferredSpriteLoad)
                    {
#if DEBUG
                        Plugin.Log.Debug($"Updating image for {collection.collectionName}");
#endif
                        Accessors.CoverImageAccessor(ref tableCell).sprite = deferredSpriteLoad.Sprite;
                    }
                    else
                    {
                        Plugin.Log.Warn($"Collection '{collection.collectionName}' is not {(deferredSpriteLoad as IAnnotatedBeatmapLevelCollection).collectionName}");
                        EventTable.Remove(deferredSpriteLoad);
                        deferredSpriteLoad.SpriteLoaded -= OnSpriteLoaded;
                    }
                }
                else
                {
                    Plugin.Log.Warn($"{(deferredSpriteLoad as IAnnotatedBeatmapLevelCollection).collectionName} is not in the EventTable.");
                    deferredSpriteLoad.SpriteLoaded -= OnSpriteLoaded;
                }
            }
            else
            {
                Plugin.Log.Warn($"Wrong sender type for deferred sprite load: {sender?.GetType().Name ?? "<NULL>"}");
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// The update method.
        /// </summary>
        public void Update()
        {
            if (_saber != null && _saber.gameObject.activeInHierarchy && !_saber.disableCutting)
            {
                var topTrans = Accessors.SaberBladeTopTransform(ref _saber);
                var botTrans = Accessors.SaberBladeBottomTransform(ref _saber);

                var topPos = Accessors.SaberBladeTopPosition(ref _saber) = topTrans.position;
                var botPos = Accessors.SaberBladeBottomPosition(ref _saber) = botTrans.position;

                int i = 0;
                var swingRatingCounters       = Accessors.SwingRatingCounters(ref _saber);
                var unusedSwingRatingCounters = Accessors.UnusedSwingRatingCounters(ref _saber);
                while (i < swingRatingCounters.Count)
                {
                    var counter = swingRatingCounters[i];
                    if (counter.didFinish)
                    {
                        counter.Deinit();
                        swingRatingCounters.RemoveAt(i);
                        unusedSwingRatingCounters.Add(counter);
                    }
                    else
                    {
                        i++;
                    }
                }
                Accessors.MovementData(ref _saber).AddNewData(topPos, botPos, TimeHelper.time);
                _noteCutter.Cut(_saber);
            }
        }
Exemplo n.º 5
0
        internal void Construct(NoteCutter noteCutter, ColorManager colorManager, SaberProvider saberProvider, SiraSaberEffectManager siraSaberEffectManager)
        {
            _noteCutter             = noteCutter;
            _colorManager           = colorManager;
            _saberProvider          = saberProvider;
            _siraSaberEffectManager = siraSaberEffectManager;
            // Create all the stuff thats supposed to be on the saber
            _saberTypeObject = gameObject.AddComponent <SaberTypeObject>();
            Accessors.ObjectSaberType(ref _saberTypeObject) = nextType;

            // Create and populate the saber object
            _saber = gameObject.AddComponent <Saber>();
            Accessors.SaberObjectType(ref _saber) = _saberTypeObject;
            var top    = new GameObject("Top");
            var bottom = new GameObject("Bottom");

            top.transform.SetParent(transform);
            bottom.transform.SetParent(transform);
            top.transform.position = new Vector3(0f, 0f, 1f);

            Accessors.SaberHandleTransform(ref _saber)      = bottom.transform;
            Accessors.SaberBladeTopTransform(ref _saber)    = top.transform;
            Accessors.SaberBladeBottomTransform(ref _saber) = bottom.transform;
            Accessors.SaberBladeTopPosition(ref _saber)     = top.transform.position;
            Accessors.SaberBladeBottomPosition(ref _saber)  = bottom.transform.position;

            _saberProvider.GetModel(smc => smc.Init(transform, _saber));

            _siraSaberEffectManager.SaberCreated(_saber);
        }
Exemplo n.º 6
0
        public void Update(Accessors accessors)
        {
            float x = 0;
            float y = 0;

            x += accessors.Input.GetKey(SharpDX.DirectInput.Key.D) ? 1.0f : 0.0f;
            x -= accessors.Input.GetKey(SharpDX.DirectInput.Key.A) ? 1.0f : 0.0f;

            y += accessors.Input.GetKey(SharpDX.DirectInput.Key.W) ? 1.0f : 0.0f;
            y -= accessors.Input.GetKey(SharpDX.DirectInput.Key.S) ? 1.0f : 0.0f;

            cameraEulerRotation.X = 0;

            cameraEulerRotation.Y -= accessors.Input.GetKey(SharpDX.DirectInput.Key.Right) ? 1.0f : 0.0f;
            cameraEulerRotation.Y += accessors.Input.GetKey(SharpDX.DirectInput.Key.Left) ? 1.0f : 0.0f;

            cameraEulerRotation.Z += accessors.Input.GetKey(SharpDX.DirectInput.Key.Up) ? 1.0f : 0.0f;
            cameraEulerRotation.Z -= accessors.Input.GetKey(SharpDX.DirectInput.Key.Down) ? 1.0f : 0.0f;

            cameraEulerRotation.Y = cameraEulerRotation.Y % 360;
            cameraEulerRotation.Z = cameraEulerRotation.Z % 360;


            Owner.SetEulerRotation(cameraEulerRotation * 2.0f);

            Rendering.Camera camera = (Rendering.Camera)Owner.GetChildren()[0];

            Vector3 movement = new Vector3(x, 0, y) * 0.1f;
            Vector3 newPos   = Owner.GetPosition() + AdjustDirectionToCamera(movement);

            Owner.SetPosition(newPos);
        }
Exemplo n.º 7
0
        internal static void Prefix(ref BeatmapObjectsInstaller __instance, ref GameNoteController ____normalBasicNotePrefab, ref BombNoteController ____bombNotePrefab)
        {
            var         mib       = __instance as MonoInstallerBase;
            DiContainer Container = Accessors.GetDiContainer(ref mib);

            _staticGameNotePrefab = ____normalBasicNotePrefab;
            _staticBombNotePrefab = ____bombNotePrefab;

            if (_staticGameNotePrefab != null)
            {
                ____normalBasicNotePrefab = _staticGameNotePrefab;
            }
            if (_staticBombNotePrefab != null)
            {
                ____bombNotePrefab = _staticBombNotePrefab;
            }

            var normal = InstallModelProviderSystem(Container, ____normalBasicNotePrefab);
            var bomb   = InstallModelProviderSystem(Container, ____bombNotePrefab);

            if (normal != null)
            {
                normal.gameObject.SetActive(false);
                ____normalBasicNotePrefab.gameObject.SetActive(false);
                ____normalBasicNotePrefab = normal;
            }
            if (bomb != null)
            {
                bomb.gameObject.SetActive(false);
                ____bombNotePrefab.gameObject.SetActive(false);
                ____bombNotePrefab = bomb;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// This method assumes no concurrent accesses, and that the new item isn't already in the list
        /// </summary>
        internal void UnsafeAddItems <TPendingItem>(IEnumerable <TPendingItem> pendingItems)
            where TPendingItem : IPendingSetItem <TItem>
        {
            Accessors accessors = m_accessors;

            foreach (var pendingItem in pendingItems)
            {
                int bucketHashCode = GetBucketHashCode(pendingItem.HashCode);

                int lockNo = 0;

                // Number of nodes searched to find the item or the total number of nodes if the item is not found
                var result = FindItem(
                    pendingItem,
                    bucketHashCode,
                    out int bucketNo,
                    out int headNodeIndex,
                    ref accessors,
                    out int findCount,
                    out int priorNodeIndex);
                Contract.Assert(!result.IsFound);

                // now make an item from the lookup value
                TItem item = pendingItem.CreateOrUpdateItem(result.Item, false, out bool remove);
                Contract.Assert(!remove, "Remove is only allowed when performing update operation");
                SetBucketHeadNode(bucketNo, lockNo, bucketHashCode, headNodeIndex, item, ref accessors);
                int countAfterAdd = Interlocked.Increment(ref m_count);

                if (countAfterAdd != 0)
                {
                    PerformPostInsertSplitOperations(ref accessors, countAfterAdd);
                }
            }
        }
Exemplo n.º 9
0
 public void TestAsLambdaTypeNotFound()
 {
     Assert.That(
         () => Accessors <Book> .AsLambda <long>("Author"),
         Throws.InstanceOf <MissingMemberException>()
         );
 }
Exemplo n.º 10
0
        internal static void Prefix(ref MultiplayerConnectedPlayerInstaller __instance,
                                    ref MultiplayerConnectedPlayerGameNoteController ____multiplayerGameNoteControllerPrefab,
                                    ref MultiplayerConnectedPlayerBombNoteController ____multiplayerBombNoteControllerPrefab)
        {
            var         mib       = __instance as MonoInstallerBase;
            DiContainer Container = Accessors.GetDiContainer(ref mib);

            _staticMultiplayerGameNotePrefab = ____multiplayerGameNoteControllerPrefab;
            _staticMultiplayerBombNotePrefab = ____multiplayerBombNoteControllerPrefab;

            if (_staticMultiplayerGameNotePrefab != null)
            {
                ____multiplayerGameNoteControllerPrefab = _staticMultiplayerGameNotePrefab;
            }
            if (_staticMultiplayerBombNotePrefab != null)
            {
                ____multiplayerBombNoteControllerPrefab = _staticMultiplayerBombNotePrefab;
            }

            var normal = BeatmapObjectRedecorator.InstallModelProviderSystem(Container, ____multiplayerGameNoteControllerPrefab);
            var bomb   = BeatmapObjectRedecorator.InstallModelProviderSystem(Container, ____multiplayerBombNoteControllerPrefab);

            if (normal != null)
            {
                ____multiplayerGameNoteControllerPrefab = normal;
            }
            if (bomb != null)
            {
                ____multiplayerBombNoteControllerPrefab = bomb;
            }
        }
    private static Task <Document> RemovePropertySetterAsync(
        Document document,
        SyntaxNode root,
        PropertyDeclarationSyntax?declaration)
    {
        if (declaration is null)
        {
            return(Task.FromResult(document));
        }

        var setter = declaration.AccessorList?.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.SetAccessorDeclaration));

        if (setter is not null)
        {
            var newAccessors    = declaration.AccessorList !.Accessors.Remove(setter);
            var newAccessorList = declaration.AccessorList.WithAccessors(newAccessors);
            var newDeclaration  = declaration.WithAccessorList(newAccessorList);
            var newRoot         = root.ReplaceNode(declaration, newDeclaration);
            var newDoc          = document.WithSyntaxRoot(newRoot);

            document = newDoc;
        }

        return(Task.FromResult(document));
    }
Exemplo n.º 12
0
        internal static void Prefix(GameplayCoreInstaller __instance, ref GameplayCoreSceneSetupData ____sceneSetupData)
        {
            var mib       = __instance as MonoInstallerBase;
            var Container = Accessors.GetDiContainer(ref mib);

            Container.BindInterfacesAndSelfTo <Submission>().AsSingle();
        }
Exemplo n.º 13
0
        internal static Accessors GetAccessors(PropertyInfo member)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(new Accessors(inst => Helpers.GetPropertyValue(member, inst), (inst, v) => member.SetValue(inst, v, null)));
            }
            Accessors accessors;

            lock (Properties)
            {
                if (Properties.TryGetValue(member, out accessors))
                {
                    return(accessors);
                }
            }

            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(member.ReflectedType, member) ?? (inst => Helpers.GetPropertyValue(member, inst));
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(member.ReflectedType, member) ?? ((inst, v) => member.SetValue(inst, v, null));

            accessors = new Accessors(getter, setter);

            lock (Properties)
                Properties[member] = accessors;

            return(accessors);
        }
Exemplo n.º 14
0
 public void TestAsLambdaNameNotFound()
 {
     Assert.That(
         () => Accessors <Book> .AsLambda <string>(nameof(Book.Author) + "5"),
         Throws.InstanceOf <MissingMemberException>()
         );
 }
        private Accessors GetAccessors(Type type)
        {
            if (_accessors.TryGetValue(type, out var value))
            {
                return(value);
            }

            lock (_locker)
            {
                if (_accessors.TryGetValue(type, out value))
                {
                    return(value);
                }

                var accessor = new Accessors
                {
                    PropertyNameGetter = type.GetProperty("PropertyName")?.MakeGetterDelegate <string>()
                };

                // have to create a new instance here, because readers don't have any
                // synchronization with writers.
                var newAccessors = new Dictionary <Type, Accessors>(_accessors)
                {
                    [type] = accessor
                };

                // This memory barrier is needed if this class is ever used in
                // a weaker memory model implementation, allowed by the CLR
                // specification.
                Interlocked.MemoryBarrier();

                _accessors = newAccessors;
                return(accessor);
            }
        }
Exemplo n.º 16
0
        internal void ToggleSelectedDifficultyHighlight()
        {
            if (selectedPlaylistSong != null)
            {
                List <SegmentedControlCell> difficultyCells = Accessors.SegmentedControllerCellsAccessor(ref beatmapDifficultySegmentedControl);
                if (IsSelectedDifficultyHighlighted)
                {
                    selectedPlaylistSong.Difficulties.RemoveAll(d => d.BeatmapDifficulty == beatmapDifficultySegmentedControlController.selectedDifficulty);
                    SegmentedControlCell cellToUnhighlight = difficultyCells[beatmapDifficultySegmentedControlController.GetClosestDifficultyIndex(beatmapDifficultySegmentedControlController.selectedDifficulty)];
                    CurvedTextMeshPro    textToUnhighlight = cellToUnhighlight.GetComponentInChildren <CurvedTextMeshPro>();
                    textToUnhighlight.faceColor = new UnityEngine.Color32(255, 255, 255, 255);
                }
                else
                {
                    if (selectedPlaylistSong.Difficulties == null)
                    {
                        selectedPlaylistSong.Difficulties = new List <Difficulty>();
                    }
                    Difficulty difficulty = new Difficulty();
                    difficulty.BeatmapDifficulty = beatmapDifficultySegmentedControlController.selectedDifficulty;
                    difficulty.Characteristic    = beatmapCharacteristicSegmentedControlController.selectedBeatmapCharacteristic.serializedName;
                    selectedPlaylistSong.AddDifficulty(difficulty);

                    SegmentedControlCell cellToHighlight = difficultyCells[beatmapDifficultySegmentedControlController.GetClosestDifficultyIndex(beatmapDifficultySegmentedControlController.selectedDifficulty)];
                    CurvedTextMeshPro    textToHighlight = cellToHighlight.GetComponentInChildren <CurvedTextMeshPro>();
                    textToHighlight.faceColor = new UnityEngine.Color32(255, 255, 0, 255);
                }
            }
        }
 public void Refresh()
 {
     if (folderMode == FolderMode.AllPacks)
     {
         IBeatmapLevelPack[] annotatedBeatmapLevelCollections = Accessors.CustomLevelPackCollectionAccessor(ref beatmapLevelsModel).beatmapLevelPacks.Concat(PlaylistLibUtils.playlistManager.GetAllPlaylists(true)).ToArray();
         int indexToSelect = annotatedBeatmapLevelCollections.IndexOf(annotatedBeatmapLevelCollectionsViewController.selectedAnnotatedBeatmapLevelCollection);
         if (indexToSelect != -1)
         {
             annotatedBeatmapLevelCollectionsViewController.SetData(annotatedBeatmapLevelCollections, indexToSelect, false);
         }
     }
     else if (folderMode == FolderMode.Playlists)
     {
         BeatSaberPlaylistsLib.Types.IPlaylist[] annotatedBeatmapLevelCollections = PlaylistLibUtils.playlistManager.GetAllPlaylists(true);
         int indexToSelect = annotatedBeatmapLevelCollections.IndexOf(annotatedBeatmapLevelCollectionsViewController.selectedAnnotatedBeatmapLevelCollection);
         if (indexToSelect != -1)
         {
             annotatedBeatmapLevelCollectionsViewController.SetData(annotatedBeatmapLevelCollections, indexToSelect, false);
         }
     }
     else if (folderMode == FolderMode.Folders)
     {
         BeatSaberPlaylistsLib.Types.IPlaylist[] annotatedBeatmapLevelCollections = currentParentManager.GetAllPlaylists(false);
         int indexToSelect = annotatedBeatmapLevelCollections.IndexOf(annotatedBeatmapLevelCollectionsViewController.selectedAnnotatedBeatmapLevelCollection);
         if (indexToSelect != -1)
         {
             annotatedBeatmapLevelCollectionsViewController.SetData(annotatedBeatmapLevelCollections, indexToSelect, false);
         }
         SetupList(currentParentManager, false);
     }
 }
Exemplo n.º 18
0
 public void TestPropertyAsLambdaCache()
 {
     Assert.That(
         Accessors <Book> .AsLambda <string>(nameof(Book.Author)),
         Is.SameAs(Accessors <Book> .AsLambda <string>(nameof(Book.Author)))
         );
 }
Exemplo n.º 19
0
 public void TestFieldAsLambdaCache()
 {
     Assert.That(
         Accessors <Book> .AsLambda <string>(nameof(Book.Name)),
         Is.SameAs(Accessors <Book> .AsLambda <string>(nameof(Book.Name)))
         );
 }
Exemplo n.º 20
0
        public _TestState(Accessors accessors) : base("TestState", accessors)
        {
            testObject = new GameObject("testObject", 0);
            testObject.SetPosition(new SharpDX.Vector3(0, 0, -4));

            sphere = new GameObject("sphere", 0);
            sphere.SetPosition(new Vector3(0, 0, 0));
            sphere.Name = "Sphere";

            testUI = new GameObject("testUI", 0);


            groundPlane = new GameObject("groundPlane", 0);
            stateScene.AddObjectAsRootChild(groundPlane);
            groundPlane.SetPosition(new Vector3(0, -1, 0));
            groundPlane.SetEulerRotation(new Vector3(0, 0, 90));
            groundPlane.SetScale(new Vector3(10, 10, 10));



            //stateScene.AddObjectAsRootChild(testObject);
            stateScene.AddObjectAsRootChild(sphere);
            uiScene.AddObjectAsRootChild(testUI);

            cameraHandle = new GameObject("cameraHandle", 0);
            cameraHandle.AddChild(stateScene.Camera);
            cameraHandle.Components.Create <ComponentSystem._FPSCameraComponent>();
            cameraHandle.SetPosition(new Vector3(0, 0, -7));

            stateScene.AddObjectAsRootChild(cameraHandle);

            sphere.AddChild(testObject);
            //testObject.SetParent(sphere);
        }
Exemplo n.º 21
0
 public SparkViewDescriptor AddAccessor(string property, string getValue)
 {
     Accessors.Add(new Accessor {
         Property = property, GetValue = getValue
     });
     return(this);
 }
Exemplo n.º 22
0
            public Subscription(SubscriptionDic <T, TSubscriber> sdic, Type targetType, object target, string eventName)
            {
                _sdic      = sdic;
                _target    = target;
                _eventName = eventName;
                Dictionary <string, EventInfo> evDic;

                if (!Accessors.TryGetValue(targetType, out evDic))
                {
                    Accessors[targetType] = evDic = new Dictionary <string, EventInfo>();
                }

                if (!evDic.TryGetValue(eventName, out _info))
                {
                    var ev = targetType.GetRuntimeEvents().FirstOrDefault(x => x.Name == eventName);

                    if (ev == null)
                    {
                        throw new ArgumentException(
                                  $"The event {eventName} was not found on {target.GetType()}.");
                    }

                    evDic[eventName] = _info = ev;
                }

                var del = new Action <object, T>(OnEvent);

                _delegate = del.GetMethodInfo().CreateDelegate(_info.EventHandlerType, del.Target);
                _info.AddMethod.Invoke(target, new[] { _delegate });
            }
        /// <summary>
        /// Handles movie searches.
        /// </summary>
        /// <param name="stepContext">The step context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task&lt;DialogTurnResult&gt;.</returns>
        private async Task <DialogTurnResult> HandleMovieSearch(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userProfile = await Accessors.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);

            var client = new TMDbClient(Settings.ApiSettings.MovieDatabaseApiKey);
            var result = await client.SearchMovieAsync(userProfile.MovieDownload.Title, cancellationToken : cancellationToken);

            if (result.TotalResults == 0)
            {
                var noResultsActivity = MessageFactory.Text(Resources.MovieDialog_ImdbSearch_NoResults);

                await stepContext.Context.SendActivityAsync(noResultsActivity, cancellationToken);

                return(await stepContext.ReplaceDialogAsync(TitleWaterFall, cancellationToken : cancellationToken));
            }
            else
            {
                var options = result.Results.Select(resultItem =>
                                                    new AttachmentOption
                {
                    ImageUrl = ActivityHelpers.FormatTmdbPosterPath(resultItem.PosterPath),
                    Value    = resultItem.Id.ToString(),
                    Title    = resultItem.Title
                }).ToList();

                userProfile.MovieDownload.SearchOptions = options;

                var activity = ActivityHelpers.GetCardChoicesFromOptions(Resources.MovieDialog_SelectMovie_Message, options, AttachmentLayoutTypes.Carousel, true);
                return(await stepContext.PromptAsync(TextPromptDialog, new PromptOptions
                {
                    Prompt = activity
                }, cancellationToken));
            }
        }
Exemplo n.º 24
0
 public void TestAsFuncNameNotFound()
 {
     Assert.That(
         () => Accessors <Book> .AsFunc <string>("Author5"),
         Throws.InstanceOf <MissingMemberException>()
         );
 }
Exemplo n.º 25
0
 public void TestAsFuncTypeNotFound()
 {
     Assert.That(
         () => Accessors <Book> .AsFunc <long>(nameof(Book.Author)),
         Throws.InstanceOf <MissingMemberException>()
         );
 }
Exemplo n.º 26
0
        internal static Accessors GetAccessors(FieldInfo member)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(new Accessors(member.GetValue, member.SetValue));
            }
            Accessors accessors;

            lock (Fields)
            {
                if (Fields.TryGetValue(member, out accessors))
                {
                    return(accessors);
                }
            }

            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(member.ReflectedType, member) ?? member.GetValue;
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(member.ReflectedType, member) ?? member.SetValue;

            accessors = new Accessors(getter, setter);

            lock (Fields)
                Fields[member] = accessors;

            return(accessors);
        }
Exemplo n.º 27
0
        private Accessors GetAccessors(Type type)
        {
            Accessors value;

            if (accessors.TryGetValue(type, out value))
            {
                return(value);
            }
            lock (this)
            {
                if (accessors.TryGetValue(type, out value))
                {
                    return(value);
                }
                var accessor = new Accessors
                {
                    PropertyNameGetter = type.GetTypeInfo().GetDeclaredProperty("PropertyName")?.MakeGetterDelegate <string>()
                };
                // have to create a new instance here, because readers don't have any
                // syncronization with writers.
                accessors = new Dictionary <Type, Accessors>(accessors)
                {
                    [type] = accessor
                };
                return(accessor);
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Create deep clone of the property data object.
 /// </summary>
 public object Clone()
 {
     return(new PropertyData()
     {
         Accessors = (AccessorType[])Accessors.Clone(),
         Type = Type
     });
 }
        public void Wrong_Argument_Should_Throw()
        {
            Expression <Func <TestClass, object> > expr = s => s.Property;

            var foundAccessor = Accessors.Find(typeof(TestClass).GetProperty(nameof(TestClass.Property)));

            Assert.Throws <InvalidCastException>(() => foundAccessor.Get("Not a TestClass but string"));
        }
Exemplo n.º 30
0
 //static FastGetter<InteractionHighlightController, bool> IsHighlightingGet;
 //static FastSetter<InteractionHighlightController, bool> IsHighlightingSet;
 static bool Prepare()
 {
     // Accessors.CreateFieldRef<KingdomEvent, int>("m_StartedOn");
     m_IsHighlightingRef = Accessors.CreateFieldRef <InteractionHighlightController, bool>("m_IsHighlighting");
     //IsHighlightingGet = Accessors.CreateFieldRe<InteractionHighlightController, bool>("IsHighlighting");
     //IsHighlightingSet = Accessors.CreateSetter<InteractionHighlightController, bool>("IsHighlighting");
     return(true);
 }
        private Accessors GetAccessors(Type type)
        {
            // ReSharper disable InconsistentlySynchronizedField
            if (!accessors.ContainsKey(type))
                lock (accessors)
                    if (!accessors.ContainsKey(type))
                    {
                        var accessor = new Accessors
                        {
                            PropertyNameGetter = type.GetProperty("PropertyName")?.MakeGetterDelegate<string>()
                        };
                        Thread.MemoryBarrier();
                        accessors[type] = accessor;
                        return accessor;
                    }

            return accessors[type];
            // ReSharper restore InconsistentlySynchronizedField
        }
Exemplo n.º 32
0
		public static Accessor Translate(Accessors accessor)
		{
			return accessorsDictionary[accessor];
		}
Exemplo n.º 33
0
 internal DomAccessorAttribute(Accessors type)
 {
     Type = type;
 }
Exemplo n.º 34
0
 /// <summary>
 /// Creates a new DomAccessorAttribute.
 /// </summary>
 /// <param name="type">
 /// The type of accessors to apply.
 /// </param>
 public DomAccessorAttribute(Accessors type)
 {
     Type = type;
 }