예제 #1
0
        public async Task MoveStep_WithIncorrectTarget_MustNotMove()
        {
            //Arrange
            var stateManager      = new MockState().MockStateManager();
            var instance          = MockData.GetFlowInstances().FirstOrDefault();
            var flowManager       = new ManagerFactory().GetFlowManager(stateManager);
            var flowReportManager = new ManagerFactory().GetFlowReportManager(stateManager);
            var existTransitions  = await flowReportManager.GetInstanceTransitionsAsync(instance.Id);

            var transitions      = existTransitions.Result.Select(x => x.Id).ToList();
            var targetTransition = MockData.GetFlowTransitions()
                                   .FirstOrDefault(x => transitions.Contains(x.Id) == false);

            var moveModel = new MoveModel()
            {
                IdentityId   = "1",
                InstanceId   = instance.Id,
                Payload      = string.Empty,
                TransitionId = targetTransition.Id,
                Comment      = "Sure, It's ok.",
            };
            //Act
            var act = await flowManager.MoveAsync(moveModel);

            //Assert
            LogTestInfo(moveModel, act);
            Assert.False(act.Succeeded);
            Assert.NotEmpty(act.Errors);
        }
예제 #2
0
        /// <summary>
        /// Execute the player move. This would need way more information in full implementation.
        /// Should just be ExecuteMove, take the source and the target and apply result accordingly
        /// </summary>
        /// <param name="move"></param>
        IEnumerator ExecuteMove(MoveModel move, BaseBattleAgent source, BaseBattleAgent target)
        {
            uiManager.battleTextPanel.SetInfoText($"{source.CurrentStats.agentName} used {move.MoveName}!");
            var roll = UnityEngine.Random.Range(0, move.Accuracy);

            yield return(new WaitForSeconds(2));

            if (roll >= move.Accuracy)
            {
                Debug.Log($"missed!");
                Debug.Log($"roll {roll}, Move accuracy: {move.Accuracy}");
                yield return(new WaitForSeconds(3));
            }
            else
            {
                target.Damage(move.Power);
                uiManager.battleTextPanel.SetInfoText($"Hit for {move.Power} damage!");
                yield return(new WaitForSeconds(3));

                if (target.GetType() == typeof(PlayerBattleAgent))
                {
                    uiManager.playerStatusPanel.UpdateHealthText(target.CurrentStats.healthPoints, target.BaseStats.healthPoints);
                }
                else
                {
                    uiManager.enemyStatusPanel.UpdateHealthText(target.CurrentStats.healthPoints, target.BaseStats.healthPoints);
                }
                uiManager.battleTextPanel.SetInfoText($"{target.CurrentStats.agentName} has {target.CurrentStats.healthPoints} hp!");
                yield return(new WaitForSeconds(3));
            }
            executing = false;
        }
예제 #3
0
    public void Move(MoveModel move, ref PieceModel [,] board)
    {
        board[move.y, move.x] = this;
        board[y, x]           = null;
        x = move.x;
        y = move.y;
        // next steps here
        if (move.isCapture())
        {
            PieceModel piece = board[move.capture.removeY, move.capture.removeX];
            piece.doRemove(ref board);
            OnJump();
        }
        else
        {
            OnMove();
        }
        //doMove();

        if (type == PieceType.KING)
        {
            return;
        }

        doKinging(ref board);
    }
예제 #4
0
    // Use this for initialization
    protected virtual void Start()
    {
        legalMovesForAPiece = new List <Vector2>();
        gameState           = new GameState(ChessGlobals.GameState.WHITE_TURN);

        //Initialize Model
        board = new Board();

        //Initialize Movement Model
        moveModel      = gameObject.AddComponent <MoveModel> ();
        capturedPieces = new List <Piece> ();

        //Initialize View
        //drawBoard.InitBoard();
        var startingPositions = drawPiece.InitPieces();

        for (int i = 0; i < startingPositions.t1.Count; ++i)
        {
            Piece blackPiece = CreatePieceAt(startingPositions.t1[i].t1, startingPositions.t1[i].t2, ChessGlobals.Teams.BLACK_TEAM);
            Piece whitePiece = CreatePieceAt(startingPositions.t2[i].t1, startingPositions.t2[i].t2, ChessGlobals.Teams.WHITE_TEAM);

            board.Mark(blackPiece.GetPiecePosition(), blackPiece);
            board.Mark(whitePiece.GetPiecePosition(), whitePiece);

            board.AddActivePiece(whitePiece);
            board.AddActivePiece(blackPiece);
        }
    }
