public void Test_Update_InvalidEntityMustNotUpdate()
        {
            // Create the mock entity
            MockRequiredEntity entity = new MockRequiredEntity();

            entity.TestProperty = "Test1";

            entity.Validator = new ValidateStrategy();


            // Save the entity
            SaveStrategy.New(entity, false).Save(entity);

            // Set the required property to empty
            entity.TestProperty = "";

            Assert.IsFalse(entity.IsValid, "The validator returned true when it should return false.");

            // Update the invalid entity
            bool isValid = UpdateStrategy.New(entity, false).Update(entity);

            Assert.IsFalse(isValid, "The update strategy didn't recognise the entity as invalid.");

            MockRequiredEntity foundEntity = RetrieveStrategy.New <MockRequiredEntity>(false).Retrieve <MockRequiredEntity>("ID", entity.ID);

            Assert.IsNotNull(foundEntity);

            Assert.AreNotEqual(foundEntity.TestProperty, entity.TestProperty, "The entity was updated despite being invalid.");
        }
Example #2
0
    /// <summary>
    /// Sets the followed <see cref="GameObject" />
    /// </summary>
    /// <param name="player">Player GameObject</param>
    public void SetFollowedPlayer(GameObject player)
    {
        Vector3 direction = transform.rotation * Vector3.forward;

        this.updateStrategy = () =>
        {
            if (player)
            {
                transform.position = player.transform.position - (Distance * direction);
            }
        };

        this.castStrategy = () =>
        {
            if (!player)
            {
                return;
            }

            RaycastHit hit;
            if (Physics.Linecast(transform.position, player.transform.position, out hit))
            {
                if (hit.collider.gameObject.tag == "Wall")
                {
                    MeshRenderer meshRenderer = hit.collider.gameObject.GetComponent <MeshRenderer>();
                    meshRenderer.enabled = false;
                    disabledRenderers.Add(meshRenderer);
                    MeshRenderer edgeMeshRenderer = GetMeshRenderFromChild(meshRenderer.gameObject);
                    edgeMeshRenderer.enabled = true;
                }
            }
        };
    }
        /// <summary>
        /// Updates the strategy in the strategy view
        /// </summary>
        /// <param name="updateStrategy">Contians info for the strategy to be updated</param>
        private void UpdateSelectedStrategy(UpdateStrategy updateStrategy)
        {
            try
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Updating strategy: " + updateStrategy.StrategyKey, _type.FullName, "UpdateSelectedStrategy");
                }

                // Get required stratgey to update on UI
                var selectedStrategy = _strategiesCollection.FirstOrDefault(i => i.Key == updateStrategy.StrategyKey);
                if (selectedStrategy != null)
                {
                    lock (_currentDispatcher)
                    {
                        _currentDispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
                        {
                            _strategiesCollection.Remove(selectedStrategy);
                            selectedStrategy.IsRunning = updateStrategy.IsRunning;
                            _strategiesCollection.Insert(0, selectedStrategy);
                        }));
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "UpdateSelectedStrategy");
            }
        }
        public void Update(float deltaTime)
        {
            List <Effect> effectsEllapced = new List <Effect>();

            foreach (Effect e in effects)
            {
                if (e.hasElapsed())
                {
                    e.OnTimeoutElapsed(entity);
                    effectsEllapced.Add(e);
                }
                else
                {
                    e.Update(entity, deltaTime);
                }
            }
            foreach (Effect e in effectsEllapced)
            {
                effects.Remove(e);
            }
            effectsEllapced.Clear();

            if (UpdateStrategy != null)
            {
                UpdateStrategy.Update(entity, deltaTime);
            }
            circle.Position = Position;
            circle.Rotation = Rotation;
            circle.Scale    = Scale;
            circle.Radius   = Radius;
        }
Example #5
0
        /// <summary>
        /// Authenticates the user with the provided username and password.
        /// </summary>
        /// <param name="username">The username of the user to authenticate.</param>
        /// <param name="password">The unencrypted password of the user to authenticate.</param>
        /// <returns>A value indicating whether the user's credentials are authentic.</returns>
        public bool Authenticate(string username, string password)
        {
            string encryptedPassword = Crypter.EncryptPassword(password);

            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("Username", username);
            parameters.Add("Password", encryptedPassword);

            IRetrieveStrategy strategy = RetrieveStrategy.New <User>(false);

            User user = strategy.Retrieve <User>(parameters);

            bool isAuthenticated = (user != null) &&
                                   user.IsApproved &&
                                   !user.IsLockedOut;

            if (isAuthenticated)
            {
                user.Activate();
                user.LastLoginDate = DateTime.Now;
                UpdateStrategy.New(user, false).Update(user);
            }

            return(isAuthenticated);
        }
