public void Setup()
        {
            // Mock
            _configuration = new Mock <IConfiguration>(MockBehavior.Loose);
            _actionRepo    = new Mock <IActionRepo>(MockBehavior.Loose);
            _logger        = new Mock <ILogger <ActionController> >(MockBehavior.Loose);

            // Mapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperConfig());
            });

            _mapper = new Mapper(config);

            // Config
            Filler <Action>    pFiller    = new Filler <Action>();
            Filler <ActionDTO> pFillerDTO = new Filler <ActionDTO>();

            action    = pFiller.Create();
            actionDTO = pFillerDTO.Create();

            // Service under test
            _actionController = new ActionController(_configuration.Object, _mapper, _actionRepo.Object, _logger.Object);
        }
Esempio n. 2
0
        /// <summary>
        /// Récupère un role et une liste d'action selon leurs id.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roles"></param>
        public Tuple <RoleDTO, List <ActionDTO> > Get_Role_And_Actions_By_Ids(int id, string[] actions)
        {
            RoleDTO role = roleEngine.Get_By_ID(id);

            if (actions != null)
            {
                try
                {
                    List <ActionDTO> roleActions = new List <ActionDTO>();

                    foreach (string stringIdAction in actions)
                    {
                        int idAction;
                        if (int.TryParse(stringIdAction, out idAction))
                        {
                            ActionDTO action = actionLogic.Get_By_Id(idAction);
                            roleActions.Add(action);
                        }
                    }
                    return(new Tuple <RoleDTO, List <ActionDTO> >(role, roleActions));
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                return(new Tuple <RoleDTO, List <ActionDTO> >(role, null));
            }
        }
        public IActionResult Get(Guid id)
        {
            var       action    = _actionRepository.GetActionByID(id);
            ActionDTO actionDTO = _mapper.Map <ActionDTO>(action);

            return(new OkObjectResult(actionDTO));
        }
        private ActionDTO SimplifyOperations(IGrouping <int, ActionDTO> g)
        {
            ActionDTO result;

            if (g.Any(a => a.ActionType == ActionType.Delete && g.Key > 0))
            {
                result = new ActionDTO {
                    Id = g.Key, ActionType = ActionType.Delete
                }
            }
            ;
            else if (g.Any(a => a.ActionType == ActionType.Add && g.Key < 0))
            {
                var last = g.LastOrDefault(a => a.ActionType == ActionType.Modify);
                result = new ActionDTO {
                    Id = g.Key, ActionType = ActionType.Add, Text = last?.Text, Date = last?.Date
                };
            }
            else if (g.Key > 0)
            {
                var last = g.Last(a => a.ActionType == ActionType.Modify);
                result = new ActionDTO {
                    Id = g.Key, ActionType = ActionType.Modify, Text = last.Text, Date = last.Date
                };
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            return(result);
        }
Esempio n. 5
0
        public async Task AddAction()
        {
            var client = new ActionDTO
            {
                SellerId = 2,
                ClientId = 2,
                Message  = "test message2"
            };

            var json = JsonConvert.SerializeObject(client);


            var handleRequest = await httpClient.PostAsync("http://localhost:50555/api/Action",
                                                           new StringContent(json, Encoding.UTF8, "application/json"));

            Assert.True(handleRequest.StatusCode == System.Net.HttpStatusCode.Created);

            var response = await httpClient.GetAsync("http://localhost:50555/api/Action");

            var jsonContent = response.Content.ReadAsStringAsync().Result;
            var result      = JsonConvert.DeserializeObject <List <ActionDTO> >(jsonContent);
            var newSeller   = result.Single(a => a.ID == 2);


            Assert.True(response.StatusCode == System.Net.HttpStatusCode.OK);
            Assert.AreEqual(2, newSeller.ID);
            Assert.AreEqual(2, newSeller.SellerId);
            Assert.AreEqual(2, newSeller.ClientId);
            Assert.AreEqual("test message2", newSeller.Message);
            Assert.AreEqual(DateTime.Now.Day, newSeller.MessageDate.Day);

            // Assert.AreEqual(1, result.TypeId);
        }
Esempio n. 6
0
        public ActionResult Create(ActionDTO action)
        {
            MethodBase method = MethodBase.GetCurrentMethod();

            try
            {
                Action newAction = Mapper.Map <Action>(action);
                newAction.IsValid = true;
                newAction.Id      = 0;
                var response = ActionRepo.Create(newAction);
                if (response > 0)
                {
                    CreateLog(Enums.Success, GetMethodCode(method), LogLevel.Information);
                    return(Ok(response));
                }
                else
                {
                    CreateLog(Enums.BadRequest, GetMethodCode(method), LogLevel.Warning);
                    return(BadRequest(response));
                }
            }
            catch (Exception ex)
            {
                return(HandleError(ex.Message, GetMethodCode(method)));
            }
        }
Esempio n. 7
0
 public List <ActionDTO> GetActions()
 {
     using (IDbSvc dbSvc = new DbSvc(_configSvc))
     {
         try
         {
             dbSvc.OpenConnection();
             MySqlCommand command = new MySqlCommand();
             command.CommandText = "select ActionId,ActionName from dic_action where Active=1";
             command.Connection  = dbSvc.GetConnection() as MySqlConnection;
             _dtData             = new DataTable();
             MySqlDataAdapter msDa = new MySqlDataAdapter(command);
             msDa.Fill(_dtData);
             List <ActionDTO> lstAction = new List <ActionDTO>();
             if (_dtData != null && _dtData.Rows.Count > 0)
             {
                 ActionDTO actionDTO = null;
                 foreach (DataRow dr in _dtData.Rows)
                 {
                     actionDTO            = new ActionDTO();
                     actionDTO.RowId      = (int)dr["ActionId"];
                     actionDTO.ActionName = dr["ActionName"].ToString();
                     lstAction.Add(actionDTO);
                 }
             }
             return(lstAction);
         }
         catch (Exception exp)
         {
             throw exp;
         }
     }
 }
Esempio n. 8
0
        public void AddAction(IAction Action)
        {
            ActionDTO adto = new ActionDTO()
            {
                Name  = Action.Name,
                Scene = Action.Scene
            };

            sc.Actions.Add(adto);
        }
        private ActionDTO MapActionToDto(Action action)
        {
            var dto = new ActionDTO();

            dto.Id   = action.Id;
            dto.Name = action.Name;
            dto.GeneralDescription = action.GeneralDescription;

            return(dto);
        }
Esempio n. 10
0
 private static ActionModel GenereazaActionModelView(ActionDTO action)
 {
     return(new ActionModel()
     {
         Id = action.Id,
         DateForAction = action.DateForAction,
         _ActionType = (ActionTypeWeb)action._ActionType,
         Money = action.Money
     });
 }
Esempio n. 11
0
 public void adaugaAction(ActionDTO action)
 {
     if (action != null)
     {
         _ActionType   = action._ActionType;
         Money         = action.Money;
         DateForAction = action.DateForAction;
         Id            = action.Id;
     }
 }
Esempio n. 12
0
        public void AddDirection(ILocation Location, Object callback = null, bool CopyToAction = false)
        {
            String       id          = null;
            CallbackDTO  cdo         = new CallbackDTO();
            PropertyInfo Name        = null;
            PropertyInfo Description = null;

            if (callback != null)
            {
                Description = callback.GetType().GetProperty("Description");
                var t = callback.GetType().GetProperty("t");
                var c = callback.GetType().GetProperty("c");
                Name = callback.GetType().GetProperty("Name");

                if (c != null)
                {
                    id               = Guid.NewGuid().ToString("N");
                    cdo.c            = (Action)c.GetValue(callback, null);
                    cdo.Scene        = Location.Scene;
                    cdo.CurrentScene = data.CurrentScene;
                }
                if (t != null)
                {
                    id               = Guid.NewGuid().ToString("N");
                    cdo.t            = Convert.ToInt32(t.GetValue(callback, null).ToString());
                    cdo.Scene        = Location.Scene;
                    cdo.CurrentScene = data.CurrentScene;
                }
                if (id != null)
                {
                    sc.Callbacks.Add(id, cdo);
                }
            }

            DirectionDTO ddt = new DirectionDTO()
            {
                id          = id,
                Name        = (Name != null) ? Name.GetValue(callback, null).ToString() : Location.Name,
                Description = (Description != null) ? Description.GetValue(callback, null).ToString() : Location.Description,
                Scene       = Location.Scene
            };

            sc.Directions.Add(ddt);
            if (CopyToAction)
            {
                ActionDTO adto = new ActionDTO()
                {
                    id          = id,
                    Name        = (Name != null) ? Name.GetValue(callback, null).ToString() : Location.Name,
                    Description = (Description != null) ? Description.GetValue(callback, null).ToString() : Location.Description,
                    Scene       = Location.Scene
                };
                sc.Actions.Add(adto);
            }
        }
        /// <summary>
        /// Applies the move to the board. If there are mandatory moves it returns a list containing it.
        /// If the turn is over, it returns a turnDTO with an empty list of moves
        /// </summary>
        /// <param name="gameId"></param>
        /// <param name="move"></param>
        /// <returns></returns>
        public static OutgoingMessage TakeTurn(Guid gameId, ActionDTO action)
        {
            //---Apply Move---
            Game game = GameRepository.Instance.getGame(gameId);
            Move move = new Move()
            {
                MoveTo = action.moveTo,
                Piece  = game.board.Get(action.moveFrom.Item1, action.moveFrom.Item2)
            };
            bool isKingBefore = move.Piece.IsKing;

            if (!AvailableMoveService.GetMoves(game.board, game.turn).Contains(move))
            {
                throw new ArgumentOutOfRangeException("Invalid move");
            }

            game.board.ApplyMove(move);

            //---Check for Game Over---
            if (AvailableMoveService.IsGameOver(game.board))
            {
                return(new EndGameDTO()
                {
                    reason = EndReason.GAME_OVER,
                    winner = AvailableMoveService.GetWinner(game.board)
                });
            }

            //---Check for forced jump moves---
            var  jumpMoves   = new List <Move>();
            var  to          = action.moveTo;
            var  loc         = action.moveFrom;
            bool isKingAfter = game.board.Get(to.Item1, to.Item2).IsKing;

            if (Math.Abs(loc.Item1 - to.Item1) == 2 &&
                Math.Abs(loc.Item2 - to.Item2) == 2 &&
                !(isKingBefore != isKingAfter))
            {
                jumpMoves = AvailableMoveService.GetJumpMoves(game.board, game.board.Get(to.Item1, to.Item2));
            }

            if (jumpMoves.Count == 0)
            {
                game.turn = (game.turn == Player.BLACK) ? Player.RED : Player.BLACK;
            }

            GameRepository.Instance.update(gameId, game);

            return(new TurnDTO()
            {
                board = game.board,
                moves = jumpMoves
            });
        }
Esempio n. 14
0
        // פעולה המציגה את המסך למשתמש
        public override void Show()
        {
            try
            {
                base.Show();                                                                    // ניקיון המסך והצגת הכותרת
                Task <ActionTypeDTO> actionTypeTask = UIMain.api.GetActionTypeAsync("Playing"); // בניית אוביקט הפעולה
                Console.WriteLine("May take a few seconds...");
                actionTypeTask.Wait();
                ActionTypeDTO actionType = actionTypeTask.Result;

                Task <List <ActionDTO> > actionListTask = UIMain.api.GetActionsListAsync(actionType);
                Console.WriteLine("May take a few seconds...");
                actionTypeTask.Wait();
                List <ActionDTO> actionList = actionListTask.Result;

                List <object> listActions = actionList.ToList <object>();            // קבלת הפעולות שניתן לבצע על החיה לתוך רשימה
                ObjectsList   objList     = new ObjectsList("Actions", listActions); // בניית טבלת פעולות שניתן לבצע על החיה
                objList.Show();                                                      // הצגת הפעולות שניתן לבצע לחיה למשתמש
                Console.WriteLine();

                // קליטה מהמשתמש את הפעולה אותה הוא רוצה לבצע לחיה
                Console.WriteLine("Choose what do you want to play with your tamagotchi: ");
                int       id     = int.Parse(Console.ReadLine());
                ActionDTO action = actionList.Where(p => p.ActionId == id).FirstOrDefault();

                // מסננת קלט לבדוק שבאמת חזרה פעולה
                while (action == null)
                {
                    Console.WriteLine("The id is invalid! Please type again: ");
                    id     = int.Parse(Console.ReadLine());
                    action = actionList.Where(p => p.ActionId == id).FirstOrDefault();
                }

                Task <bool> playTask = UIMain.api.PlayWithAnimalAsync(action);
                Console.WriteLine("Your animal is playing, please wait a few seconds...");
                playTask.Wait();
                bool play = playTask.Result;

                if (play)
                {
                    Console.WriteLine("Action managed successfully!");
                }
                else
                {
                    Console.WriteLine("OOps, something went wrong...");
                }
                Console.ReadKey();
            }

            catch (Exception e)
            {
                Console.WriteLine($"Fail with error: {e.Message}!");
            }
        }
Esempio n. 15
0
        public async Task <ActionDTO> UnpauseServer(string idServer)
        {
            var payload = new ActionDTO
            {
                Unpause = 1
            };

            var action = await HttpClientPostActionComputeApi <ActionDTO>(_configuration, "servers/" + idServer + "/action", "unpause", payload);

            return(action);
        }
Esempio n. 16
0
 public bool makeTransaction(ActionDTO action)
 {
     if (action._ActionType == ActionType.Deposit)
     {
         return(this.deposit(action.Money));
     }
     else
     {
         return(this.withdraw(action.Money));
     }
 }
Esempio n. 17
0
        // return Action List
        public SelectList getActionLinkDropDown()
        {
            List <ActionDTO> lactionDto = _ddlRepo.GetActions();

            ActionDTO actDto = new ActionDTO();

            actDto.RowId      = -1;
            actDto.ActionName = string.Empty;

            lactionDto.Insert(0, actDto);

            return(new SelectList(lactionDto, "RowId", "ActionName"));
        }
Esempio n. 18
0
        public async Task <ServerDTO> StopServer(string idServer)
        {
            var payload = new ActionDTO
            {
                OsStop = 1
            };

            var action = await HttpClientPostActionComputeApi <ActionDTO>(_configuration, "servers/" + idServer + "/action", "os-stop", payload);

            var server = await HttpClientGetComputeApi <ServerDTO>(_configuration, "servers/" + idServer, "server");

            return(server);
        }
        private void SetActinList(DatabaseObjectCategory entity)
        {
            var actions           = SecurityHelper.GetActionsByCategory(DatabaseObjectCategory.Column);
            List <ActionDTO> list = new List <ActionDTO>();

            foreach (var action in actions)
            {
                ActionDTO item = new ActionDTO();
                item.Action = action;
                list.Add(item);
            }

            dtgRoleActions.ItemsSource = list;
        }
        void ucObjectList_ObjectSelected(object sender, ObjectSelectedArg e)
        {
            Object = e.Object;
            var actions           = SecurityHelper.GetActionsByCategory(Object.ObjectCategory);
            List <ActionDTO> list = new List <ActionDTO>();

            foreach (var action in actions)
            {
                ActionDTO item = new ActionDTO();
                item.Action = action;
                list.Add(item);
            }
            dtgRoleActions.ItemsSource = list;
            GetMessage();
        }
Esempio n. 21
0
        public async Task <ServerDTO> RebootServer(string idServer)
        {
            var payload = new ActionDTO
            {
                Reboot = new RebootDTO
                {
                    Type = "HARD"
                }
            };

            var action = await HttpClientPostActionComputeApi <ActionDTO>(_configuration, "servers/" + idServer + "/action", "reboot", payload);

            var server = await HttpClientGetComputeApi <ServerDTO>(_configuration, "servers/" + idServer, "server");

            return(server);
        }
Esempio n. 22
0
 public ActionResult Deposit(Guid id, string s)
 {
     if (Session["UserID"] != null)
     {
         float     sumToDeposit = Convert.ToInt64(Request["txtAmount"].ToString());
         ActionDTO action       = new ActionDTO()
         {
             Money         = sumToDeposit,
             DateForAction = DateTime.Now,
             _ActionType   = PSSC.Models.ActionType.Deposit,
             Id            = Guid.NewGuid()
         };
         _writeRepo.adaugaAction(action, id, Session["Username"].ToString());
     }
     return(RedirectToAction("ShowAccounts"));
 }
Esempio n. 23
0
        public void depositMoney()
        {
            Cont cont = new Cont(new ContDTO()
            {
                AccountNumber  = "ROSDSNASD29121",
                MoneyDeposited = 300,
                Currency       = "RON",
            });

            ActionDTO action = new ActionDTO()
            {
                _ActionType = ActionType.Deposit,
                Money       = 400
            };

            Assert.IsTrue(cont.makeTransaction(action));
        }
        // Mappers
        private IndividualPlanDTO MapIndividualPlanWithActionsToDto(IndividualPlan plan, List <AgreedClientAction> actions)
        {
            var actionsForDays = new List <AgreedActionsForDayDTO>();

            var actionsGrouped = actions.GroupBy(a => a.Day);

            foreach (var group in actionsGrouped)
            {
                var day           = group.Key;
                var actionsForDay = new AgreedActionsForDayDTO();
                actionsForDay.Day = day;

                var actionsDtos = new List <AgreedActionBasicDTO>();
                foreach (var action in group)
                {
                    var agreedActionDto = new AgreedActionBasicDTO();
                    agreedActionDto.Id = action.Id;
                    agreedActionDto.EstimatedDurationMinutes        = action.EstimatedDurationMinutes;
                    agreedActionDto.ClientActionSpecificDescription = action.ClientActionSpecificDescription;
                    agreedActionDto.PlannedStartTime = DateTime.Today.Add(action.PlannedStartTime);
                    agreedActionDto.PlannedEndTime   = DateTime.Today.Add(action.PlannedStartTime.Add(TimeSpan.FromMinutes(action.EstimatedDurationMinutes)));

                    var actionDto = new ActionDTO();
                    actionDto.Id = action.ActionId;
                    actionDto.GeneralDescription = action.Action.GeneralDescription;
                    actionDto.Name = action.Action.Name;

                    agreedActionDto.Action = actionDto;
                    actionsDtos.Add(agreedActionDto);
                }

                actionsDtos = actionsDtos.OrderBy(a => a.PlannedStartTime).ToList();
                actionsForDay.AgreedActions = actionsDtos.ToArray();
                actionsForDays.Add(actionsForDay);
            }

            var planDto = new IndividualPlanDTO();

            planDto.Id            = plan.Id;
            planDto.ValidFrom     = plan.ValidFromDate;
            planDto.ValidUntil    = plan.ValidUntilDate;
            planDto.ActionsForDay = actionsForDays.ToArray();

            return(planDto);
        }
        public async Task <bool> PlayWithAnimalAsync(ActionDTO action)
        {
            string              json     = JsonSerializer.Serialize(action);
            StringContent       content  = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await this.client.PostAsync($"{this.baseUri}/PlayWithAnimal", content);

            if (response.IsSuccessStatusCode)
            {
                JsonSerializerOptions options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };
                string res = await response.Content.ReadAsStringAsync();

                return(JsonSerializer.Deserialize <bool>(res, options));
            }
            return(false);
        }
Esempio n. 26
0
        public void AddDynamicAction(Object Action, bool IsDynamic = false)
        {
            var          Description = Action.GetType().GetProperty("Description");//.GetValue(Action, null).ToString();
            var          t           = Action.GetType().GetProperty("t");
            var          c           = Action.GetType().GetProperty("c");
            var          LoadLast    = Action.GetType().GetProperty("LoadLast");
            String       id          = null;
            CallbackDTO  cdo         = new CallbackDTO();
            PropertyInfo Scene       = Action.GetType().GetProperty("Scene");

            if (c != null)
            {
                id                 = Guid.NewGuid().ToString("N");
                cdo.c              = (Action)c.GetValue(Action, null);
                cdo.Scene          = (Scene == null) ? data.CurrentScene : Scene.GetValue(Action, null).ToString();
                cdo.CurrentScene   = data.CurrentScene;
                cdo.IsDynamicScene = IsDynamic;
            }
            if (LoadLast != null && (Boolean)LoadLast.GetValue(Action, null) == true)
            {
                cdo.LoadLast = LastCallBack;
            }
            if (t != null)
            {
                id               = Guid.NewGuid().ToString("N");
                cdo.t            = Convert.ToInt32(t.GetValue(Action, null).ToString());
                cdo.Scene        = (Scene == null) ? data.CurrentScene : Scene.GetValue(Action, null).ToString();
                cdo.CurrentScene = data.CurrentScene;
            }
            if (id != null)
            {
                sc.Callbacks.Add(id, cdo);
            }

            ActionDTO adto = new ActionDTO()
            {
                id          = id,
                Name        = Action.GetType().GetProperty("Name").GetValue(Action, null).ToString(),
                Scene       = (Scene == null) ? data.CurrentScene : Scene.GetValue(Action, null).ToString(),
                Description = (Description == null) ? "" : Description.GetValue(Action, null).ToString()
            };

            sc.Actions.Add(adto);
        }
Esempio n. 27
0
        private bool SalvareActionInLista(ActionDTO action, Guid id, string username)
        {
            List <Client> allClients = new List <Client>();

            allClients = IncarcaListaDeClienti();

            var account = allClients.Find(x => x.Username == username).myAccounts.Find(x => x.Id == id);

            if (account.makeTransaction(action))
            {
                account.adaugaActiune(action);
                SalvareClientInListaClienti(allClients);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 28
0
        public ActionResult Withdraw(Guid id, string s)
        {
            bool ok = true;

            if (Session["UserID"] != null)
            {
                float     sumToWithdraw = Convert.ToInt64(Request["txtAmount"].ToString());
                ActionDTO action        = new ActionDTO()
                {
                    Money         = sumToWithdraw,
                    DateForAction = DateTime.Now,
                    _ActionType   = PSSC.Models.ActionType.Withdraw,
                    Id            = Guid.NewGuid()
                };
                ok = _writeRepo.adaugaAction(action, id, Session["Username"].ToString());
            }
            if (!ok)
            {
                ViewBag.Message = "Not enough money to withdraw in this account";
                return(View("ShowAccounts"));
            }
            return(RedirectToAction("ShowAccounts"));
        }
Esempio n. 29
0
        public async Task onMove(string move_resonse)
        {
            var response = GameManagerService.TakeTurn(gameId, ActionDTO.Deserialize(move_resonse));

            if (response is EndGameDTO)
            {
                var casted_response = (EndGameDTO)response;
                await Clients.Clients(Context.ConnectionId, OpponentId)
                .SendAsync("gameEnd", casted_response.Serialize());
            }
            else
            {
                var casted_response = (TurnDTO)response;
                if (casted_response.moves.Count != 0)
                {
                    await Clients.Caller.SendAsync("yourMove", casted_response.Serialize());
                }
                else
                {
                    await Clients.Client(OpponentId)
                    .SendAsync("yourMove", GameManagerService.StartTurn(gameId, OpponentColor).Serialize());
                }
            }
        }
Esempio n. 30
0
        public ActionResult Delete(ActionDTO action)
        {
            MethodBase method = MethodBase.GetCurrentMethod();

            try
            {
                if (action.Id > 0)
                {
                    Action delAction = Mapper.Map <Action>(action);
                    ActionRepo.Delete(delAction);
                    CreateLog(Enums.Success, GetMethodCode(method), LogLevel.Information);
                    return(Ok(true));
                }
                else
                {
                    CreateLog(Enums.BadRequest, GetMethodCode(method), LogLevel.Information);
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                return(HandleError(ex.Message, GetMethodCode(method)));
            }
        }