예제 #5
0
 public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
 {
     for (int i = 0; i < moves.Count; i++)
     {
         MoveModel move = moves[i];
         if (move.Stats.Type != MoveType.Range && (move.attackTimeLeft <= 0 || move.Ended))
         {
             EndMove(move);
             RemoveMove(move);
         }
     }
     DebugWrite(playerIndex + "LOL", moves.Count);
     for (int i = 0; i < explotions.Count; i++)
     {
         Explotion explotion = explotions[i];
         explotion.TimeLeft -= gameTime.ElapsedGameTime.Milliseconds;
         if (explotion.TimeLeft <= 0)
         {
             explotion.Img.BoundBox.Dispose();
             explotions.Remove(explotion);
             i--;
         }
         else
         {
             explotion.Img.BoundBox.Dispose();
             explotion.Img.CurrentPos -= explotion.Size * explotion.TimeLeft / explotion.Duration / 2;
             explotion.Img.SetBoundBox(World, (int)MathHelper.Max((float)(explotion.TimeLeft / explotion.Duration * explotion.Size.X), 1), (int)MathHelper.Max((float)(explotion.TimeLeft / explotion.Duration * explotion.Size.Y), 1), Vector2.Zero, Category.Cat31, Category.Cat11, true);
             explotion.Img.BoundBox.IgnoreGravity = true;
             explotion.Img.BoundBox.IsStatic      = true;
             explotion.Img.BoundBox.UserData      = explotion;
             explotion.Img.BoundBox.OnCollision  += ExplodeHit;
         }
     }
 }
예제 #6
0
        public async Task PopulateMoveUsersAsync_FirstMove_NothingChanges()
        {
            var moves = new MoveModel[]
            {
                new MoveModel
                {
                    CardId    = 1,
                    Column    = 1,
                    Row       = 1,
                    StartTime = DateTime.UtcNow.AddMinutes(-10),
                    UserId    = 1,
                }
            };

            var cards = new CardModel[]
            {
                new CardModel
                {
                    Id = 1,
                }
            };

            var users = new int[]
            {
                1,
                2
            };

            var result = await _service.PopulateMoveUsersAsync(moves, cards, users, default);

            Assert.Single(result);
            Assert.Equal(1, result.First().UserId);
        }
예제 #7
0
        async Task IMoveValidator.ValidateMoveAsync(MoveModel move, GameModel game, CancellationToken cancellationToken)
        {
            var card = (await _gameDeckCardCollectionRepository.SearchAsync(
                            new GameDeckCardCollectionSearchFilter
            {
                Ids = new int[] { move.GameDeckCardCollectionId },
                UserId = move.UserId,
            }, cancellationToken: cancellationToken)).SingleOrDefault(x => x.Id == move.GameDeckCardCollectionId);

            if (card == null)
            {
                throw new InvalidCardException();
            }

            if (move.Row < 0 || move.Row >= game.Rows || move.Column < 0 || move.Column >= game.Columns)
            {
                throw new InvalidMoveException("Move must be made on the board.");
            }

            var moves = await _moveRepository.GetMovesByGameIdAsync(move.GameId, cancellationToken : cancellationToken);

            if (moves.Any(x => x.Row == move.Row && x.Column == move.Column))
            {
                throw new InvalidMoveException("There is already a card in this location.");
            }
        }
예제 #8
0
        public JsonResult Move(MoveModel model)
        {
            var response = this.GameService.Move(model.MazeId, (MoveType)model.Direction).ToMap();

            response.Data = this.GameService.Print(model.MazeId);
            return(this.Json(response, JsonRequestBehavior.AllowGet));
        }