Example #6
0
        private IEnumerable <WriteModel <T> > UpdateChangedModels(TrackedModelCollection <T> trackedModels)
        {
            var updatedModels  = trackedModels.OfState(TrackedModelState.Existing).Where(m => m.IsDirty).ToArray();
            var updateStrategy = UpdateStrategy.ForType <T>();

            return(updatedModels.Select(m => updateStrategy.GetWriteModelForUpdate(m)));
        }
        public void Test_Update_RemovesUnauthorisedReferences()
        {
            MockEntity entity = new MockEntity();

            entity.ID = Guid.NewGuid();

            MockRestrictedEntity restrictedEntity = new MockRestrictedEntity();

            restrictedEntity.ID = Guid.NewGuid();

            SaveStrategy.New(restrictedEntity, false).Save(restrictedEntity);
            SaveStrategy.New(entity, false).Save(entity);

            entity.RestrictedEntities = new MockRestrictedEntity[] {
                restrictedEntity
            };

            UpdateStrategy.New(entity).Update(entity);

            MockEntity foundEntity = RetrieveStrategy.New <MockEntity>(false).Retrieve <MockEntity>("ID", entity.ID);

            foundEntity.Activate();

            Assert.AreEqual(0, foundEntity.RestrictedEntities.Length, "Restricted entity wasn't removed from reference property.");
        }
Example #8
0
 protected AbstractTable(string tableName, UpdateStrategy updateStrategy, VerifyOnWriteStrategy verifyOnWriteStrategy
                         , DirtyCheckStrategy dirtyCheckStrategy)
 {
     TableName             = tableName;
     UpdateStrategy        = updateStrategy;
     VerifyOnWriteStrategy = verifyOnWriteStrategy;
     DirtyCheckStrategy    = dirtyCheckStrategy;
 }
        public bool Connect(Uri aUri, UpdateStrategy aUpdateStrategy)
        {
            if (IsConnected)
                throw new InvalidOperationException("Already connected.");

            mUpdateStrategy = aUpdateStrategy;

            var args = new SocketAsyncEventArgs()
            {
                RemoteEndPoint = new DnsEndPoint(aUri.Host,aUri.Port),
                UserToken = aUri
            };

            args.Completed += OnConnected;

            return Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);
        }
        public void Test_Update_AutoActivateReferences()
        {
            // Create the mock entities
            TestUser user = CreateStrategy.New <TestUser>(false).Create <TestUser>();

            user.ID        = Guid.NewGuid();
            user.FirstName = "Test";
            user.LastName  = "User";

            TestRole role = CreateStrategy.New <TestRole>(false).Create <TestRole>();

            role.ID   = Guid.NewGuid();
            role.Name = "Test Role";

            // Assign the user to the role
            user.Roles = new TestRole[] { role };

            // Save the entities
            SaveStrategy.New(role, false).Save(role);
            SaveStrategy.New(user, false).Save(user);

            // Retrieve the mock user from the data store
            TestUser foundUser = RetrieveStrategy.New <TestUser>(false).Retrieve <TestUser>("ID", user.ID);

            // Change a standard property value
            foundUser.FirstName = "Test2";

            // Update WITHOUT having activated the user manually
            // This update should automatically activate the user entity before updating and
            // should therefore persist the references
            UpdateStrategy.New(foundUser, false).Update(foundUser);

            // Retrieve the mock user again
            TestUser foundUser2 = RetrieveStrategy.New <TestUser>(false).Retrieve <TestUser>("ID", user.ID);

            // Manually activate the user
            foundUser2.Activate();

            // Assert that the referenced roles are found on the user which indicates
            // that the update strategy did automatically activate the entity and persist
            // the references
            Assert.IsNotNull(foundUser2.Roles, "Roles property is null.");
            Assert.AreEqual(1, foundUser2.Roles.Length, "Invalid number of roles assigned to user.");
        }