예제 #9
0
    internal bool OnCheck()
    {
        if (_model.IsThinking)
        {
            return(false);
        }
        _borderimage.color = BorderHighlight;
        var moves = _tilemodel.GetMoves().OrderBy(m => m.NewPosition).ToList();

        if (moves.Count == 0)
        {
            _uimx.StatusText.text = (_tilemodel.PieceName == null) ? String.Format("{0}", _tilemodel.Name)
        : String.Format("{0} {1} on {2}", _tilemodel.PlayerName, _tilemodel.PieceName, _tilemodel.Name);
        }
        else
        {
            // in case we want to make this move
            _previewmove = moves[PickMove(moves.Count)];
            LoadPieceImage(PreviewObject, _previewmove.Player, _previewmove.Piece);
            if (_previewmove.IsDual)
            {
                _tilemodel.Board.SetPreview(_previewmove.Player, _previewmove.NewPosition, _previewmove.NewPiece);
            }
            _tileimage.color      = TileHighlight;
            _uimx.StatusText.text = _previewmove.Display;
            return(true);
        }
        _tileimage.color = TileNormal;
        return(false);
    }
예제 #10
0
        public ActionResult SendTransfer(MoveModel model)
        {
            try
            {
                //model.Locations = _locationService.GetLocations();
                //model.TransferComplete = _transferService.TransferOut(model.SelectedInventoryId, model.SelectedDepartureLocationId,
                //    model.SelectedArrivingLocationId, model.SelectedQuantity);

                //if (!model.TransferComplete.GetValueOrDefault())
                //{
                //    ModelState.AddModelError("GENERALERR-1", "Transfer Incomplete. General Error");
                //}

                //model.ItemsAtLocation =
                //    _inventoryService.GetAllLocationsWithProduct()
                //        .ToList();
                //model.SelectedQuantity = 0;
                return(View("Move", model));
            }
            catch (Exception e)
            {
                ModelState.AddModelError("CAUGHTERR-1", e.Message);
                model.TransferComplete = false;
                model.ItemsAtLocation  =
                    productService.GetLocationsWithProduct(model.SelectedInventoryId)
                    .Where(x => x.LocationId == model.SelectedDepartureLocationId)
                    .ToList();
                return(View("Move", model));
            }
        }
예제 #11
0
        public async Task MoveStep_WithCorrectModel_MustHaveMoveAStep()
        {
            //Arrange
            var stateManager      = new MockState().MockStateManager();
            var instance          = MockData.GetFlowInstances().FirstOrDefault();
            var flowManager       = new ManagerFactory().GetFlowManager(stateManager);
            var flowReportManager = new ManagerFactory().GetFlowReportManager(stateManager);
            var existTransitions  = await flowReportManager.GetInstanceTransitionsAsync(instance.Id);

            var targetTransition = existTransitions.Result.FirstOrDefault();

            var moveModel = new MoveModel()
            {
                IdentityId   = "1",
                InstanceId   = instance.Id,
                Payload      = string.Empty,
                TransitionId = targetTransition.Id,
                Comment      = "Sure, It's ok.",
            };
            //Act
            var act = await flowManager.MoveAsync(moveModel);

            var steps = await flowReportManager.GetInstanceStepsAsync(instance.Id);

            var currentStep = steps.Result.FirstOrDefault(x => x.IsCurrent);

            //Assert
            LogTestInfo(moveModel, act);
            Assert.True(act.Succeeded);
            Assert.NotNull(act.Result);
            Assert.Equal(moveModel.TransitionId, currentStep.TransitionId);
        }
예제 #12
0
        private async Task PlayCurrentRound()
        {
            if (_cancellationToken.IsCancellationRequested)
            {
                return;
            }
            if (PlayerOne.PlayerType != RockPaperScissors.Common.Enums.PlayerType.HumanPlayer)
            {
                _nextPlayerOneMove = PlayerOne.GetNextMove(Game.Rules);
            }
            MoveModel move = Game.Rules.MoveList.FirstOrDefault(i => i.RuleValue == _nextPlayerOneMove);
            string    nextPlayerOneMoveDescription = move.Description;


            if (PlayerTwo.PlayerType != RockPaperScissors.Common.Enums.PlayerType.HumanPlayer)
            {
                _nextPlayerTwoMove = PlayerTwo.GetNextMove(Game.Rules);
            }
            move = Game.Rules.MoveList.FirstOrDefault(i => i.RuleValue == _nextPlayerTwoMove);
            string nextPlayerTwoMoveDescription = move.Description;

            await TurnCountDown();

            if (_cancellationToken.IsCancellationRequested)
            {
                return;
            }
            PlayerOneChoice = nextPlayerOneMoveDescription;
            PlayerTwoChoice = nextPlayerTwoMoveDescription;
            DisplayWinningMove(_nextPlayerOneMove.Value, _nextPlayerTwoMove.Value);

            await DecideNextAction();
        }
예제 #13
0
        public bool MoveCard(string id, MoveModel model)
        {
            db_.RemoveCardFromList(id, model.DestinationId);
            db_.InsertCardIntoList(id, model.TargetId);

            return(true);
        }
예제 #14
0
        public void Get_XY_Coords_And_SrcDst_Pieces_From_Move_Input()
        {
            string    move = "d2d4";
            MoveModel mm   = val.GetMoveCoordsAndPiece(Game1, move);

            Assert.IsTrue(mm.xsrc == 100 && mm.ysrc == 50 && mm.xdst == 100 && mm.ydst == 52 && mm.srcval == " P" && mm.dstval == "  ");
        }
예제 #15
0
        private MoveModel ProcessMove(dynamic m)
        {
            var move    = ((dynamic)m).move;
            var newMove = new MoveModel();

            newMove.Name        = move.name.ToString();
            newMove.ResourceUri = move.url.ToString();

            var info = GetAdditionInfo(newMove.ResourceUri);

            if (info != null && info.Count > 0)
            {
                newMove.Id     = info.ContainsKey("id") ? int.Parse(info?["id"].ToString()) : 0;
                newMove.Damage = info.ContainsKey("power") && info?["power"] != null?int.Parse(info?["power"].ToString()) : 0;

                newMove.Category = info.ContainsKey("damage_class") && info?["damage_class"] != null ? ((ExpandoObject)info?["damage_class"]).First().Value.ToString() : string.Empty;
                newMove.Type     = info.ContainsKey("type") ? ((ExpandoObject)info?["type"]).First().Value.ToString() : string.Empty;
            }

            if (newMove.Type == null)
            {
                ProcessMove(m);
            }
            return(newMove);
        }
예제 #16
0
    public void ChangeModelType(Vector2 pos, string type, int team)
    {
        GameObject new_Model = null;

        if (type == "Rook")
        {
            new_Model = Instantiate(castle);
        }
        else if (type == "Bishop")
        {
            new_Model = Instantiate(bishop);
        }
        else if (type == "Queen")
        {
            new_Model = Instantiate(queen);
        }
        else if (type == "Knight")
        {
            new_Model = Instantiate(knight);
        }

        Material mat = firstTeam;

        if (team == Teams.BLACK_TEAM)
        {
            mat = secondTeam;
        }

        Vector3 newPos = new Vector3(pos.x + MODEL_OFFSET, MODEL_OFFSET_Y, pos.y + MODEL_OFFSET);

        Destroy(MoveModel.CheckAt(pos));
        new_Model.transform.position = newPos;
        new_Model.GetComponent <Renderer>().material = mat;
    }
예제 #17
0
        public async Task PopulateMoveUsersAsync_UsersNotMatchingMoves_ThrowsInvalidPlayerException()
        {
            var moves = new MoveModel[]
            {
                new MoveModel
                {
                    CardId    = 1,
                    Column    = 1,
                    Row       = 1,
                    StartTime = DateTime.UtcNow.AddMinutes(-10),
                    UserId    = 1
                }
            };

            var cards = new CardModel[]
            {
                new CardModel
                {
                    Id = 1,
                }
            };

            var users = new int[]
            {
            };

            await Assert.ThrowsAsync <InvalidPlayerException>(() => _service.PopulateMoveUsersAsync(moves, cards, users, default));
        }