Example #11
0
        public bool Connect(Uri aUri, UpdateStrategy aUpdateStrategy)
        {
            if (IsConnected)
            {
                throw new InvalidOperationException("Already connected.");
            }

            mUpdateStrategy = aUpdateStrategy;

            var args = new SocketAsyncEventArgs()
            {
                RemoteEndPoint = new DnsEndPoint(aUri.Host, aUri.Port),
                UserToken      = aUri
            };

            args.Completed += OnConnected;

            return(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
        }
        /// <summary>
        /// Raised when a custom loaded strategy status changes
        /// </summary>
        /// <param name="status">Indicated if the strategy is Running/Stopped</param>
        /// <param name="strategyKey">Unique Key to identify Strategy Instance</param>
        private void OnStatusChanged(bool status, string strategyKey)
        {
            try
            {
                if (_asyncClassLogger.IsDebugEnabled)
                {
                    _asyncClassLogger.Debug("Stratgey: " + strategyKey + " is running: " + status, _type.FullName, "OnStatusChanged");
                }

                // Create a new instance to be used with event aggregator
                UpdateStrategy updateStrategy = new UpdateStrategy(strategyKey, status);

                // Publish event to notify listeners
                EventSystem.Publish <UpdateStrategy>(updateStrategy);
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "OnStatusChanged");
            }
        }
Example #13
0
        public TrackerBlock()
        {
            // Preset parameters depending on algorithm used.

            // 0.8.4 Parameters:

            /*m_UpdateStrategy = UpdateStrategy.Current;
             * m_bWorkOnGrayscale = false;
             * m_bCorrelationMatching = false;
             * m_fSimilarityTreshold = 0.80f;
             * m_fScoreTreshold = 0.80f;*/

            // 0.8.5, Profile A Parameters:
            // Note: The "Both" strategy will make annoying traj shift.

            /*m_UpdateStrategy = UpdateStrategy.Both;
             * m_bWorkOnGrayscale = false;
             * m_bCorrelationMatching = false;
             * m_fSimilarityTreshold = 0.80f;
             * m_fScoreTreshold = 0.80f;
             * m_fOriginalSimilarityThreshold = 0.90f;
             * m_fForecastDistanceWeight = 0.0f;*/

            // 0.8.5, Profile B Parameters:
            // Putting weight on the forecast may loose the tracker altogether when object change direction radically. (basket ball).

            /*m_UpdateStrategy = UpdateStrategy.Current;
             * m_bCorrelationMatching = false;
             * m_bWorkOnGrayscale = false;
             * m_fSimilarityTreshold = 0.80f;
             * m_fScoreTreshold = 0.70f;
             * m_fForecastDistanceWeight = 0.25f;*/

            // 0.8.5, Profile C Parameters:
            m_UpdateStrategy       = UpdateStrategy.Current;
            m_bCorrelationMatching = true;
            m_fSimilarityTreshold  = 0.50f;
            m_fScoreTreshold       = 0.50f;
            m_bWorkOnGrayscale     = false;
        }
        public void Test_Update()
        {
            TestArticle article = CreateStrategy.New <TestArticle>(false).Create <TestArticle>();

            article.ID    = Guid.NewGuid();
            article.Title = "Mock Title";

            Data.DataAccess.Data.Saver.Save(article);

            string newTitle = "Updated";

            article.Title = newTitle;

            IUpdateStrategy strategy = UpdateStrategy.New <TestArticle>(false);

            strategy.Update(article);

            TestArticle foundArticle = Data.DataAccess.Data.Reader.GetEntity <TestArticle>("ID", article.ID);

            Assert.IsNotNull(foundArticle);

            Assert.AreEqual(newTitle, foundArticle.Title, "Title wasn't updated.");
        }
        public void Test_Update_InactiveEntityCausesException()
        {
            // Create the mock entity
            TestUser user = CreateStrategy.New <TestUser>(false).Create <TestUser>();

            user.ID        = Guid.NewGuid();
            user.FirstName = "Test";
            user.LastName  = "User";

            // Save the entity
            SaveStrategy.New(user, false).Save(user);

            // Change a standard property value
            user.FirstName = "Test2";

            // Set AutoActivate to false otherwise it'll auto activate and won't be tested properly
            user.AutoActivate = false;

            // Set IsActivated to false
            user.IsActivated = false;

            // Update the inactive entity
            UpdateStrategy.New(user, false).Update(user);
        }
Example #16
0
 public bool Connect(string aUri, UpdateStrategy aUpdateStrategy)
 {
     return(Connect(new Uri(aUri), aUpdateStrategy));
 }
Example #17
0
 public void SetStrategy(UpdateStrategy s)
 {
     _strategy = s;
 }
Example #18
0
 public LapCounter(int lapCount, int waypointsCntPerLap)
 {
     _totalLapCnt        = lapCount;
     _waypointsCntPerLap = waypointsCntPerLap;
     _strategy           = UpdateStrategy.PreferLocal;
 }
Example #19
0
 /// <summary>
 /// Method to set UpdateStrategy
 /// </summary>
 /// <param name="updateStrategy"></param>
 public void SetUpdateStrategy(UpdateStrategy updateStrategy)
 {
     _updateStrategy = updateStrategy;
 }
Example #20
0
 public DefaultTable(string tableName, UpdateStrategy updateStrategy
                     , VerifyOnWriteStrategy verifyOnWriteStrategy, DirtyCheckStrategy dirtyCheckStrategy)
     : base(tableName, updateStrategy, verifyOnWriteStrategy, dirtyCheckStrategy)
 {
 }
Example #21
0
        public override AbstractTrackPoint CreateTrackPoint(bool _bManual, int _x, int _y, double _fSimilarity, long _t, Bitmap _CurrentImage, List <AbstractTrackPoint> _previousPoints)
        {
            // Creates a TrackPoint from the input image at the given coordinates.
            // Stores algorithm internal data in the point, to help next match.
            // _t is in relative timestamps from the first point.

            Bitmap   tpl = new Bitmap(m_BlockSize.Width, m_BlockSize.Height, PixelFormat.Format24bppRgb);
            Graphics g   = Graphics.FromImage(tpl);

            UpdateStrategy strategy = m_UpdateStrategy;

            if (_bManual)
            {
                // No points yet, or the user manually changed the point.
                // Use the block from the current image.
                strategy = UpdateStrategy.Current;
            }

            switch (strategy)
            {
            case UpdateStrategy.Original:
                // No update, we keep the original block.
                g.DrawImage(((TrackPointBlock)_previousPoints[0]).Template, 0, 0);
                break;

            case UpdateStrategy.Mixed:
            {
                // Update the template with a mix of the current block around match and the original block selected.

                // Paste the new block.
                Rectangle rDst = new Rectangle(0, 0, m_BlockSize.Width, m_BlockSize.Height);
                Rectangle rSrc = new Rectangle(_x - (m_BlockSize.Width / 2), _y - (m_BlockSize.Height / 2), m_BlockSize.Width, m_BlockSize.Height);
                g.DrawImage(_CurrentImage, rDst, rSrc, GraphicsUnit.Pixel);

                // Paste the original block at 50%.
                ColorMatrix mergeMatrix = new ColorMatrix();
                mergeMatrix.Matrix00 = 1.0f;
                mergeMatrix.Matrix11 = 1.0f;
                mergeMatrix.Matrix22 = 1.0f;
                mergeMatrix.Matrix33 = 0.5f;
                mergeMatrix.Matrix44 = 1.0f;

                ImageAttributes mergeImgAttr = new ImageAttributes();
                mergeImgAttr.SetColorMatrix(mergeMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                //g.DrawImage(m_SyncMergeImage, rSyncDst, 0, 0, m_SyncMergeImage.Width, m_SyncMergeImage.Height, GraphicsUnit.Pixel, m_SyncMergeImgAttr);
                Bitmap originalTpl = ((TrackPointBlock)_previousPoints[0]).Template;
                g.DrawImage(originalTpl, rDst, 0, 0, m_BlockSize.Width, m_BlockSize.Height, GraphicsUnit.Pixel, mergeImgAttr);

                break;
            }

            case UpdateStrategy.Current:
            case UpdateStrategy.Both:
            default:
            {
                // Update the template with the block around the new position.
                Rectangle rDst = new Rectangle(0, 0, m_BlockSize.Width, m_BlockSize.Height);
                Rectangle rSrc = new Rectangle(_x - (m_BlockSize.Width / 2), _y - (m_BlockSize.Height / 2), m_BlockSize.Width, m_BlockSize.Height);
                g.DrawImage(_CurrentImage, rDst, rSrc, GraphicsUnit.Pixel);
                break;
            }
            }

            TrackPointBlock tpb = new TrackPointBlock(_x, _y, _t, tpl);

            tpb.IsReferenceBlock = _bManual;
            tpb.Similarity       = _bManual ? 1.0f : 0;

            return(tpb);
        }
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="revisioneventTypeName">name</param>
        /// <param name="spec">specification</param>
        /// <param name="statementStopService">for stop handling</param>
        /// <param name="eventAdapterService">for nested property handling</param>
        /// <param name="eventTypeIdGenerator">The event type id generator.</param>
        public VAERevisionProcessorMerge(String revisioneventTypeName, RevisionSpec spec, StatementStopService statementStopService, EventAdapterService eventAdapterService, EventTypeIdGenerator eventTypeIdGenerator)
            : base(spec, revisioneventTypeName, eventAdapterService)
        {
            // on statement stop, remove versions
            statementStopService.StatementStopped += () => _statePerKey.Clear();
            _statePerKey = new Dictionary <Object, RevisionStateMerge>();

            // For all changeset properties, add type descriptors (property number, getter etc)
            var propertyDesc = new Dictionary <String, RevisionPropertyTypeDesc>();
            var count        = 0;

            foreach (String property in spec.ChangesetPropertyNames)
            {
                var fullGetter     = spec.BaseEventType.GetGetter(property);
                var propertyNumber = count;
                var paramList      = new RevisionGetterParameters(property, propertyNumber, fullGetter, null);

                // if there are no groups (full event property only), then simply use the full event getter
                EventPropertyGetter revisionGetter = new ProxyEventPropertyGetter(
                    eventBean =>
                {
                    var riv = (RevisionEventBeanMerge)eventBean;
                    return(riv.GetVersionedValue(paramList));
                },
                    eventBean => null,
                    eventBean => true);

                var type = spec.BaseEventType.GetPropertyType(property);
                if (type == null)
                {
                    foreach (EventType deltaType in spec.DeltaTypes)
                    {
                        var dtype = deltaType.GetPropertyType(property);
                        if (dtype != null)
                        {
                            type = dtype;
                            break;
                        }
                    }
                }

                var propertyTypeDesc = new RevisionPropertyTypeDesc(revisionGetter, paramList, type);
                propertyDesc.Put(property, propertyTypeDesc);
                count++;
            }

            count = 0;
            foreach (String property in spec.KeyPropertyNames)
            {
                var keyPropertyNumber = count;
                EventPropertyGetter revisionGetter;
                if (spec.KeyPropertyNames.Length == 1)
                {
                    revisionGetter = new ProxyEventPropertyGetter
                    {
                        ProcGet = eventBean => ((RevisionEventBeanMerge)eventBean).Key,
                        ProcIsExistsProperty = eventBean => true,
                        ProcGetFragment      = eventBean => null
                    };
                }
                else
                {
                    revisionGetter = new ProxyEventPropertyGetter
                    {
                        ProcGet = eventBean =>
                        {
                            var riv = (RevisionEventBeanMerge)eventBean;
                            return(((MultiKeyUntyped)riv.Key).Keys[keyPropertyNumber]);
                        },
                        ProcIsExistsProperty = eventBean => true,
                        ProcGetFragment      = eventBean => null
                    };
                }

                var type = spec.BaseEventType.GetPropertyType(property);
                if (type == null)
                {
                    foreach (EventType deltaType in spec.DeltaTypes)
                    {
                        var dtype = deltaType.GetPropertyType(property);
                        if (dtype != null)
                        {
                            type = dtype;
                            break;
                        }
                    }
                }
                var propertyTypeDesc = new RevisionPropertyTypeDesc(revisionGetter, null, type);
                propertyDesc.Put(property, propertyTypeDesc);
                count++;
            }

            // compile for each event type a list of getters and indexes within the overlay
            foreach (EventType deltaType in spec.DeltaTypes)
            {
                RevisionTypeDesc typeDesc = MakeTypeDesc(deltaType, spec.PropertyRevision);
                TypeDescriptors.Put(deltaType, typeDesc);
            }
            _infoFullType = MakeTypeDesc(spec.BaseEventType, spec.PropertyRevision);

            // how to handle updates to a full event
            if (spec.PropertyRevision == PropertyRevisionEnum.MERGE_DECLARED)
            {
                _updateStrategy = new UpdateStrategyDeclared(spec);
            }
            else if (spec.PropertyRevision == PropertyRevisionEnum.MERGE_NON_NULL)
            {
                _updateStrategy = new UpdateStrategyNonNull(spec);
            }
            else if (spec.PropertyRevision == PropertyRevisionEnum.MERGE_EXISTS)
            {
                _updateStrategy = new UpdateStrategyExists(spec);
            }
            else
            {
                throw new ArgumentException("Unknown revision type '" + spec.PropertyRevision + "'");
            }

            EventTypeMetadata metadata = EventTypeMetadata.CreateValueAdd(revisioneventTypeName, TypeClass.REVISION);

            RevisionEventType = new RevisionEventType(metadata, eventTypeIdGenerator.GetTypeId(revisioneventTypeName), propertyDesc, eventAdapterService);
        }
 public bool Connect(string aUri, UpdateStrategy aUpdateStrategy)
 {
     return Connect(new Uri(aUri), aUpdateStrategy);
 }