예제 #18
0
        internal static PolyMove Create(int index, MoveModel move)
        {
            if (move == null)
            {
                return new PolyMove {
                           Index = index,
                }
            }
            ;
            if (move.IsPass)
            {
                return new PolyMove {
                           Index     = index, IsPass = true,
                           Player    = move.Player.Value,
                           Position1 = "", Piece1 = "", Position2 = "", Piece2 = "",
                           _move     = move,
                }
            }
            ;
            var mp     = move.MoveParts[0];
            var occup1 = mp.Kind == MoveKinds.Drop || mp.Kind == MoveKinds.Copy;
            var occup2 = mp.Final != null;

            return(new PolyMove {
                Index = index,
                Player = mp.Player.Value,
                Position1 = mp.Position.Value,
                Piece1 = occup1 ? mp.Piece.Value : "",
                Position2 = occup2 ? mp.Final.Value : "",
                Piece2 = occup2 ? mp.Piece.Value : "",
                _move = move,
            });
        }
    }
예제 #19
0
        public void UpdatePlayer(MoveModel move)
        {
            var playerId = Context.User.Identity.GetUserId();
            var game     = _gameManager.GetGame(playerId);

            game.UpdatePlayer(playerId, move, this);
        }
예제 #20
0
        /// <summary>
        /// Returns the ViewResult for use in the Move/Copy dialogs
        /// </summary>
        /// <returns></returns>
        protected ActionResult MoveCopyView(HiveId id, MoveModel model)
        {
            using (var uow = Hive.Create <IContentStore>())
            {
                var contentData = uow.Repositories.Get <TypedEntity>(id);
                if (contentData == null)
                {
                    throw new ArgumentException(string.Format("No content found for id: {0} on action Move/Copy", id));
                }

                //TODO: need to filter the start id based on the user's start node id, or just put that funcionality into the url helper

                //get the tree url for use in the copy/move dialog
                var treeUrl = Url.GetTreeUrl(new HiveId(_treeId), _treeId,
                                             new
                {
                    //specify that the tree is in dialog mode
                    DialogMode = true,
                    //specify the onClick JS method handler for the node
                    OnNodeClick = "Rebel.Editors.MoveCopyDialog.getInstance().nodeClickHandler"
                });

                var contentItem = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <TypedEntity, ContentEditorModel>(contentData);

                model.SelectedItemId   = contentItem.Id;
                model.SelectedItemName = contentItem.Name;
                model.TreeRenderModel  = new TreeRenderModel(treeUrl, "moveCopyTree")
                {
                    ShowContextMenu = false
                };
                return(View(model));
            }
        }
예제 #21
0
    void Update()
    {
        var forward = Input.GetAxis("Vertical");
        if (forward != 0f)
        {
            // create random move
            var randomShift = Random.insideUnitCircle * moveTolerance * Time.deltaTime;
            var shift = transform.forward*forward*moveSpeed*Time.deltaTime +
                        new Vector3(randomShift.x, 0f, randomShift.y);
            transform.position += shift;

            // shift map using move model when move is big enough
            moveAdd.shift += transform.forward * forward * moveSpeed * Time.deltaTime;
            moveAdd.tolerance += moveTolerance * Time.deltaTime;
            if (moveAdd.shift.sqrMagnitude >= 0.25)
            {
                map.OnMove(moveAdd);
                moveAdd = new MoveModel();
                GetComponent<DroidSound>().PlayRandom();
            }
        }
        var horizontal = Input.GetAxis("Horizontal");
        if (horizontal != 0f)
        {
            // rotate over y axis
            var yRotation = horizontal*Time.deltaTime * rotationSpeed;
            var euler = transform.rotation.eulerAngles;
            euler.y += yRotation;
            transform.rotation = Quaternion.Euler(euler);
        }
    }
        public ActionResult ChangeGroupForUsers(int formResultId, int groupId, int entId = -1)
        {
            MoveModel moveModel = new MoveModel(formResultId, formsRepo);

            moveModel.GetUsersByGroup(groupId, entId);

            return(View("MoveUser", moveModel));
        }
        public ActionResult ChangeEnterpriseForUsers(int formResultId, int entId)
        {
            MoveModel moveModel = new MoveModel(formResultId, formsRepo);

            moveModel.GetUsers(entId);

            return(View("MoveUser", moveModel));
        }
예제 #24
0
        public GameStateModel MakeMove(Guid id, [FromBody] MoveModel moveModel)
        {
            var player    = new Player(moveModel.Name);
            var move      = Move.GetMoveFromString(moveModel.Move);
            var gameState = _gameSupervisor.MakeMove(id, player, move);

            return(new GameStateModel(gameState));
        }
예제 #25
0
        public MoveModel newMove(MoveStats stats, bool right)
        {
            //foreach (MoveModel moveModel in moves) if (moveModel.Stats.Equals(stats)) return null;
            MoveModel move = new MoveModel(stats, right, playerIndex);

            moves.Add(move);
            return(move);
        }
예제 #26
0
        private void folders_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var    FolderContent = new FolderContent();
            string FolderTag     = ((System.Windows.FrameworkElement)folders.SelectedItem).Tag.ToString();

            MoveModel.SetDestinationDirectory(FolderTag);
            SelectedFolderContain.ItemsSource = FolderContent.GetAllFiles(FolderTag);
        }
예제 #27
0
        private async Task <GameModel> ValidateMoveInternalAsync(MoveModel move, CancellationToken cancellationToken = default)
        {
            var game = await _gameValidator.ValidateGameForMoveAsync(move.GameId, move.UserId, cancellationToken : cancellationToken);

            await _moveValidator.ValidateMoveAsync(move, game, cancellationToken : cancellationToken);

            return(game);
        }
예제 #28
0
        public JsonResult AutoMove(MoveModel model)
        {
            var response = this.RobotEngine.GotoNext(model.MazeId).ToMap();

            response.MazeId = model.MazeId;
            response.IsAuto = true;
            response.Data   = this.GameService.Print(model.MazeId);
            return(this.Json(response, JsonRequestBehavior.AllowGet));
        }
예제 #29
0
        private async void StartNewGame(object sender, RoutedEventArgs e)
        {
            //await httpService.GetEndpoitResponse("https://history-service.azurewebsites.net/api/StartNewGame?");
            MoveModel moveModel = new MoveModel();

            GameWindow gameWindow = new GameWindow();

            gameWindow.Show();
        }
예제 #30
0
        public ContentResult GetResults(Guid gameId, string username)
        {
            var game  = GameManager.GetGame(gameId);
            var model = new MoveModel {
                Game = GetNewGame(game), Username = username
            };

            model.ArrangeUsers(username);
            return(Content(model.ToJson(), "application/json"));
        }
예제 #31
0
    private List <Move> GetMovesMan(ref PieceModel[,] board)
    {
        // next steps here
        List <Move> moves = new List <Move>(2);

        int[] moveX = new int[] { -1, 1 };
        int   moveY = -1;

        if (color == PieceColor.BLACK)
        {
            moveY = 1;
        }
        foreach (int mX in moveX)
        {
            int nextX = x + mX;
            int nextY = y + moveY;

            if (!IsMoveInBounds(nextX, nextY, ref board))
            {
                continue;
            }
            PieceModel p = board[nextY, nextX];
            if (p != null && p.color == color)
            {
                continue;
            }
            MoveModel m = new MoveModel();
            m.piece = this;
            if (p == null)
            {
                m.x = nextX;
                m.y = nextY;
            }
            else
            {
                int hopX = nextX + mX;
                int hopY = nextY + moveY;
                Debug.Log(hopX + " " + hopY);
                if (!IsMoveInBounds(hopX, hopY, ref board))
                {
                    continue;
                }
                if (board[hopY, hopX] != null)
                {
                    continue;
                }

                m.x       = hopX;
                m.y       = hopY;
                m.capture = new Capture(nextX, nextY);
            }
            moves.Add(m);
        }
        return(moves);
    }
예제 #32
0
 // on move
 public void OnMove(MoveModel model)
 {
     //float time = Time.realtimeSinceStartup;
     // on move shift all particles in move direction
     ShiftParticles(model.shift);
     //time = Time.realtimeSinceStartup - time;
     //Debug.Log("ShiftParticles execution time: " + time);
     //time = Time.realtimeSinceStartup;
     // next weight all particles according to new scan data
     WeightParticles();
     //time = Time.realtimeSinceStartup - time;
     //Debug.Log("WeightParticles execution time: " + time);
     //time = Time.realtimeSinceStartup;
     // next recreate particles with a probabilities
     Resample(model.tolerance);
     //time = Time.realtimeSinceStartup - time;
     //Debug.Log("Resample execution time: " + time);
     // in the end start particles rerender
     StartCoroutine(minimap.ShowParticles(particlesMap.Particles));
 }
예제 #33
0
        //[RebelAuthorize(Permissions = new[] { FixedPermissionIds.Move })]  
        public virtual JsonResult MoveForm(MoveModel model)
        {
            if (!TryValidateModel(model))
            {
                return ModelState.ToJsonErrors();
            }

            return ProcessMoveCopy(model.SelectedItemId, model.ToId, (selectedEntity, toEntity, uow) =>
                {
                    var previousParents = uow.Repositories.GetParentRelations(selectedEntity, FixedRelationTypes.DefaultRelationType);
                    if (!previousParents.Any())
                        throw new InvalidOperationException(
                            "Could not find any parents for entity '{0}' with id {1}".InvariantFormat(
                                model.SelectedItemName, model.SelectedItemId));

                    // TODO: (APN) At the moment the MoveModel does not provide the single parent from which we're moving, 
                    // so we've had to load all parents. We need to change one, and remove the rest.
                    var toChange = previousParents.FirstOrDefault();
                    var rest = previousParents.Skip(1);
                    uow.Repositories.ChangeRelation(toChange, toEntity.Id, toChange.DestinationId);
                    rest.ForEach(x => uow.Repositories.RemoveRelation(x));

                    uow.Complete();

                    return new Tuple<string, EntityPathCollection, string>(
                        "Move.Success.Message".Localize(this, new
                            {
                                FromName = selectedEntity.GetAttributeValueAsString(NodeNameAttributeDefinition.AliasValue, "Name"),
                                ToName = toEntity.GetAttributeValueAsString(NodeNameAttributeDefinition.AliasValue, "Name")
                            }, encode: false),
                        uow.Repositories.GetEntityPaths<TypedEntity>(toChange.DestinationId, FixedRelationTypes.DefaultRelationType),
                        "move");

                });
        }
예제 #34
0
 public void AddMove(MoveModel model)
 {
     _moveModels.Add(model);
 }
예제 #35
0
 public MoveTableSelectionModel(MoveModel model) :
     this((ITableModel<Move>) model)
 {
 
 }
예제 #36
0
        /// <summary>
        /// Returns the ViewResult for use in the Move/Copy dialogs
        /// </summary>
        /// <returns></returns>
        protected ActionResult MoveCopyView(HiveId id, MoveModel model)
        {

            using (var uow = Hive.Create<IContentStore>())
            {
                var contentData = uow.Repositories.Get<TypedEntity>(id);
                if (contentData == null)
                    throw new ArgumentException(string.Format("No content found for id: {0} on action Move/Copy", id));

                //TODO: need to filter the start id based on the user's start node id, or just put that funcionality into the url helper

                //get the tree url for use in the copy/move dialog
                var treeUrl = Url.GetTreeUrl(new HiveId(_treeId), _treeId,
                                             new
                                                 {
                                                     //specify that the tree is in dialog mode
                                                     DialogMode = true,
                                                     //specify the onClick JS method handler for the node
                                                     OnNodeClick = "Rebel.Editors.MoveCopyDialog.getInstance().nodeClickHandler"
                                                 });

                var contentItem = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<TypedEntity, ContentEditorModel>(contentData);

                model.SelectedItemId = contentItem.Id;
                model.SelectedItemName = contentItem.Name;
                model.TreeRenderModel = new TreeRenderModel(treeUrl, "moveCopyTree")
                    {
                        ShowContextMenu = false
                    };
                return View(model);
            }
        }